Search completed in 1.22 seconds.
7857 results for "low":
Your results are loading. Please wait...
Flow Layout and Overflow - CSS: Cascading Style Sheets
when there is more content than can fit into a container, an overflow situation occurs. understanding how overflow behaves is important in dealing with any element with a constrained size in css. this guide explains how overflow works when working with normal flow. what is overflow? ...
... when there is more content than can fit into a container, an overflow situation occurs. understanding how overflow behaves is important in dealing with any element with a constrained size in css. this guide explains how overflow works when working with normal flow. what is overflow? ...
.... understanding how overflow behaves is important in dealing with any element with a constrained size in css. this guide explains how overflow works when working with normal flow. what is overflow? ...
...And 16 more matches
In Flow and Out of Flow - CSS: Cascading Style Sheets
in the previous guide i explained block and inline layout in normal flow. all elements that are in flow, will be laid out using this method. in the following example i have a heading, paragraph, a list and a final paragraph which contains a strong element. the heading and paragraphs are block level, the strong element inline. the list is displayed using flexbox to arrange the items into a row, however it too is participating in block and inline layout - the container has an outside display type of block. all of the elements can be said to be in flow. appearing on the page in the order that they are in the source. ...
...element. the heading and paragraphs are block level, the strong element inline. the list is displayed using flexbox to arrange the items into a row, however it too is participating in block and inline layout - the container has an outside display type of block. all of the elements can be said to be in flow. appearing on the page in the order that they are in the source. ...
...aragraphs are block level, the strong element inline. the list is displayed using flexbox to arrange the items into a row, however it too is participating in block and inline layout - the container has an outside display type of block. all of the elements can be said to be in flow. appearing on the page in the order that they are in the source. ...
...And 7 more matches
Reason: Multiple CORS header 'Access-Control-Allow-Origin' not allowed - HTTP
reason reason: multiple cors header ‘access-control-allow-origin’ not allowed what went wrong? more than one access-control-allow-origin header was sent by the server. this isn't allowed. if you have access to the server you can change your implementation to echo back an origin in the access-control-allow-origin header. you cannot send back a list of origins, because browsers only accept a value that is either a single origin or null ...
Table Reflow Internals - Archive of obsolete content
overview review of reflow table frames table reflow intro to paginated reflow table paginated reflow review of reflow reflow process starts when an html document starts loading (the frame tree contains only viewport, scroll(s), canvas, html, body). the initial chunk of an xml doc is loaded. the initial chunk of an html doc (or a subsequent chunk of an xml doc) is loaded. the container posts a dirty reflow command with itself as the target. content is inserted, appended, or deleted through the dom. the container posts a dirty reflow command with itself as the target. style changes through the dom - javascript, browser change font (ctrl+/-), a preference changes, etc. ...
... the initial chunk of an html doc (or a subsequent chunk of an xml doc) is loaded. the container posts a dirty reflow command with itself as the target. content is inserted, appended, or deleted through the dom. the container posts a dirty reflow command with itself as the target. style changes through the dom - javascript, browser change font (ctrl+/-), a preference changes, etc. review of reflow reflow starts with pres shell which reflows the reflow root (usually the viewport frame), which reflows it children, etc. ususally it starts when the pres shell processes its queue of reflow commands. ...
...container posts a dirty reflow command with itself as the target. style changes through the dom - javascript, browser change font (ctrl+/-), a preference changes, etc. review of reflow reflow starts with pres shell which reflows the reflow root (usually the viewport frame), which reflows it children, etc. ususally it starts when the pres shell processes its queue of reflow commands. the reflower positions reflowee (if it can) before actually reflowing in case views are involved (e.g. ...
...And 45 more matches
Notes on HTML Reflow - Archive of obsolete content
the html formatting objects are called frames : a frame corresponds to the geometric information for (roughly) a single element in the content model; the frames are arranged into a hierarchy that parallels the containment hierarchy in the content model. a frame is rectangular, with width, height, and an offset from the parent frame that contains it. more than one frame may be needed to represent a single element from the content model; for example, text that wraps is broken into several frames, one per wrapped line. ...
...arent frame that contains it. more than one frame may be needed to represent a single element from the content model; for example, text that wraps is broken into several frames, one per wrapped line. in this case, the primary frame is the frame containing the first line of text, with continuing frames (or continuations ) created for subsequent lines. html uses a flow based layout model, meaning that most of the time it is possible to compute the geometry in a single pass. elements later "in the flow" typically do not affect the geometry of elements that are earlier "in the flow", so layout can proceed left-to-right, top-to-bottom through the document. there are exceptions to this rule: most notably, html tables may require more than one pass. the xul box la...
...e exceptions to this rule: most notably, html tables may require more than one pass. the xul box layout model, on the other hand, is constraint based , meaning that geometric preferences and constraints of neighboring elements are taken into consideration before the elements' final geometry can be computed. the box is the geometric primitive for the xul layout model. ...
...And 33 more matches
overflow-inline - CSS: Cascading Style Sheets
values visible content is not clipped and may be rendered outside the padding box's inline start and end edges. ...
... values visible content is not clipped and may be rendered outside the padding box's inline start and end edges. ...
... values visible content is not clipped and may be rendered outside the padding box's inline start and end edges. ...
...And 20 more matches
overflow-block - CSS: Cascading Style Sheets
values visible content is not clipped and may be rendered outside the padding box's block start and block end edges. ...
... values visible content is not clipped and may be rendered outside the padding box's block start and block end edges. ...
... values visible content is not clipped and may be rendered outside the padding box's block start and block end edges. ...
...And 19 more matches
overflow - CSS: Cascading Style Sheets
Web › CSS › overflow
the overflow css shorthand property sets the desired behavior for an element's overflow — i.e. when an element's content is too big to fit in its block formatting context — in both directions. 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. ...
......
... overflow-x overflow-y syntax /* keyword values */ overflow: visible; overflow: hidden; overflow: clip; overflow: scroll; overflow: auto; overflow: hidden visible; /* global values */ overflow: inherit; overflow: initial; overflow: unset; the overflow property is specified as one or two keywords chosen from the list of values below. if two keywords are specified, the first applies to overflow-x and the second to overflow-y. otherwise, both overflow-x and overflow-y are set to the same value. values visible content is not clipped and may be rendered outside the padding box. hidden content is clipped if necessary to fit the padding box. no scrollbars are provided, and no support for allowing the user to scroll (such as by dragging or using a scroll wheel) is allowed. the content ...
...And 15 more matches
text-overflow - CSS: Cascading Style Sheets
the text-overflow css property sets how hidden overflow content is signaled to users. it can be clipped, display an ellipsis ('…'), or display a custom string. 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 text-overflow property doesn't force an overflow to occur. to make text overflow its container you have to set other css properties: overflow and white-space. for example: overflow: hidden; white-space: nowrap; the text-overflow property only affects content that is overflowing a block container element in its inline progression direction (not text overflowing at the bottom of a box, for example). synt...
...sn't force an overflow to occur. to make text overflow its container you have to set other css properties: overflow and white-space. for example: overflow: hidden; white-space: nowrap; the text-overflow property only affects content that is overflowing a block container element in its inline progression direction (not text overflowing at the bottom of a box, for example). syntax the text-overflow property may be specified using one or two values. if one value is given, it specifies overflow behavior for the end of the line (the right end for left-to-right text, the left end for right-to-left text). if two values are given, the first specifies overflow behavior for the left end of the line, and the second specifies it for the right end of the line. each value is specified as one of: on...
...values: clip, ellipsis, fade the function fade(), which is passed a <length> or a <percentage> to control the fade distance a <string>. values clip the default for this property. this keyword value will truncate the text at the limit of the content area, therefore the truncation can happen in the middle of a character. to clip at the transition between characters you can specify text-overflow as an empty string, if that is supported in your target browsers: text-overflow: '';. ellipsis this keyword value will display an ellipsis ('…', u+2026 horizontal ellipsis) to represent clipped text. the ellipsis is displayed inside the content area, decreasing the amount of text displayed. if there is not enough space to display the ellipsis, it is clipped. <string> the <string> to be us...
...And 15 more matches
Overflowing content - Learn web development
previous overview: building blocks next overflow is what happens when there is too much content to fit in a container. in this guide you will learn what overflow is and how to manage 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 understand overflow and how to manage it. what is overflow? everything in css is a box. you can constrain the size of these boxes by assigning values of width and height (or inline-size and block-size). overflow happens when there is too much content to fit in a box. css provides various tools to manage overflow. as you go further with css layout an...
... the second example is a word in a box. ...
... the second example is a word in a box. the box has been made too small for the word and so it breaks out of the box. ...
...And 14 more matches
Debugging Frame Reflow
general overview the frame reflow can be logged with the debug capabilities implemented in nsframe.cpp. it provides the following information for each frame at the start of its reflow reflow reason available width, available height computed width, computed height the previous and the next frame in flow and a count number. when the frame's reflow is finished the following information is displayed : reflow metric (desired) width, height max. element width maximum width frame status overflow area getting the log make sure that your build is a debug build (in short you need ac_add_options --enable-debug in your .mozconfig file). create a text file (for instance reflow_rules.txt). enter this line in the text file * 1 this should look like: point ...
... run the debug build, saving stdout to a file. ...
... run the debug build, saving stdout to a file. ...
...And 14 more matches
Debugging Table Reflow
reflow the most efficient tool to claim that html-table code is the victim and not the source of layout bugs is a frame reflow debug log. look there especially how the maxelementsize (mes) and desired size are propagated. block reflow another way to debug the reflow process is implemented inside nsblockframe.cpp. ...
... reflow the most efficient tool to claim that html-table code is the victim and not the source of layout bugs is a frame reflow debug log. look there especially how the maxelementsize (mes) and desired size are propagated. block reflow another way to debug the reflow process is implemented inside nsblockframe.cpp. ...
... the most efficient tool to claim that html-table code is the victim and not the source of layout bugs is a frame reflow debug log. look there especially how the maxelementsize (mes) and desired size are propagated. block reflow another way to debug the reflow process is implemented inside nsblockframe.cpp. ...
...And 12 more matches
Access-Control-Allow-Origin - HTTP
attempting to use the wildcard with credentials will result in an error. <origin> specifies an origin. only a single origin can be specified. ...
...attempting to use the wildcard with credentials will result in an error. <origin> specifies an origin. only a single origin can be specified. ...
...attempting to use the wildcard with credentials will result in an error. <origin> specifies an origin. only a single origin can be specified. ...
...And 12 more matches
Control flow and error handling - JavaScript
this chapter provides an overview of these statements. the javascript reference contains exhaustive details about the statements in this chapter. the semicolon (;) character is used to separate statements in javascript code. any javascript expression is also a statement. see expressions and operators for complete information about expressions. block statement the most basic statement is a block statement, which is used to group statements. ...
...ipt code. any javascript expression is also a statement. see expressions and operators for complete information about expressions. block statement the most basic statement is a block statement, which is used to group statements. the block is delimited by a pair of curly brackets: { statement_1; statement_2; ⋮ statement_n; } example block statements are commonly used with control flow statements (if, for, while). while (x < 10) { x++; } here, { x++; } is the block statement. important: javascript before ecmascript2015 (6th edition) does not have block scope! in older javascript, variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. in other words, block statements do not def...
...ession that evaluates to true or false. (see boolean for an explanation of what evaluates to true and false.) if condition evaluates to true, statement_1 is executed. otherwise, statement_2 is executed. statement_1 and statement_2 can be any statement, including further nested if statements. you can also compound the statements using else if to have multiple conditions tested in sequence, as follows: if (condition_1) { statement_1; } else if (condition_2) { statement_2; } else if (condition_n) { statement_n; } else { statement_last; } in the case of multiple conditions, only the first logical condition which evaluates to true will be executed. to execute multiple statements, group them within a block statement ({ … }). best practice in general, it's good practice to always us...
...And 11 more matches
overflow-x - CSS: Cascading Style Sheets
the overflow-x css property sets what shows when content overflows a block-level element's left and right edges. this may be nothing, a scroll bar, or the overflow content. 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 values */ overflow-x: visible; overflow-x: hidden; overflow-x: clip; overflow-x: scroll; overflow-x: auto; /* global values */ overflow-x: inherit; overflow-x: initial; overflow-x: unset; the overflow-x property is specified as a single keyword chosen from the list of values below. values visible content is not clipped and may be rendered outside the padding box's left an...
... hidden content is clipped if necessary to fit horizontally in the padding box. no scrollbars are provided. clip like for hidden, the content is clipped to the element's padding box. ...
... the padding box. no scrollbars are provided. clip like for hidden, the content is clipped to the element's padding box. the difference between clip and hidden is that the clip keyword also forbids all scrolling, including programmatic scrolling. the box is not a scroll container, and does not start a new formatting context. if you wish to start a new formatting context, you can use display: flow-root to do so. scroll content is clipped if necessary to fit horizontally in the padding box. browsers display scrollbars whether or not any content is actually clipped. (this prevents scrollbars from appearing or disappearing when the content changes.) printers may still print overflowing content. auto depends on the user agent. if content fits inside the padding box, it looks the same as vi...
...And 9 more matches
RTCDataChannel: bufferedamountlow event - Web APIs
in other words, we'll try to keep at least 64kb of data in the buffer, reading 64kb at a time from the source. ...
...in other words, we'll try to keep at least 64kb of data in the buffer, reading 64kb at a time from the source. ...
...in other words, we'll try to keep at least 64kb of data in the buffer, reading 64kb at a time from the source. ...
...And 8 more matches
Block and inline layout in normal flow - CSS: Cascading Style Sheets
they can be either block or inline, but not both at once. we describe block-level boxes as participating in a block formatting context, and inline-level boxes as participating in an inline formatting context. the behaviour of elements which have a block or inline formatting context is also defined in this specification. ...
... area that contains the boxes that form a line is called a line box.” - 9.4.2 note that the css 2.1 specification describes documents as being in a horizontal, top to bottom writing mode. for example, by describing vertical distance between block boxes. the behavior on block and inline elements is the same when working in a vertical writing mode, and we will explore this in a future guide on flow layout and writing modes. elements participating in a block formatting context block elements in a horizontal writing mode such as english, layout vertically, one below the other. in a vertical writing mode then would lay out horizontally. in this guide, we will be working in english and therefore a horizontal writing mode. however, everything described should work in the same way if your...
...et adds spacing between the paragraphs by way of adding a margin to the top and bottom. if we set margins on the paragraph element to 0 then the borders will touch. by default block elements will consume all of the space in the inline direction, so our paragraphs spread out and get as big as they can inside their containing block. if we give them a width, they will continue to lay out one below the other - even if there would be space for them to be side by side. each will start against the start edge of the containing block, so the place at which sentences would begin in that writing mode. margin collapsing the spec explains that margins between block elements collapse. this means that if you have an element with a top margin immediately after an element with a bottom margin, rathe...
...And 8 more matches
Access-Control-Allow-Headers - HTTP
the header may list any number of headers, separated by commas. ...
...the header may list any number of headers, separated by commas. * (wildcard) the value "*" only counts as a special wildcard value for requests without credentials (requests without http cookies or http authentication information). ...
...o a preflight request which includes the access-control-request-headers to indicate which http headers can be used during the actual request. this header is required if the request has an access-control-request-headers header. header type response header forbidden header name no syntax access-control-allow-headers: <header-name>[, <header-name>]* access-control-allow-headers: * directives <header-name> the name of a supported request header. the header may list any number of headers, separated by commas. * (wildcard) the value "*" only counts as a special wildcard value for requests without credentials (requests without http cookies or http authentication information). in requests with credentials, it is treated as the literal header name "*" without ...
...And 8 more matches
DataTransfer.effectAllowed - Web APIs
the datatransfer.effectallowed property specifies the effect that is allowed for a drag operation. the copy operation is used to indicate that the data being dragged will be copied from its present location to the drop location. the move operation is used to indicate that the data being dragged will be moved, and the link operation 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. ...
...tion 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. copymove a copy or move operation is permitted. link a link ...
...peration is permitted. copymove a copy or move operation is permitted. link a link may be established to the source at the new location. linkmove a link or move operation is permitted. move an item may be moved to a new location. all all operations are permitted. uninitialized the default value when the effect has not been set, equivalent to all. ...
...And 7 more matches
flex-flow - CSS: Cascading Style Sheets
Web › CSS › flex-flow
the flex-flow css shorthand property specifies the direction of a flex container, as well as its wrapping behavior. 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. ...
...-flow css shorthand property specifies the direction of a flex container, as well as its wrapping behavior. 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. ...
...r, as well as its wrapping behavior. 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 7 more matches
grid-auto-flow - CSS: Cascading Style Sheets
two keywords: row dense or column dense. ...
... two keywords: row dense or column dense. ...
...ow css property controls how the auto-placement algorithm works, specifying exactly how auto-placed items get flowed into the grid. 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 values */ grid-auto-flow: row; grid-auto-flow: column; grid-auto-flow: dense; grid-auto-flow: row dense; grid-auto-flow: column dense; /* global values */ grid-auto-flow: inherit; grid-auto-flow: initial; grid-auto-flow: unset; this property may take one of two forms: a single keyword: one of row, column, or dense. two keywords: row dense or column dense. values row items are placed by filling each row in tu...
...And 7 more matches
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
see cors settings attributes for details on how the crossorigin attribute is used. security and tainted canvases because the pixels in a canvas's bitmap can come from a variety of sources, including images or videos retrieved from other hosts, it's inevitable that security problems may arise. ...
... canvas any data that was loaded from another origin without cors approval, the canvas becomes tainted. a tainted canvas is one which is no longer considered secure, and any attempts to retrieve image data back from the canvas will cause an exception to be thrown. ...
...exception to be thrown. if the source of the foreign content is an html <img> or svg <svg> element, attempting to retrieve the contents of the canvas isn't allowed. if the foreign content comes from an image obtained from either as htmlcanvaselement or imagebitmap, and the image source doesn't meet the same origin rules, attempts to read the canvas's contents are blocked. calling any of the following on a tainted canvas will result in an error: calling getimagedata() on the canvas's context calling toblob() on the <canvas> element itself calling todataurl() on the canvas attempting any of these when the canvas is tainted will cause a securityerror to be thrown. this protects users from having private data exposed by using images to pull information from remote web sites without perm...
...And 7 more matches
String.prototype.toLocaleLowerCase() - JavaScript
if multiple locales are given in an array, the best available locale is used. the default locale is the host environment’s current locale. ...
...if multiple locales are given in an array, the best available locale is used. the default locale is the host environment’s current locale. ...
...if multiple locales are given in an array, the best available locale is used. the default locale is the host environment’s current locale. ...
...And 7 more matches
Following the Android Toasts Tutorial from a JNI Perspective
it will use the jni.jsm module that is available in firefox for android since version 17. this article teaches developers how to port java code to jni by reading the java and android documentation. toast description a toast provides simple feedback about an operation in a small popup. it only fills the amount of space required for the message, and the current activity remains visible and interactive. ...
...emains visible and interactive. for example, navigating away from an email before you send it triggers a "draft saved" toast to let you know that you can continue editing later. toasts automatically disappear after a timeout. toasts do not have to be created with jni; they are exposed by the nativewindow feature on firefox for android, see toast documentation. java code let's start with the following java code, which invokes a toast and says "hello, firefox!". context context = getapplicationcontext(); charsequence text = "hello, firefox!"; int duration = toast.length_short; toast toast = toast.maketext(context, text, duration); toast.show(); nativewindow code as mentioned earlier, toasts are a very popular feature, so mozilla developers chose to bring it to the privileged javascript s...
...irefox!"; int duration = toast.length_short; toast toast = toast.maketext(context, text, duration); toast.show(); nativewindow code as mentioned earlier, toasts are a very popular feature, so mozilla developers chose to bring it to the privileged javascript scope via the nativewindow object. ...
...And 6 more matches
Flow Layout and Writing Modes - CSS: Cascading Style Sheets
the css 2.1 specification, which details how normal flow behaves, assumes a horizontal writing mode. layout properties should work in the same way in vertical writing modes. in this guide, we look at how flow layout behaves when used with different document writing modes. this is not a comprehensive guide to the use of writing modes in css, the aim here is to document the areas where flow layout interacts 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 ...
...esources. 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. ...
...erties. 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 before it would begin to wrap onto a new line. the block flow direction is the direction in which boxes, for example paragraphs, stack in that writing mode. the css writing-mode property controls the block flow direction. if you want to change your page, or part of your page, to vertical-lr then you can set writing-mode: vertical-lr on the element and this will change the direction of the blocks and therefore the inline direction as well. while certain lan...
...And 6 more matches
overflow-y - CSS: Cascading Style Sheets
the overflow-y css property sets what shows when content overflows a block-level element's top and bottom edges. this may be nothing, a scroll bar, or the overflow content. 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 values */ overflow-y: visible; overflow-y: hidden; overflow-y: clip; overflow-y: scroll; overflow-y: auto; /* global values */ overflow-y: inherit; overflow-y: initial; overflow-y: unset; the overflow-y property is specified as a single keyword chosen from the list of values below. ...
... values visible content is not clipped and may be rendered outside the padding box's top and bottom edges. ...
... the padding box. no scrollbars are provided. clip like for hidden, the content is clipped to the element's padding box. the difference between clip and hidden is that the clip keyword also forbids all scrolling, including programmatic scrolling. the box is not a scroll container, and does not start a new formatting context. if you wish to start a new formatting context, you can use display: flow-root to do so. scroll content is clipped if necessary to fit vertically in the padding box. browsers display scrollbars whether or not any content is actually clipped. (this prevents scrollbars from appearing or disappearing when the content changes.) printers may still print overflowing content. auto depends on the user agent. if content fits inside the padding box, it looks the same as visi...
...And 6 more matches
2015 MDN Fellowship Program - Archive of obsolete content
warning: the 2015 mdn fellowship program is closed. we are not accepting applications. this page is a historical archive, originally hosted at /fellowship, and was localized. more information: mdn/developerfellowship wiki page. announcing the mdn fellows! blog post, may 14 2015. mdn fellows successfully oriented blog post, july 6 2015. mdn fellows: what they did & what’s next blog post, september 23, 2015. 2015 mdn fellowship program launching in q1 2015, the mozilla developer fellowship intends to accelerate the involvement of highly-skilled and experienced web developers with the open web. who web and mobile developers with an established track record of contributions and expertise in a specific web technology, function or domain who wish to increase the effectiveness of ...
...est practices for effectively communicating and educating with technical information. we expect this to be between 5-10 hours of your time per week. specific projects (we encourage you to target one of these in your application): testthewebforward brief project description mozilla participates in an important w3c open testing initiative, testthewebforward.com. to support our efforts, the fellow will review various technical specifications to identify gaps between the documentation and current situation and refine existing tests to adapt to this cross-browser test harness. activities and deliverables identify gaps between existing documentation and current development environments. the work would entail refining existing tests to adapt to this framework. required skills and experience...
...nce and comfort writing javascript test scripts. mentor information josh matthews, mozilla platform group. github: jdm twitter: @lastontheboat service workers brief project description service workers essentially act as proxy servers that sit between web applications, the browser and (when available) the network. they enable the creation of effective offline experiences and wiill also allow access to push notifications and background sync apis. activities and deliverables write a demonstration web application (new or existing) to showcase service worker functionality. provide detailed api descriptions. required skills and experience experienced web developer with expertise in javascript, css, html as well as with efficient network interaction (queuing resource fetching, etc.). s...
...And 5 more matches
Normal Flow - Learn web development
previous overview: css layout next this article explains normal flow, or the way that webpage elements lay themselves out if you have not changed their layout. prerequisites: the basics of html (study introduction to html), and an idea of how css works (study introduction to css.) objective: to explain how browsers layout web pages by default, before we begin to make changes. as detailed in the last lesson introducing layout, elements on a webpage lay out in the normal flow, if you have not applied any css to change the way they behave. and, as we began to discover, you can change how elements behave either by adjusting their position in that normal flow, or removing them from it altogether. starting with a solid, well-structured document that is read...
... as detailed in the last lesson introducing layout, elements on a webpage lay out in the normal flow, if you have not applied any css to change the way they behave. and, as we began to discover, you can change how elements behave either by adjusting their position in that normal flow, or removing them from it altogether. starting with a solid, well-structured document that is readable in normal flow is the best way to begin any webpage. it ensures that your content is readable, even if the user is using a very limited browser or a device such as a screen reader that reads out the content of the page. in addition, as normal flow is designed to make a readable document, by starting in this way you are working with the document rather than fighting against it as you make changes to the layout. ...
... how are elements laid out by default? first of all, individual element boxes are laid out by taking the elements' content, then adding any padding, border and margin around them — it's that box model thing again, which we've looked at earlier. ...
...And 5 more matches
overflow-clip-box-block
note that this property is activated by default only in the ua stylesheet and chrome contexts. value not found in db! syntax values padding-box this keyword makes the clipping be related to the padding box. ...
...note that this property is activated by default only in the ua stylesheet and chrome contexts. value not found in db! syntax values padding-box this keyword makes the clipping be related to the padding box. ...
...note that this property is activated by default only in the ua stylesheet and chrome contexts. value not found in db! syntax values padding-box this keyword makes the clipping be related to the padding box. ...
...And 5 more matches
overflow-clip-box-inline
note that this property is activated by default only in the ua stylesheet and chrome contexts. value not found in db! syntax values padding-box this keyword makes the clipping be related to the padding box. ...
...note that this property is activated by default only in the ua stylesheet and chrome contexts. value not found in db! syntax values padding-box this keyword makes the clipping be related to the padding box. ...
...note that this property is activated by default only in the ua stylesheet and chrome contexts. value not found in db! syntax values padding-box this keyword makes the clipping be related to the padding box. ...
...And 5 more matches
IDBKeyRange.lowerBound() - Web APIs
the lowerbound() method of the idbkeyrange interface creates a new key range with only a lower bound. by default, it includes the lower endpoint value and is closed. note: this feature is available in web workers. syntax var myidbkeyrange = idbkeyrange.lowerbound(lower); var myidbkeyrange = idbkeyrange.lowerbound(lower, open); parameters lower specifies the lower bound of the new key range. open optional indicates whether the lower bound excludes the endpoint value. the default is false. return value idbkeyrange: the newly created key range. exceptions this method may raise a domexception of the following type: exception description dataerror the value parameter passed was not a valid key. ...
...he new key range. open optional indicates whether the lower bound excludes the endpoint value. the default is false. return value idbkeyrange: the newly created key range. exceptions this method may raise a domexception of the following type: exception description dataerror the value parameter passed was not a valid key. example the following example illustrates how you'd use a lower bound key range. here we declare keyrangevalue = idbkeyrange.lowerbound("f", false); — a range that includes the value "f" and everthing after it. we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. this means that the cursor will ...
...eyrange.lowerbound("f", false); — a range that includes the value "f" and everthing after it. we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. this means that the cursor will only retrieve the record with the key value "f" and all that come after it. if we used idbkeyrange.lowerbound("f", true);, then the range would not include "f"; only the values after it. ...
...And 5 more matches
CSS Flow Layout - CSS: Cascading Style Sheets
normal flow, or flow layout, is the way that block and inline elements are displayed on a page before any changes are made to their layout. the flow is essentially a set of things that are all working together and know about each other in your layout. once something is taken out of flow it works independently. in normal flow, inline elements display in the inline direction, that is in the direction words are displayed in a sentence according to the writing mode of the document. block elements display one after the other, as paragraphs do in the writing mode of that document. in english therefore, inline elements display one after the other, starting on the left, and block elements start at the top and move down the page. ...
... the inline direction, that is in the direction words are displayed in a sentence according to the writing mode of the document. block elements display one after the other, as paragraphs do in the writing mode of that document. in english therefore, inline elements display one after the other, starting on the left, and block elements start at the top and move down the page. ...
...the top and move down the page. basic example the following example demonstrates block and inline level boxes. the two paragraph elements with a green border are block level, displaying one under the other. the first sentence also includes a span element with a blue background. this is inline level and therefore displays in place in the sentence. ...
...And 5 more matches
Control flow - MDN Web Docs Glossary: Definitions of Web-related terms
for example, imagine a script used to validate user data from a webpage form. the script submits validated data, but if the user, say, leaves a required field empty, the script prompts them to fill it in. ...
... for example, imagine a script used to validate user data from a webpage form. the script submits validated data, but if the user, say, leaves a required field empty, the script prompts them to fill it in. ...
...side a function that runs when the user clicks the submit button for the form. the function could also include a loop, which iterates through all of the fields in the form, checking each one in turn. looking back at the code in the if and else sections, the lines promptuser and submitform could also be calls to other functions in the script. ...
...And 4 more matches
FeaturePolicy.allowedFeatures() - Web APIs
please note that these features might be restricted by the permissions api, if the user did not grant the corrsponding permission yet. ...
...please note that these features might be restricted by the permissions api, if the user did not grant the corrsponding permission yet. ...
...please note that these features might be restricted by the permissions api, if the user did not grant the corrsponding permission yet. ...
...And 4 more matches
IDBKeyRange.lower - Web APIs
Web › API › IDBKeyRange › lower
the lower read-only property of the idbkeyrange interface returns the lower bound of the key range. note: this feature is available in web workers. syntax var lower = mykeyrange.lower value the lower bound of the key range (can be any type.) example the following example illustrates how you'd use a key range. here we declare keyrangevalue = idbkeyrange.upperbound("f", "w", true, true); — a range that includes everything between "f" and "w" but not including them — since both the upper and lower bounds have been declared as open (true). we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. ...
...und("f", "w", true, true); — a range that includes everything between "f" and "w" but not including them — since both the upper and lower bounds have been declared as open (true). we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. after declaring the key range, we log its lower property value to the console, which should appear as "f". ...
...hem — since both the upper and lower bounds have been declared as open (true). we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. after declaring the key range, we log its lower property value to the console, which should appear as "f". ...
...And 4 more matches
IDBKeyRange.lowerOpen - Web APIs
the loweropen read-only property of the idbkeyrange interface returns a boolean indicating whether the lower-bound value is included in the key range. note: this feature is available in web workers. syntax var loweropen = mykeyrange.loweropen value a boolean: value indication true the lower-bound value is not included in the key range. false the lower-bound value is included in the key range. example the following example illustrates how you'd use a key range. here we declare keyrangevalue = idbkeyrange.upperbound("f", "w", true, true); — a range that includes everything between "f" and "w" but not including them — since both the upper and lower bounds have been declared as open (true). we open a transaction (using idbtransact...
...und("f", "w", true, true); — a range that includes everything between "f" and "w" but not including them — since both the upper and lower bounds have been declared as open (true). we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. after declaring the key range, we log its loweropen property value to the console, which should appear as "true": the lower bound is open, so won't be included in the range. ...
... open (true). we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. after declaring the key range, we log its loweropen property value to the console, which should appear as "true": the lower bound is open, so won't be included in the range. ...
...And 4 more matches
CSS Overflow - CSS: Cascading Style Sheets
the css overflow module contains the features of css relating to scrollable overflow handling in visual media. in css overflow happens when the content of a box extends past one or more of the box's edges. ink overflow and scrollable overflow there are two types of overflow that you might encounter in css. the first is described as ink overflow. this is the overflow of painting effects which do not affect layout or otherwise extend the scrollable overflow region, such as box shadows, border images, text decoration, overhanging glyphs, outlines, etc. the overflow that we sometimes need to manage in css is described as scrollable overflow. this is the content appearing outside of the box for which scrolling mechanisms need to be provided. ...
... the source for this interactive example is stored in a github repository. ...
... the source for this interactive example is stored in a github repository. ...
...And 4 more matches
overflow-wrap - CSS: Cascading Style Sheets
the overflow-wrap css property applies to inline elements, setting whether the browser should insert line breaks within an otherwise unbreakable string to prevent text from overflowing its line box. 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: in contrast to word-break, overflow-wrap will only create a break if an entire word cannot be placed on its own line without overflowing. the property was originally a nonstandard and unprefixed microsoft extension called word-wrap, and was implemented by most browsers with the same name. it has since been renamed to overflow-wrap, with word-wrap being an alias. ...
... contrast to word-break, overflow-wrap will only create a break if an entire word cannot be placed on its own line without overflowing. the property was originally a nonstandard and unprefixed microsoft extension called word-wrap, and was implemented by most browsers with the same name. it has since been renamed to overflow-wrap, with word-wrap being an alias. syntax /* keyword values */ overflow-wrap: normal; overflow-wrap: break-word; overflow-wrap: anywhere; /* global values */ overflow-wrap: inherit; overflow-wrap: initial; overflow-wrap: unset; the overflow-wrap property is specified as a single keyword chosen from the list of values below. values normal lines may only break at normal word break points (such as a space between two words). ...
...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. ...
...And 4 more matches
overflow-clip-box
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the overflow-clip-box css property specifies relative to which box the clipping happens when there is an overflow. ...
...ature 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 overflow-clip-box css property specifies relative to which box the clipping happens when there is an overflow. it is short hand for the overflow-clip-box-inline and overflow-clip-box-block properties. ...
...s 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 overflow-clip-box css property specifies relative to which box the clipping happens when there is an overflow. it is short hand for the overflow-clip-box-inline and overflow-clip-box-block properties. /* keyword values */ overflow-clip-box: padding-box; overflow-clip-box: content-box; /* two values */ overflow-clip-box: padding-box content-box; overflow-clip-box: content-box content-box; /* global values */ overflow-clip-box: inherit; overflow-clip-box: initial; overflow-clip-box: unset; note: on gecko, by default, padding-box is used everywhere, but <input type="text"> and similar use the value content-box. prior to ...
...And 3 more matches
HTMLIFrameElement.allowPaymentRequest - Web APIs
living standard browser compatibility the compatibility table on this page is generated from structured data. ...
... living standard browser compatibility the compatibility table on this page is generated from structured data. ...
... living standard browser compatibility the compatibility table on this page is generated from structured data. ...
...And 3 more matches
PublicKeyCredentialRequestOptions.allowCredentials - Web APIs
as of this writing (march 2019), only "public-key" may be used. ...
...property of the publickeycredentialrequestoptions dictionary which indicates the existing credentials acceptable for retrieval. this is an array of credential descriptors. note: publickeycredentialcreationoptions.excludecredentials may be used during the creation of the credentials in order to avoid creating new credentials for an existing user with existing public key credential. contrary to allowcredentials, it is used to filter out credentials. syntax allowcredentials = publickeycredentialrequestoptions.allowcredentials value an array whose elements are objects with the following properties: type a string describing type of public-key credential to be created. as of this writing (march 2019), only "public-key" may be used. id a buffersource matching an existing public key cred...
...ation of the publickeycredential instance. transports optional an array of strings describing the possible transports between the client and the authenticator. ...
...And 3 more matches
Handling Overflow in Multicol - CSS: Cascading Style Sheets
in this guide we look at how multicol deals with overflow, both inside the column boxes and in situations where there is more content than will fit into the container. overflow inside column boxes an overflow situation happens when an item's size is larger than the column box. for example, the situation could happen when an image in a column is wider than the column-width value or the width of the column based on the number of columns declared with column-count. in this situation, the content should visibly overflow into the next column, rather than be clipped by the column box. you can see an example of this below, with an image of the expected rendering as, at the time of writing, browsers deal with this differently. if you want an image to size down to fit the column box, the stan...
...o the next column, rather than be clipped by the column box. you can see an example of this below, with an image of the expected rendering as, at the time of writing, browsers deal with this differently. if you want an image to size down to fit the column box, the standard responsive images solution of setting max-width: 100% will achieve that for you. more columns than will fit how overflowing columns are handled depends on whether you are in a fragmented media context, such as print, or a continuous media context, such as a web page. in fragmented media, once a fragment (for example a page) is filled with columns, the columns will move to a new page and fill that up with columns. in continuous media, columns will overflow in the inline direction. on the web this means that you wil...
...u are in a fragmented media context, such as print, or a continuous media context, such as a web page. in fragmented media, once a fragment (for example a page) is filled with columns, the columns will move to a new page and fill that up with columns. in continuous media, columns will overflow in the inline direction. on the web this means that you will get a horizontal scrollbar. the example below shows this overflow behaviour. ...
...And 3 more matches
Reason: CORS header 'Access-Control-Allow-Origin' does not match 'xyz' - HTTP
reason reason: cors header 'access-control-allow-origin' does not match 'xyz' what went wrong? ...
... reason reason: cors header 'access-control-allow-origin' does not match 'xyz' what went wrong? ...
... reason reason: cors header 'access-control-allow-origin' does not match 'xyz' what went wrong? ...
...And 3 more matches
Reason: CORS header 'Access-Control-Allow-Origin' missing - HTTP
reason reason: cors header 'access-control-allow-origin' missing what went wrong? 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. 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. for example, to allow a site at https://amazing.site to access the resource using cors, the header should be: access-control-allow-origin: https://amazing.site you can also configure a site to allow any site to access it by using the * wildcard. you should only use this for public apis. private apis should never use *, an...
... can also configure a site to allow any site to access it by using the * wildcard. you should only use this for public apis. private apis should never use *, and should instead have a specific domain or domains set. in addition, the wildcard only works for requests made with the crossorigin attribute set to anonymous, and it prevents sending credentials like cookies in requests. access-control-allow-origin: * warning: using the wildcard to allow all sites to access a private api is a bad idea. ...
...or public apis. private apis should never use *, and should instead have a specific domain or domains set. in addition, the wildcard only works for requests made with the crossorigin attribute set to anonymous, and it prevents sending credentials like cookies in requests. access-control-allow-origin: * warning: using the wildcard to allow all sites to access a private api is a bad idea. to allow any site to make cors requests without using the * wildcard (for example, to enable credentials), your server must read the value of the request's origin header and use that value to set access-control-allow-origin, and must also set a vary: origin header to indicate that some headers are being set dynamically depending on the origin. the exact directive for setting headers depends on your web s...
...And 3 more matches
Access-Control-Allow-Credentials - HTTP
credentials are cookies, authorization headers or tls client certificates. when used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. ...
... credentials are cookies, authorization headers or tls client certificates. when used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. ...
...cates. when used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. note that simple get requests are not preflighted, and so if a request is made for a resource with credentials, if this header is not returned with the resource, the response is ignored by the browser and not returned to web content. ...
...And 3 more matches
SyntaxError: "use strict" not allowed in function with non-simple parameters - JavaScript
the javascript exception "'use strict' not allowed in function" occurs when a "use strict" directive is used at the top of a function with default parameters, rest parameters, or destructuring parameters. message edge: cannot apply strict mode on functions with non-simple parameter list firefox: syntaxerror: "use strict" not allowed in function with default parameter syntaxerror: "use strict" not allowed in function with rest parameter syntaxerror: "use strict" not allowed in function with destructuring parameter chrome: syntaxerror: illegal 'use strict' directive in function with non-simple parameter list error type syntaxerror. ...
...n with default parameter syntaxerror: "use strict" not allowed in function with rest parameter syntaxerror: "use strict" not allowed in function with destructuring parameter chrome: syntaxerror: illegal 'use strict' directive in function with non-simple parameter list error type syntaxerror. what went wrong? ...
... not allowed in function with destructuring parameter chrome: syntaxerror: illegal 'use strict' directive in function with non-simple parameter list error type syntaxerror. what went wrong? ...
...And 3 more matches
overflow - SVG: Scalable Vector Graphics
when scroll is specified on an <svg> element, a scrollbar or panner is normally shown for the svg viewport whether or not any of its content is clipped. within svg content, the value auto implies that all rendered content for child elements must be visible, either through a scrolling mechanism, or by rendering with no clip. ...
... when scroll is specified on an <svg> element, a scrollbar or panner is normally shown for the svg viewport whether or not any of its content is clipped. within svg content, the value auto implies that all rendered content for child elements must be visible, either through a scrolling mechanism, or by rendering with no clip. ...
...e of the svg viewport is applied. when scroll is specified on an <svg> element, a scrollbar or panner is normally shown for the svg viewport whether or not any of its content is clipped. within svg content, the value auto implies that all rendered content for child elements must be visible, either through a scrolling mechanism, or by rendering with no clip. although the initial value for overflow is auto, it is overwritten in the user agent style sheet for the <svg> element when it is not the root element of a stand-alone document, the <pattern> element, and the <marker> element to be hidden by default. note: as a presentation attribute, overflow can be used as a css property. see the css opacity property for more information. as a presentation attribute, it can be applied to any elemen...
...And 3 more matches
-ms-wrap-flow - Archive of obsolete content
the -ms-wrap-flow css property is a microsoft extension that specifies how exclusions impact inline content within block-level elements. initial valueautoapplies toblock-level elementsinheritednocomputed valueas specifiedanimation typediscrete syntax values auto for floated elements, an exclusion is created; for all other elements, an exclusion is not created. both inline flow content can flow on all sides of the exclusion. start inline flow content can wrap on the start edge of the exclusion area but must leave empty the area after the end edge of the exclusion area. end inline flow content can wrap after the end edge of the exclusion area but must leave empty the area before the start edge of the exclusion area. ...
... both inline flow content can flow on all sides of the exclusion. start inline flow content can wrap on the start edge of the exclusion area but must leave empty the area after the end edge of the exclusion area. end inline flow content can wrap after the end edge of the exclusion area but must leave empty the area before the start edge of the exclusion area. maximum inline flow content can wrap on the side of the exclusion with the largest available space for the given line, and must leave empty the other side of the exclusion. clear inline flow content can only wrap on top and bottom of the exclusion and must leave empty the areas to the start and end edges of the exclusion box. formal syntax auto | both | start | end | maximum | clear specifications not ...
... the largest available space for the given line, and must leave empty the other side of the exclusion. clear inline flow content can only wrap on top and bottom of the exclusion and must leave empty the areas to the start and end edges of the exclusion box. formal syntax auto | both | start | end | maximum | clear specifications not part of any specification. remarks the -ms-wrap-flow property makes an element an exclusion element when it has a computed value other than auto. ...
...And 2 more matches
::-ms-fill-lower - Archive of obsolete content
other properties are ignored. ...
...other properties are ignored. ...
...other properties are ignored. ...
...And 2 more matches
RTCDataChannel.bufferedAmountLowThreshold - Web APIs
the rtcdatachannel property bufferedamountlowthreshold is used to specify the number of bytes of buffered outgoing data that is considered "low." the default value is 0. when the number of buffered outgoing bytes, as indicated by the bufferedamount property, falls to or below this value, a bufferedamountlow event is fired. this event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them. listeners may be added with onbufferedamountlow or addeventlistener(). the user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. ...
...ode which queues more messages to be sent whenever there's room to buffer them. listeners may be added with onbufferedamountlow or addeventlistener(). the user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. as messages are actually sent, this value is reduced accordingly. bufferedamountlow events are not fired after the data channel is closed. ...
...fferedamountlow or addeventlistener(). the user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. as messages are actually sent, this value is reduced accordingly. bufferedamountlow events are not fired after the data channel is closed. ...
...And 2 more matches
x-ms-aria-flowfrom - Accessibility
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. ...
... non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the x-ms-aria-flowfrom property specifies the id of the previous element in an alternative reading order, allowing assistive technology to override the general default of reading in document source order. ...
...ompatibilities between implementations and the behavior may change in the future. the x-ms-aria-flowfrom property specifies the id of the previous element in an alternative reading order, allowing assistive technology to override the general default of reading in document source order. the property serves to define element relationships utilizing aria relationship attributes and the aria-flowto property. this proprietary property is specific to internet explorer and microsoft edge. syntax x-ms-aria-flowfrom="elementid"; value the x-ms-aria-flowfrom property value uses an id selector to define which previous element the reading order will flow from. ...
...And 2 more matches
Low-Level APIs - Archive of obsolete content
you can use these modules in your add-on if you need to, but should be aware that the cost of privileged access is the need to take more elaborate security precautions. ...
...es fall roughly into three categories: fundamental utilities such as collection. many add-ons are likely to want to use modules from this category. building blocks for higher level modules, such as events and worker. you're more likely to use these if you are building your own modules that implement new apis, thus extending the sdk itself. privileged modules that expose powerful low-level capabilities such as window/utils and net/xhr. you can use these modules in your add-on if you need to, but should be aware that the cost of privileged access is the need to take more elaborate security precautions. in many cases these modules have simpler, more restricted analogs among the "high-level apis" (for example, windows or request). these modules are still in active developmen...
...e restricted analogs among the "high-level apis" (for example, windows or request). these modules are still in active development, and we expect to make incompatible changes to them in future releases. /loader create commonjs module loaders. 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. console/plain-text constructor for a console instance. console/traceback functionality similar to python's traceback module. content/content re-exports three objects from three other modules: loader, worker, and symbiont. content/loader provides one of the building blocks for those modules that use content scripts to interact with web content, such as panel and page-mo...
...tent. 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 platform internals like frames and browsers. fs/path provides access to the local filesystem with the nodejs path modu...
-ms-overflow-style - Archive of obsolete content
"traditional" scrollbars don't auto-hide and never overlap the element's content. ...
..."traditional" scrollbars don't auto-hide and never overlap the element's content. ...
..."traditional" scrollbars don't auto-hide and never overlap the element's content. ...
...lies tonon-replaced block-level elements and non-replaced inline-block elementsinheritedyescomputed valueas specifiedanimation typediscrete syntax values auto the initial value. same as inherit. none scrollbars are never displayed, although the element can still be scrolled if the element's content overflows. scrollbar "traditional" scrollbars are displayed if the element's content overflows. "traditional" scrollbars don't auto-hide and never overlap the element's content. accordingly, the dimensions of the layout area for the content are reduced by the width (for vertical scrollbars) or height (for horizontal scrollbars) of the scrollbar(s). -ms-autohiding-scrollbar auto-hiding scrollbars are used if the element's content overflows. auto-hiding scrollbars are displayed during scr...
Test your skills: Overflow - Learn web development
the aim of these tasks is to help you check your understanding of overflow in css. note: you can try out solutions in the interactive 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. task one the content is overflowing the box because it has a fixed height. keep the height but cause the box to have scrollbars only if there is enough text to cause an overflow. test by removing some of the text from the html, that if there is only a small amount of text that does not overflow, no scrollbar appears. ...
...ther help section at the bottom of this page. task one the content is overflowing the box because it has a fixed height. keep the height but cause the box to have scrollbars only if there is enough text to cause an overflow. test by removing some of the text from the html, that if there is only a small amount of text that does not overflow, no scrollbar appears. 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. task two in this task an image is in the box, it is bigger than the dimensions of the box so overflows visibly. ...
... assessment or further help you can practice these examples in the interactive editors mentioned above. ...
... stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yourself, or use the starting point files linked to in the above sections. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for overflow skill test 1". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want to be assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their c...
Element: overflow event - Web APIs
the overflow event is fired when an element has been overflowed by its content or has been rendered for the first time in this state (only works for elements styled with overflow != visible). it is a proprietary event specific to gecko (firefox). ...
...e first time in this state (only works for elements styled with overflow != visible). it is a proprietary event specific to gecko (firefox). ...
...ific to gecko (firefox). ...
...idth: 20px; height: 20px; background: #000; padding: 5px; overflow: hidden; } #child { width: 40px; height: 40px; border: 2px solid grey; background: #ccc; } </style> <script> var wrapper = document.getelementbyid("wrapper"), child = document.getelementbyid("child"), toggle = document.getelementbyid("toggle"); wrapper.addeventlistener("overflow", function( event ) { console.log( event ); }, false); wrapper.addeventlistener("underflow", function( event ) { console.log( event ); }, false); toggle.addeventlistener("change", function( event ) { if ( event.target.checked ) { child.style.width = "40px"; child.style.height = "40px"; } else { child.style.width = "10px"; c...
Element: underflow event - Web APIs
the non-standard underflow event, which is specific to firefox, is fired when an element is no longer overflowed by its content. this only works for elements for which overflow is not set to visible. the counterpart overflow event is fired when overflow occurs. ...
...ontent. this only works for elements for which overflow is not set to visible. the counterpart overflow event is fired when overflow occurs. ...
...ed when overflow occurs. ...
...idth: 20px; height: 20px; background: #000; padding: 5px; overflow: hidden; } #child { width: 40px; height: 40px; border: 2px solid grey; background: #ccc; } </style> <script> var wrapper = document.getelementbyid("wrapper"), child = document.getelementbyid("child"), toggle = document.getelementbyid("toggle"); wrapper.addeventlistener("overflow", function( event ) { console.log( event ); }, false); wrapper.addeventlistener("underflow", function( event ) { console.log( event ); }, false); toggle.addeventlistener("change", function( event ) { if ( event.target.checked ) { child.style.width = "40px"; child.style.height = "40px"; } else { child.style.width = "10px"; c...
Reason: invalid token ‘xyz’ in CORS header ‘Access-Control-Allow-Methods’ - HTTP
reason reason: invalid token ‘xyz’ in cors header ‘access-control-allow-methods’ what went wrong? ...
... reason reason: invalid token ‘xyz’ in cors header ‘access-control-allow-methods’ what went wrong? ...
... reason reason: invalid token ‘xyz’ in cors header ‘access-control-allow-methods’ what went wrong? ...
...ors requests. the header's value is a comma-delineated string of http method names, such as get, post, or head. if any of the specified values are not recognized by the client user agent, this error occurs. this is a problem that most likely can only be fixed on the server side, by modifying the server's configuration to no longer send the invalid or unknown method name with the access-control-allow-methods header. it may also be worth checking to ensure that the user agent or http library you're using on the client is up-to-date. ...
allowevents - Archive of obsolete content
« xul reference home allowevents type: boolean if true, events are passed to children of the element. otherwise, events are passed to the element only. on listitem and titlebar elements, mouse events normally do not get sent to their children; instead they are retargeted to the listitem and titlebar element itself. this means that elements placed inside a listitem do not respond to events, and instead clicking the mouse simply selects that item within the list. by setting the allowevents attribute to true, this special behavior is disabled, and the events are targeted the same as other elements. for menu, menuseparator, menuitem and treecol elements, as well as menu buttons, and the popup datepicker, mouse events are also retargeted to the element itself. however, the...
...o events, and instead clicking the mouse simply selects that item within the list. by setting the allowevents attribute to true, this special behavior is disabled, and the events are targeted the same as other elements. for menu, menuseparator, menuitem and treecol elements, as well as menu buttons, and the popup datepicker, mouse events are also retargeted to the element itself. however, the allowevents attribute is handled in a different way. instead, the allowevents may be set to true on a descendant instead. this does the same thing in that it allows events to be targeted normally, but allows this to be different for each descendant. ...
... and the popup datepicker, mouse events are also retargeted to the element itself. however, the allowevents attribute is handled in a different way. instead, the allowevents may be set to true on a descendant instead. this does the same thing in that it allows events to be targeted normally, but allows this to be different for each descendant. this behavior is used for menus, for instance, to allow a menu button to behave as a menu when clicking on it, yet have part of the menu behave as a button. for the latter, the allowevents attribute is set to true to have a click on the child button receive events instead of targeting all events at the menu. ...
TCP slow start - MDN Web Docs Glossary: Definitions of Web-related terms
tcp slow start helps buildup transmission speeds to the network's capabilities. it does this without initially knowing what those capabilities are and without creating congestion. tcp slow start is an algorithm used to detect the available bandwidth for packet transmission, and balances the speed of a network connection. it prevents the appearance 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 c...
...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 within a network layer when the message traffic is too busy it slows the network response time. the server sends data in tcp packets, the user's client then confirms delivery by returning acknoledgements, or acks. the connection has a limited capacity depending on hardware and netw...
...the server sends data in tcp packets, 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 ...
FeaturePolicy.allowsFeature() - Web APIs
the allowsfeature() method of the featurepolicy interface enables introspection of individual directives of the feature policy it is run on. it returns a boolean that is true if and only if the specified feature is allowed in the specified context (or the default context if no context is specified). syntax const allowed = featurepolicy.allowsfeature(<feature>) or const allowed = featurepolicy.allowsfeature(<feature>, <origin>) parameters feature name a specific feature name must be specified. origin name optional an origin url to check the feature on. if it is omitted the default origin is used. return value a boolean that is true if and only if the feature is allowed. ...
...x const allowed = featurepolicy.allowsfeature(<feature>) or const allowed = featurepolicy.allowsfeature(<feature>, <origin>) parameters feature name a specific feature name must be specified. origin name optional an origin url to check the feature on. if it is omitted the default origin is used. return value a boolean that is true if and only if the feature is allowed. example the following example queries whether or not the document is allowed to use camera api by the feature policy. please note that camera api might be restricted by the permissions api, if the user did not grant the corresponding permission yet. ...
...ature is allowed. example the following example queries whether or not the document is allowed to use camera api by the feature policy. please note that camera api might be restricted by the permissions api, if the user did not grant the corresponding permission yet. // first, get the feature policy object const featurepolicy = document.featurepolicy // then query feature for specific const allowed = featurepolicy.allowsfeature("camera") if (allowed){ console.log("fp allows camera.") } else { console.log("fp does not allows camera.") } specifications specification status comment feature policythe definition of 'allowsfeature' in that specification. editor's draft initial definition. ...
FeaturePolicy.getAllowlistForFeature() - Web APIs
the getallowlistforfeature() method of the featurepolicy allows query of the allow list for a specific feature for the current feature policy. syntax const allowlist = featurepolicy.getallowlistforfeature(<feature>) parameter feature name a specific feature name must be specified. return value an allow list for the specified feature. errors the function will raise a warning if the specified feature policy directive name is not known. however, it will also return empty array, inditating that no origin is allowed to use the feature. example the followin example prints all the origins that are allowed to use camera api by the feature policy. please note that camera api might be restricted by the permissions api, if the user did not grant the corrsponding permission yet. /...
... editor's draft initial definition. ...
...xample the followin example prints all the origins that are allowed to use camera api by the feature policy. please note that camera api might be restricted by the permissions api, if the user did not grant the corrsponding permission yet. // first, get the feature policy object const featurepolicy = document.featurepolicy // then query feature for specific const allowlist = featurepolicy.getallowlistforfeature("camera") for (const origin of allowlist){ console.log(origin) } specification specification status comment feature policythe definition of 'getallowlistforfeature' in that specification. editor's draft initial definition. ...
HTMLImageElement.lowSrc - Web APIs
the htmlimageelement interface's obsolete lowsrc property can be used to specify the url of a reduced-quality or otherwise faster-loading version of the image specified by the src property. this property reflects the html lowsrc attribute. syntax htmlimageelement.lowsrc = imageurl; imageurl = htmlimageelement.lowsrc; value a domstring specifying the url of a version of the image specified by src which has been modified in some fashion so that it loads significantly more quickly than the primary image. there are a number of ways to achieve this; primary among them: higher compression levels (for example, a primary image saved as a jpeg using 85% quality might have a lowsrc version saved at 15%. reduced color depth; a primary image in 32-bit color might have an alternate image in...
... some fashion so that it loads significantly more quickly than the primary image. there are a number of ways to achieve this; primary among them: higher compression levels (for example, a primary image saved as a jpeg using 85% quality might have a lowsrc version saved at 15%. reduced color depth; a primary image in 32-bit color might have an alternate image in 8-bit color. important: the lowsrc property is obsolete and should not be used. instead, you should use an image format which loads progressively (such as progressive jpeg). or simply make sure your images are all well-optimized and balanced for appearance versus size. usage notes lowsrc is a strange case. it was never technically part of the html specification (it was a mozilla extension to html); however, html 5 does list ...
...olete attributes. 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. ...
RTCDataChannel.onbufferedamountlow - Web APIs
the rtcdatachannel.onbufferedamountlow property is an eventhandler which specifies a function the browser calls when the bufferedamountlow event is sent to the rtcdatachannel. this event, which is represented by a simple event object, is sent when the amount of data buffered to be sent falls to or below the threshold specified by the channel's bufferedamountlowthreshold. see buffering in using webrtc data channels to learn more about how to work with the data channel buffer. syntax rtcdatachannel.onbufferedamountlow = function; value a function which the browser will call to handle the bufferedamountlow event. this function receives as its only input parameter a simple event object representing the event which has occurred. ...
...using webrtc data channels to learn more about how to work with the data channel buffer. syntax rtcdatachannel.onbufferedamountlow = function; value a function which the browser will call to handle the bufferedamountlow event. this function receives as its only input parameter a simple event object representing the event which has occurred. example this example responds to the bufferedamountlow event by fetching up to 64kb of a file represented by an object source and calling rtcdatachannel.send() to queue up the retrieved data for sending on the data channel. pc = new rtcpeerconnection(); dc = pc.createdatachannel("sendfile"); /* ... ...
...rameter a simple event object representing the event which has occurred. example this example responds to the bufferedamountlow event by fetching up to 64kb of a file represented by an object source and calling rtcdatachannel.send() to queue up the retrieved data for sending on the data channel. pc = new rtcpeerconnection(); dc = pc.createdatachannel("sendfile"); /* ... */ dc.onbufferedamountlow = function() { if (source.position <= source.length) { dc.send(source.readfile(65536)); } } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.onbufferedamountlow' in that specification. candidate recommendation initial specification. ...
ValidityState.rangeOverflow - Web APIs
when true, the element matches the :invalid and :out-of-range css pseudo-classes. ...
... 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 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 standa...
... 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' in that specification. recommendation html5the definition of 'validitystate.rangeoverflow' in that specification. recommendation ...
ValidityState.rangeUnderflow - Web APIs
when true, the element matches the :invalid and :out-of-range css pseudo-classes. ...
...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.rangeunderflow' in that specification. living stan...
...n="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.rangeunderflow' in that specification. living standard html 5.1the definition of 'validitystate.rangeunderflow' in that specification. recommendation html5the definition of 'validitystate.rangeunderflow' in that specification. recommendation ...
msRegionOverflow - 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. the msregionoverflow read-only property determines if content fully fits into the region or not. this proprietary property is specific to internet explorer. syntax string = object.msregionoverflow values type:domstring overflow: the region element's content overflows the region's content box. note that the region's overflow property value can be used to control the visibility of the overflowing content. this means that the region is the last one in the region chain and not able to fit the ...
...o internet explorer. syntax string = object.msregionoverflow values type:domstring overflow: the region element's content overflows the region's content box. note that the region's overflow property value can be used to control the visibility of the overflowing content. this means that the region is the last one in the region chain and not able to fit the remaining content from the named flow. fit: the region element's content fits into the region's content box. it does not overflow. if the region is the last one in the region chain, it means that the content fits without overflowing. if the region is not the last one in the region chain, that means the named flow content is further fitted in subsequent regions. in particular, in this last case, that means the region may have receive...
...content fits into the region's content box. it does not overflow. if the region is the last one in the region chain, it means that the content fits without overflowing. if the region is not the last one in the region chain, that means the named flow content is further fitted in subsequent regions. in particular, in this last case, that means the region may have received no content from the named flow (for example if the region is too small to accommodate any content). empty: the region element has no content and is empty. all content from the named flow was fitted in regions with a lower content-order value. undefined: the element is not a region. when the region is an actual element, msregionoverflow provides the ability to find out if content fully fits into the region or not. however, ...
overflow-anchor - CSS: Cascading Style Sheets
none the element won't be selected as a potential anchor. ...
...roll anchoring behavior, which adjusts scroll position to minimize content shifts. 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. syntax /* keyword values */ overflow-anchor: auto; overflow-anchor: none; /* global values */ overflow-anchor: inherit; overflow-anchor: initial; overflow-anchor: unset; values auto the element becomes a potential anchor when adjusting scroll position. none the element won't be selected as a potential anchor. formal definition initial valueautoapplies toall elementsinheritednocomputed valueas specifiedanimation typediscr...
...r: unset; values auto the element becomes a potential anchor when adjusting scroll position. none the element won't be selected as a potential anchor. formal definition initial valueautoapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | none examples prevent scroll anchoring to prevent scroll anchoring in a document, use the overflow-anchor property. body { overflow-anchor: none; } specifications specification status comment css scroll anchoring module level 1the definition of 'overflow-anchor' in that specification. editor's draft initial definition. ...
Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’ - HTTP
reason reason: did not find method in cors header ‘access-control-allow-methods’ what went wrong? ...
... reason reason: did not find method in cors header ‘access-control-allow-methods’ what went wrong? ...
...d being used by the cors request is not included in the list of methods specified by the response's access-control-allow-methods header. this header specifies a comma-delineated list of the http methods which may be used when using cors to access the url specified in the request; if the request is using any other method, this error occurs. for example, if the response includes: access-control-allow-methods: get,head,post trying to use a put request will fail with this error. make sure your code only uses the permitted http methods when accessing the service. note: if the server includes any unrecognized or undefined method names in its access-control-allow-methods header, a different error occurs: reason: invalid token ‘xyz' in cors header ‘access-control-allow-methods’. ...
Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’ - HTTP
reason reason: expected ‘true’ in cors header ‘access-control-allow-credentials’ what went wrong? ...
... reason reason: expected ‘true’ in cors header ‘access-control-allow-credentials’ what went wrong? ...
... ...
Allow - HTTP
Web › HTTP › Headers › Allow
the allow header lists the set of methods supported by a resource. this header must be sent if the server responds with a 405 method not allowed status code to indicate which request methods can be used. an empty allow header indicates that the resource allows no request methods, which might occur temporarily for a given resource, for example. header type entity header forbidden header name no syntax allow: <http-methods> directives <http-methods> the comma-separated list of allowed http request methods. ...
...icate which request methods can be used. an empty allow header indicates that the resource allows no request methods, which might occur temporarily for a given resource, for example. header type entity header forbidden header name no syntax allow: <http-methods> directives <http-methods> the comma-separated list of allowed http request methods. ...
...st methods, which might occur temporarily for a given resource, for example. header type entity header forbidden header name no syntax allow: <http-methods> directives <http-methods> the comma-separated list of allowed http request methods. ...
405 Method Not Allowed - HTTP
Web › HTTP › Status › 405
the hypertext transfer protocol (http) 405 method not allowed response status code indicates that the request method is known by the server but is not supported by the target resource. the server must generate an allow header field in a 405 response containing a list of the target resource's currently supported methods. ...
... the hypertext transfer protocol (http) 405 method not allowed response status code indicates that the request method is known by the server but is not supported by the target resource. the server must generate an allow header field in a 405 response containing a list of the target resource's currently supported methods. ...
...ed response status code indicates that the request method is known by the server but is not supported by the target resource. the server must generate an allow header field in a 405 response containing a list of the target resource's currently supported methods. ...
allowEvents - Archive of obsolete content
...
... ...
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. ...
... 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. ...
JSSecurityCallbacks.contentSecurityPolicyAllows
the jssecuritycallbacks.contentsecuritypolicyallows callback is called when a script attempts to access an object property. the callback can deny the script access to the property. jscheckaccessop is the type of the callback. (it is also the type of the callback set by js_setcheckobjectaccesscallback.) syntax typedef jsbool (*jscspevalchecker)(jscontext *cx); name type description cx jscontext * the js context in which the property access attempt is occurring. description check whether runtime code generation is allowed for the current global. ...
... ...
-webkit-overflow-scrolling - CSS: Cascading Style Sheets
syntax values auto use "regular" scrolling, where the content immediately ceases to scroll when you remove your finger from the touchscreen. touch use momentum-based scrolling, where the content continues to scroll for a while after finishing the scroll gesture and removing your finger from the touchscreen. the speed and duration of the continued scrolling is proportional to how vigorous the scroll gesture was. also creates a new stacking context. ...
...creates a new stacking context. formal definition initial valueautoapplies toscrolling boxesinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | touch examples html <div class="scroll-touch"> <p> this paragraph has momentum scrolling </p> </div> <div class="scroll-auto"> <p> this paragraph does not. </p> </div> css div { width: 100%; overflow: auto; } p { width: 200%; background: #f5f9fa; border: 2px solid #eaf2f4; padding: 10px; } .scroll-touch { -webkit-overflow-scrolling: touch; /* lets it scroll lazy */ } .scroll-auto { -webkit-overflow-scrolling: auto; /* stops scrolling immediately */ } results specifications not part of any standard. apple has a description in the safari css reference. ...
overflow-block - CSS: Cascading Style Sheets
the overflow-block css media feature can be used to test how the output device handles content that overflows the initial containing block along the block axis. syntax the overflow-block feature is specified as a keyword value chosen from the list below. none content that overflows the block axis is not displayed. scroll content that overflows the block axis can be seen by scrolling to it. optional-paged content that overflows the block axis can be seen by scrolling to it, but page breaks can be manually triggered (such as via break-inside, etc.) to cause the following content to display on the following page. paged content is broken up into discrete pages; content that overflows one page in the block axis is displayed on the following page. examples html <p>lorem ipsum dolor...
...et ultrices posuere cubilia curae; nunc velit erat, tempus id rutrum sed, dapibus ut urna. integer vehicula nibh a justo imperdiet rutrum. nam faucibus pretium orci imperdiet sollicitudin. nunc id facilisis dui. proin elementum et massa et feugiat. integer rutrum ullamcorper eleifend. proin sit amet tincidunt risus. sed nec augue congue eros accumsan tincidunt sed eget ex.</p> css @media (overflow-block: scroll) { p { color: red; } } result specifications specification status comment media queries level 4the definition of 'overflow-block' in that specification. candidate recommendation initial definition. ...
overflow-inline - CSS: Cascading Style Sheets
examples html <p>lorem ipsum dolor sit amet, consectetur adipiscing elit. nullam ac turpis eleifend, fringilla velit ac, aliquam tellus. vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; nunc velit erat, tempus id rutrum sed, dapibus ut urna. integer vehicula nibh a justo imperdiet rutrum. nam faucibus pretium orci imperdiet sollicitudin. ...
...rae; nunc velit erat, tempus id rutrum sed, dapibus ut urna. integer vehicula nibh a justo imperdiet rutrum. nam faucibus pretium orci imperdiet sollicitudin. nunc id facilisis dui. proin elementum et massa et feugiat. integer rutrum ullamcorper eleifend. proin sit amet tincidunt risus. sed nec augue congue eros accumsan tincidunt sed eget ex.</p> css p { white-space: nowrap; } @media (overflow-inline: scroll) { p { color: red; } } result specifications specification status comment media queries level 4the definition of 'overflow-inline' in that specification. candidate recommendation initial definition. ...
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. ...
... 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(). ...
Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’ - HTTP
to correct this problem on the client side, simply ensure that the credentials flag's value is false when issuing your cors request. 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). ...
...rs request. 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". if, instead, you need to adjust the server's behavior, you'll need to change the value of access-control-allow-origin to grant access to the origin from which the client is loaded. ...
Access-Control-Allow-Methods - HTTP
the access-control-allow-methods response header specifies the method or methods allowed when accessing the resource in response to a preflight request. header type response header forbidden header name no syntax access-control-allow-methods: <method>, <method>, ... access-control-allow-methods: * directives <method> comma-delimited list of the allowed http request methods. * (wildcard) the value "*" only counts as a special wildcard value for requests without credentials (requests without http cookies or http authentication information). in requests with credentials, it is treated as the literal method name "*" without special semantics. ...
...low-methods: * directives <method> comma-delimited list of the allowed http request methods. * (wildcard) the value "*" only counts as a special wildcard value for requests without credentials (requests without http cookies or http authentication information). in requests with credentials, it is treated as the literal method name "*" without special semantics. examples access-control-allow-methods: post, get, options access-control-allow-methods: * specifications specification status comment fetchthe definition of 'access-control-allow-methods' in that specification. living standard 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 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. 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. ...
String.prototype.toLowerCase() - JavaScript
the tolowercase() method returns the calling string value converted to lower case. 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.tolowercase() return value a new string representing the calling string converted to lower case. description the tolowercase() method returns the value of the string converted to lower case. tolowercase() does not affect the value of the string str itself. ...
...ive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.tolowercase() return value a new string representing the calling string converted to lower case. description the tolowercase() method returns the value of the string converted to lower case. tolowercase() does not affect the value of the string str itself. examples using tolowercase() console.log('alphabet'.tolowercase()); // 'alphabet' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tolowercase' in that specification. ...
Disabling interruptible reflow - Archive of obsolete content
add the following variables to your environment to disable gecko interruptible reflow: gecko_reflow_interrupt_mode=counter gecko_reflow_interrupt_frequency=1000000 gecko_reflow_interrupt_checks_to_skip=1000000 now start firefox within this environment. ...
allownegativeassertions - Archive of obsolete content
« xul reference home allownegativeassertions type: boolean valid on any element that has a datasources attribute. when multiple datasources are used, one may override an assertion from another. this attribute, if true, which is the default, allows a datasource to negate an earlier assertion. ...
-ms-flow-from - Archive of obsolete content
initial valuenoneapplies tonon-replaced elementsinheritednocomputed valueas specifiedanimation typediscrete syntax values none default. no container has been specified. <custom-ident> the name of the region container. formal syntax [ none | <custom-ident> ]# specifications not part of any specification. ...
-ms-flow-into - Archive of obsolete content
initial valuenoneapplies toiframe elementsinheritednocomputed valueas specifiedanimation typediscrete syntax values none default. no container has been specified. <custom-ident> the name of the region container. formal syntax [ none | <custom-ident> ]# specifications not part of any specification. ...
GetAccessibleBelow
« nsiaccessible page summary this method returns an accessible node geometrically below this one. nsiaccessible getaccessiblebelow(); return value returns an accessible node geometrically below this one. see also nsiaccessible.getaccessibletoright() nsiaccessible.getaccessibletoleft() nsiaccessible.getaccessibleabove() ...
copyToFollowingLinks
...
copyToFollowingLinksNative
...
isLowMemory
...
Reason: CORS request external redirect not allowed - HTTP
for example, if the page https://service.tld/fetchdata were requested, and the http response is "301 moved permanently", "307 temporary redirect", or "308 permanent redirect" with a location of https://anotherservice.net/getdata, the cors request will fail in this manner. ...
Reason: invalid token ‘xyz’ in CORS header ‘Access-Control-Allow-Headers’ - HTTP
reason reason: invalid token ‘xyz’ in cors header ‘access-control-allow-headers’ what went wrong? the response to the cors request that was sent by the server includes an access-control-allow-headers header which includes at least one invalid header name. the access-control-allow-headers header is sent by the server in response to a preflight request; it lets the client know which http headers are permitted in cors requests. if the client user agent finds among the comma-delineated values provided by the header any header name it does not recognize, this error occurs. this is a problem that most likely can only be fixed on the server side, by modifying the server's configuration to no longer send the invalid or unknown header name with the access-control-allow-headers header. it...
Reason: missing token ‘xyz’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel - HTTP
reason reason: missing token ‘xyz’ in cors header ‘access-control-allow-headers’ from cors preflight channel what went wrong? the access-control-allow-headers header is sent by the server to let the client know which headers it supports for cors requests. the value of access-control-allow-headers should be a comma-delineated list of header names, such as "x-custom-information" or any of the standard but non-basic header names (which are always allowed). this error occurs when attempting to preflight a header that is not expressly allowed (that is, it's not included in the list specified by the access-control-allow-headers header sent by the server). to fix this, the server needs to be updated so that it allows the indicated header, or you need to avoid using that header. ...
following-sibling - XPath
the following-sibling axis indicates all the nodes that have the same parent as the context node and appear after the context node in the source document. ...
following - XPath
Web › XPath › Axes › following
the following axis indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes. ...
Index - Web APIs
Web › API › Index
found 5328 pages: # page tags and summary 1 web apis api, dom, landing, reference, web when writing code for the web, there are a large number of web apis available. below is a list of all the apis and interfaces (object types) that you may be able to use while developing your web app or site. 2 angle_instanced_arrays api, reference, webgl, webgl extension the angle_instanced_arrays extension is part of the webgl api and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. 3 angle_instanced_arrays.drawarraysinstancedangle() angle_instanced_arrays, api, method, reference, webgl, webgl extension the angle_instanced_arrays.dr...
....vertexattribdivisorangle() method of the webgl api modifies the rate at which generic vertex attributes advance when rendering multiple instances of primitives with ext.drawarraysinstancedangle() and ext.drawelementsinstancedangle(). 6 abortcontroller api, abortcontroller, experimental, interface, reference the abortcontroller interface represents a controller object that allows you to abort one or more dom requests as and when desired. 7 abortcontroller.abortcontroller() api, abortcontroller, constructor, experimental, fetch, reference the abortcontroller() constructor creates a new abortcontroller object instance. 8 abortcontroller.abort() api, abortcontroller, experimental, fetch, method, reference, abort() the abort() method...
... abortcontroller, experimental, fetch, property, reference, signal the signal read-only property of the abortcontroller interface returns an abortsignal object instance, which can be used to communicate with/abort a dom request as desired. 10 abortsignal api, abortsignal, dom, experimental, interface, reference the abortsignal interface represents a signal object that allows you to communicate with a dom request (such as a fetch) and abort it if required via an abortcontroller object. 11 abortsignal.aborted api, abortsignal, experimental, property, reference, aborted the aborted read-only property returns a boolean that indicates whether the dom request(s) the signal is communicating with is/are aborted (true) or not (false). 12 abort...
...And 276 more matches
Index - Archive of obsolete content
of an obsolete feature or api, and how it worked. 2 .htaccess ( hypertext access ) 301 redirect, cache control, custom error pages, htaccess, permanent redirect, redirect file accessing : htaccess files can be opened using any text editor, like windows notepad, vin, sublime text editor or any other. syntax highliting support for .htaccess files less. 3 2015 mdn fellowship program 2015, archive, fellowship no summary! 4 api api, archive archived documentation about obsolete web standards apis. 5 navigator api, navigator features that used to hang off the navigator interface, but have since been removed. 6 navigator.moznotification api, deprecated, mobile, non-standard, property, 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 console/plain-text constructor for a console instance. 72 console/trace...
... 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 not displayed to the user. 85 frame/utils provides helper functions for working with platform internals like frames and browsers. ...
...And 148 more matches
Index
rtability layer, called the netscape portable runtime (nspr), which provides cross platform application programming interfaces (apis) for os specific apis like file system access, memory management, network communication, and multithreaded programming. nss offers lots of functionality; we'll walk through the list of modules, design principles, and important relevant standards. ...
...rder to allow interoperability between software and devices that perform cryptographic operations, nss conforms to a standard called pkcs#11. (note that it's important to look at the number 11, as there are other pkcs standards with different numbers that define quite different topics.) a software or hardware module conforming to the pkcs#11 standard implements an interface of c calls, which allow querying the characteristics and offered services of the module. multiple elements of nss's own modules have been implemented with this interface, and nss makes use of this interface when talking to those modules. ...
...ifferent numbers that define quite different topics.) a software or hardware module conforming to the pkcs#11 standard implements an interface of c calls, which allow querying the characteristics and offered services of the module. multiple elements of nss's own modules have been implemented with this interface, and nss makes use of this interface when talking to those modules. this strategy allows nss to work with many hardware devices (e.g., to speed up the calculations required for cryptographic operations, or to access smartcards that securely protect a secret key) and software modules (e.g., to allow to load such modules as a plugin that provides additional algorithms or stores key or trust information) that implement the pkcs#11 interface. a core element of nss is freebl, a base l...
...And 102 more matches
sslfnc.html
lt ssl_cipherprefgetdefault ssl_clearsessioncache ssl_configserversessionidcache ssl_configmpserversidcache ssl_inheritmpserversidcache nss_init sets up configuration files and performs other tasks required to run network security services. database files are opened read-only. syntax #include "nss.h" secstatus nss_init(char *configdir); parameter this function has the following parameter: configdir a pointer to a string containing the pathname of the directory where the certificate, key, and security module databases reside. returns 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.d...
...fied 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 appropriate cipher suites by calling one of the ssl export policy functions: nss_setdomesticpolicy, nss_setexportpolicy, and nss_setfrancepolicy configure the cipher suites for domestic, international, and french versions of software products with encryption features. ...
...licy functions: nss_setdomesticpolicy, nss_setexportpolicy, and nss_setfrancepolicy configure the cipher suites for domestic, international, and french versions of software products with encryption features. ssl_cipherpolicyset sets policy flags for individual cipher suites, one at a time. ...
...And 96 more matches
HTTP Index - HTTP
Web › HTTP › Index
und 277 pages: # page tags and summary 1 http http, hypertext, reference, tcp/ip, web, web development, l10n:priority hypertext transfer protocol (http) is an application-layer protocol for transmitting hypermedia documents, such as html. it was designed for communication between web browsers and web servers, but it can also be used for other purposes. http follows a classical client-server model, with a client opening a connection to make a request, then waiting until it receives a response. http is a stateless protocol, meaning that the server does not keep any data (state) between two requests. though often based on a tcp/ip layer, it can be used on any reliable transport layer, that is, a protocol that doesn't lose messages silently like udp does. rudp...
...te document is reconstructed from the different sub-documents fetched, for instance text, layout description, images, videos, scripts, and more 4 basics of http guide, http, overview http is a pretty extensible protocol. it relies on a few basic concepts like the notion of resources and uris, a simple structure of messages, and a client-server structure for the communication flow. on top of these basic concepts, numerous extensions have appeared over the years, adding new functionality and new semantics by creating new http methods or headers. 5 choosing between www and non-www urls guide, http, url a recurring question among website owners is whether to choose non-www or www urls. this page provides some advice on what's best. 6 data urls ...
...tionality and new semantics by creating new http methods or headers. 5 choosing between www and non-www urls guide, http, url a recurring question among website owners is whether to choose non-www or www urls. this page provides some advice on what's best. 6 data urls base64, guide, http, intermediate, url data urls, urls prefixed with the data: scheme, allow content creators to embed small files inline in documents. 7 evolution of http guide, http, needsupdate, needsupdate(http/3) http (hypertext transfer protocol) is the underlying protocol of the world wide web. http has evolved from an early protocol to exchange files in a semi-trusted laboratory environment, to the modern maze of the internet, now carrying images, videos in h...
...And 71 more matches
Index
Mozilla › Tech › XPCOM › Index
found 1275 pages: # page tags and summary 1 xpcom add-ons, extensions, landing, mozilla, xpcom xpcom is a cross platform component object model, similar to microsoft com. it has multiple language bindings, allowing xpcom components to be used and implemented in javascript, java, and python in addition to c++. 2 accessing the windows registry using xpcom add-ons, code snippets, extensions, needsclassification, windows registry when implementing windows-specific functionality, it is often useful to access the windows registry for information about the environment or other installed programs. to this end, there exist xpcom interfaces to read and write registry data. this article will show you how to use the available interfaces in...
... if mozilla decides to upgrade to a compiler that does not have the same abi as the current version, any built component may fail. it is a possiblity that is introduced when upgrading to a new compiler without recompiling everything. effectively, it is a different platform. 5 bundling multiple binary components binary xpcom components are sometimes required to implement low-level features for extensions. since binary components are linked against a single gecko sdk, a dependency to a particular version of gecko is created. if the component uses only "frozen" xpcom interfaces, there is a good chance the same binary component will work with different versions of gecko (version 1.8 and 1.9, for example). the more likely case is that the component uses "unfrozen" interf...
...omponents.utils.unwaivexrays undo a previous call to components.utils.waivexrays(), restoring xray vision for the caller. 49 components.utils.waivexrays waives xray vision for an object, giving the caller a transparent wrapper to the underlying object. 50 javaxpcom embedding, java, javaxpcom, mozilla, xpcom, xpcom:language bindings javaxpcom allows for communication between java and xpcom, such that a java application can access xpcom objects, and xpcom can access any java class that implements an xpcom interface. javaxpcom is not actively maintained. 51 development javaxpcom, xpcom:language bindings no summary! 52 examples javaxpcom, xpcom:language bindings no summary! 53 other resource...
...And 67 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
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 restrictions. web accessibility is formally defined and discussed at the w3c through the web acc...
...separate rendering engine. 32 block disambiguation, glossary the term block can have several meanings depending on the context. it may refer to: 33 block (css) css, codingscripting, design, glossary, html a block on a webpage is an html element that appears on a new line, i.e. underneath the preceding element in a horizontal writing mode, and above the following element (commonly known as a block-level element). for example, <p> is by default a block-level element, whereas <a> is an inline element — you can put several links next to one another in your html source and they will sit on the same line as one another in the rendered output. 34 block (scripting) codingscripting, glossary, javascript in javascript, a block is a collec...
...descendants. 40 breadcrumb accessibility, glossary, navigation, search, site map, breadcrumb a breadcrumb, or breadcrumb trail, is a navigational aid that is typically placed between a site's header and the main content, displaying either a hierarchy of the current page in relation to the the site's structure, from top level to current page, or a list of the links the user followed to get to the current page, in the order visited. 41 brotli brotli, glossary, reference, web performance, compression brotli is a general-purpose lossless compression algorithm. 42 browser glossary, navigation a web browser or browser is a program that retrieves and displays pages from the web, and lets users access further pages through hyperlinks. a ...
...And 58 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
easier method of building a firefox/thunderbird addon for developers who are well-acquainted with ides like netbeans, eclipse, etc. is to use netbeans (ide from sun microsystems) and foxbeans (plugin for netbeans, by teesoft). setting up your development environment in order to develop (and test) extensions in a most convenient way it is recommended to apply some changes to firefox. in the following you will find a brief description how to do so; a more detailed one can be found under setting up an extension development environment. create a development profile if you want to partition your everyday browsing environment from your development environment in firefox, set up a second profile for development. to create this dev profile start firefox with firefox.exe -no-remote -p dev on t...
...s used to contain language data that can be translated. to make an extension’s gui support multiple languages, you can include multiple locale packages, one for each language. the skin package this is used to include source files used as visual elements in the gui, including style sheets and images. most extensions include only one skin package, but you can include multiple skin packages to allow the gui to change with different themes. chrome url use a file called a “chrome manifest” to register chrome packages with firefox and start using them. to register a package, you use a special uri scheme called a “chrome url” to represent the path to the file. chrome urls are structured as: chrome://%package name%/%package type%/%relative path to source file% for example, the chrome ...
...hrome url use a file called a “chrome manifest” to register chrome packages with firefox and start using them. to register a package, you use a special uri scheme called a “chrome url” to represent the path to the file. chrome urls are structured as: chrome://%package name%/%package type%/%relative path to source file% for example, the chrome url for the firefox browser window is as follows: chrome://browser/content/browser.xul here, the package name is “browser”, the file “browser.xul”, and the type of the package is “content”. source files represented through chrome urls run with universalxpconnect privileges; even if they haven’t been granted “use xpconnect as local file” privileges, as discussed in chapter 4, they will be able to use xpcom functions (figure ...
...And 50 more matches
Python binding for NSS
are projects. nss is fips-140 certified. nss is built upon nspr because nspr provides an abstraction of common operating system services, particularly in the areas of networking and process management. python also provides an abstraction of common operating system services but because nss and nspr are tightly bound python-nss exposes elements of nspr. ...
...e nss and nspr are tightly bound python-nss exposes elements of nspr. for information on nss and nspr, see the following: network security services (nss). nss project page. netscape portable runtime. nspr project page. nspr reference. nspr api documentation. design goals nss and nspr are c language api's which python-nss "wraps" and exposes to python programs. the design of python-nss follows these basic guiding principles: be a thin layer with almost a one-to-one mapping of nss/nspr calls to python methods and functions. programmers already familiar with nss/nspr will be quite comfortable with python-nss. be "pythonic". the term pythonic means to follow accepted python paradigms and idoms in the python language and libraries. thus when deciding if the nss/nspr api should be rigi...
... basic guiding principles: be a thin layer with almost a one-to-one mapping of nss/nspr calls to python methods and functions. programmers already familiar with nss/nspr will be quite comfortable with python-nss. be "pythonic". the term pythonic means to follow accepted python paradigms and idoms in the python language and libraries. thus when deciding if the nss/nspr api should be rigidly followed or a more pythonic api provided the pythonic implementation wins because python programmers do not want to write c programs in python, rather they want their python code to feel like python code with the richness of full python. identifer names follow the preferred python style instead of the style in the nss/nspr c header files. classes are camel-case. class names always begin with a up...
...And 49 more matches
Drawing graphics - Learn web development
previous overview: client-side web apis next 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 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. graphics on the web as we talked about in our html multimedia and embedding module, the web was originally just text, which was very boring, so images were introduced — first via the <img> element and later vi...
...svg. this however was still not enough. while you could use css and javascript to animate (and otherwise manipulate) svg vector images — as they are represented by markup — there was still no way to do the same for bitmap images, and the tools available were rather limited. ...
... for bitmap images, and the tools available were rather limited. the web still had no way to effectively create animations, games, 3d scenes, and other requirements commonly handled by lower level languages such as c++ or java. the situation started to improve when browsers began to support the <canvas> element and associated canvas api — apple invented it in around 2004, and other browsers followed by implementing it in the years that followed. ...
...And 48 more matches
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
d summary 1 html: hypertext markup language html, html5, landing, web, l10n:priority html (hypertext markup language) is the most basic building block of the web. it defines the meaning and structure of web content. other technologies besides html are generally used to describe a web page's appearance/presentation (css) or functionality/behavior (javascript). 2 allowing cross-origin use of images and canvas advanced, cors, canvas, html, image, reference, security, storage, data html provides a crossorigin attribute for images that, in combination with an appropriate cors header, allows images defined by the <img> element that are loaded from foreign origins to be used in a <canvas> as if they had been loaded from the current origin. 3 app...
...utocapitalize, global attributes, html, reference the autocapitalize global attribute is an enumerated attribute that controls whether and how text input is automatically capitalized as it is entered/edited by the user. 10 class global attributes, html, reference the class global attribute is a space-separated list of the case-sensitive classes of the element. classes allow css and javascript to select and access specific elements via the class selectors or functions like the dom method document.getelementsbyclassname. 11 contenteditable editing, global attributes, html, reference, text editing, contenteditable, text entry, text input the contenteditable global attribute is an enumerated attribute indicating if the element should be editable by ...
...ents via the class selectors or functions like the dom method document.getelementsbyclassname. 11 contenteditable editing, global attributes, html, reference, text editing, contenteditable, text entry, text input the contenteditable global attribute is an enumerated attribute indicating if the element should be editable by the user. ...
...And 43 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
Web › HTTP › CORS
s a resource that has a different origin (domain, protocol, or port) from its own. an example of a cross-origin request: the front-end javascript code served from https://domain-a.com uses xmlhttprequest to make a request for https://domain-b.com/data.json. for security reasons, browsers restrict cross-origin http requests initiated from scripts. for example, xmlhttprequest and the fetch api follow the same-origin policy. this means that a web application using those apis can only request resources from the same origin the application was loaded from unless the response from other origins includes the right cors headers. 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 fetc...
...ssion of cross-origin resource sharing from a server perspective (including php code snippets) can be found in the server-side access control (cors) article. simple requests some requests don’t trigger a cors preflight. those are called “simple requests” in this article, though the fetch spec (which defines cors) doesn’t use that term. ...
...ing from a server perspective (including php code snippets) can be found in the server-side access control (cors) article. simple requests some requests don’t trigger a cors preflight. those are called “simple requests” in this article, though the fetch spec (which defines cors) doesn’t use that term. ...
...And 39 more matches
Setting up your own test automation environment - Learn web development
n 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. different browsers require different drivers to allow webdriver to communicate with and control them. see platforms supported by selenium for more information on where to get browser drivers from, etc. we will cover writing and running selenium tests using node.js, as it is quick and easy to get started, and a more familiar environment for front end devs. note: if you want to find out how to use webdriver with other server-side environments, also...
...nt end devs. note: if you want to find out how to use webdriver with other server-side environments, also check out platforms supported by selenium for some useful links. setting up selenium in node to start with, set up a new npm project, as discussed in setting up node and npm in the last chapter. call it something different, like selenium-test. ...
...all it something different, like selenium-test. next, we need to install a framework to allow us to work with selenium from inside node. we are going to choose selenium's official selenium-webdriver, as the documentation seems fairly up-to-date and it is well-maintained. if you want different options, webdriver.io and nightwatch.js are also good choices. to install selenium-webdriver, run the following command, making sure you are inside your project folder: npm install selenium-webdriver note: it is still a good idea to follow these steps even if you previously installed selenium-webdriver and downloaded the browser drivers. you should make sure that everything is up-to-date. ...
...And 38 more matches
LiveConnect Overview - Archive of obsolete content
ts 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 java array, accessed from within javascript code. javaclass a javascript reference to a java class. javaobject a wrapped java object, accessed from within javascript code. javapackage a javascript reference to a java package. note: because ja...
...e data types for the other language when you use liveconnect. see data type conversion for complete information. in some ways, the existence of the liveconnect objects is transparent, because you interact with java in a fairly intuitive way. for example, you can create a java string object and assign it to the javascript variable mystring by using the new operator with the java constructor, as follows: var mystring = new java.lang.string("hello world"); in the previous example, the variable mystring is a javaobject because it holds an instance of the java object string. as a javaobject, mystring has access to the public instance methods of java.lang.string and its superclass, java.lang.object. these java methods are available in javascript as methods of the javaobject, and you can call them ...
... mystring = new java.lang.string("hello world"); in the previous example, the variable mystring is a javaobject because it holds an instance of the java object string. as a javaobject, mystring has access to the public instance methods of java.lang.string and its superclass, java.lang.object. these java methods are available in javascript as methods of the javaobject, and you can call them as follows: mystring.length(); // returns 11 static members can be called directly on the javaclass object. alert(java.lang.integer.max_value); //alerts 2147483647 the packages object if a java class is not part of the java, sun, or netscape packages, you access it with the packages object. for example, suppose the redwood corporation uses a java package called redwood to contain various java classes tha...
...And 36 more matches
A first splash into JavaScript - Learn web development
mmer brain" in five minutes, but we will give you plenty of opportunity to practice thinking like a programmer throughout the course. with that in mind, let's look at the example we'll be building up in this article, and review the general process of dissecting it into tangible tasks. ...
... max-width: 800px; min-width: 480px; margin: 0 auto; } .lastresult { color: white; padding: 3px; } </style> </head> <body> <h1>number guessing game</h1> <p>we have selected a random number between 1 and 100. see if you can guess it in 10 turns or fewer. ...
... guess it in 10 turns or fewer. ...
...And 35 more matches
Introduction to automated testing - Learn web development
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 selenium, but allow you to access their set up remotely using a simple interface, saving you the hassle of setting up your own testing system. we will look at how to set up your own selenium-based testing system in the next article. in this article, we'll look at how to set up a task runner, and use the basic functionality of commercial systems like the ones mentioned above. note: the above two categories are no...
...em in the next article. in this article, we'll look at how to set up a task runner, and use the basic functionality of commercial systems like 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...
...ng 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 to install it from nodejs.org: download the installer for your system from the above site. (if you already have node and npm installed, jump to point 4) install it like you would any other program. note that node comes with node package manager (npm), which allows you to easily install packages, share your own packages with others, and run useful scripts on your projects. once the install completes, test that node is installed by typing the following into the terminal, which returns the installed versions of node and npm: node -v npm -v if you've got node/npm already installed, you should update them to their latest versions. to update node, the mos...
...And 34 more matches
WebIDL bindings
ous helper objects and utility methods in dom/bindings that are also all in the mozilla::dom namespace and whose headers are all exported into mozilla/dom (placed in $objdir/dist/include by the build process). adding webidl bindings to a class to add a webidl binding for interface myinterface to a class mozilla::dom::myinterface that's supposed to implement that interface, you need to do the following: if your interface doesn't inherit from any other interfaces, inherit from nswrappercache and hook up the class to the cycle collector so it will trace the wrapper cache properly. note that you may not need to do this if your objects can only be created, never gotten from other objects. if you also inherit from nsisupports, make sure the nsisupports comes before the nswrappercache in you...
...arentobject chain will eventually get you to a window, so that every webidl object is associated with a particular window. for example, nsinode::getparentobject returns the node's owner document. the return type of getparentobject doesn't matter other than it must either singly-inherit from nsisupports or have a corresponding tosupports method that can produce an nsisupports from it. ...
...again, if you do not need wrapper caching you don't need to do this. ...
...And 34 more matches
Index - HTTP
Web › HTTP › Headers › Index
leading white space before the value is ignored. 2 accept http, http header, reference, request header the accept request http header advertises which content types, expressed as mime types, the client is able to understand. ...
...leading white space before the value is ignored. 2 accept http, http header, reference, request header the accept request http header advertises which content types, expressed as mime types, the client is able to understand. ...
...r the accept-charset request http header advertises which character set the client is able to understand. using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice within the content-type response header. browsers usually don't set this header as the default value for each content type is usually correct and transmitting it would allow easier fingerprinting. 4 accept-encoding content negotiation, http, http header, reference, request header the accept-encoding request http header advertises which content encoding, usually a compression algorithm, the client is able to understand. using content negotiation, the server selects one of the proposals, uses it and informs the client of its choice with the content...
...And 34 more matches
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
rly for various xul element types. sections in bold are to draw attention to pieces that are often overlooked for visual layouts. underlined text may be read by the screen reader. 5 attribute (xul) xul attributes, xul reference no summary! 6 flexgroup "flexgroup" is used to group flexible elements together and should be set to an integer. elements with a lower flexgroup are flexed first. when those elements have reached their maximum sizes, the elements with the next higher flexgroup are flexed. this process continues until there are no more elements remaining. the same process occurs when decreasing the size, except in the other direction. 7 accelerated xul, xul attribute, xul reference no summary! 8 acceltext xul...
...tributes, xul reference no summary! 10 accesskey reference, xul, xul attributes, xul reference, accesskey no summary! 11 activetitlebarcolor xul attributes, xul reference no summary! 12 afterselected xul attributes, xul reference no summary! 13 align reference, référence(2), xul no summary! 14 allowevents xul attributes, xul reference no summary! 15 allownegativeassertions xul attributes, xul reference no summary! 16 alternatingbackground xul attributes, xul reference no summary! 17 alwaysopenpopup xul attributes, xul reference no summary! 18 attribute xul attributes, xul reference no summary! ...
... 31 browserid xul, xul reference no summary! 32 button.type xul attributes, xul reference no summary! 33 buttonaccesskeyaccept xul attributes, xul reference no summary! 34 buttonaccesskeycancel xul attributes, xul reference ...
...And 33 more matches
Client-side storage - Learn web development
or modern web sites are dynamic — they store data on the server using some kind of database (server-side storage), then run server-side code to retrieve needed data, insert it into static page templates, and serve the resulting html to the client to be displayed by the user's browser. client-side storage works on similar principles, but has different uses. it consists of javascript apis that allow you to store data on the client (i.e. on the user's machine) and then retrieve it when needed. this has many distinct uses, such as: personalizing site preferences (e.g. showing a user's choice of custom widgets, color scheme, or font size). persisting previous site activity (e.g. storing the contents of a shopping cart from a previous session, remembering if a user was previously logged in).
...w to use cookies in this article. however, this does not mean cookies are completely useless on the modern-day web — they are still used commonly to store data related to user personalization and state, e.g. session ids and access tokens. for more information on cookies see our using http cookies article. new school: web storage and indexeddb the "easier" features we mentioned above are as follows: the web storage api provides a very simple syntax for storing and retrieving smaller, data items consisting of a name and a corresponding value. this is useful when you just need to store some simple data, like the user's name, whether they are logged in, what color to use for the background of the screen, etc. the indexeddb api provides the browser with a complete database system for stori...
...st need to store some simple data, like the user's name, whether they are logged in, what color to use for the background of the screen, etc. the indexeddb api provides the browser with a complete database system for storing complex data. this can be used for things from complete sets of customer records to even complex data types like audio or video files. you'll learn more about these apis below. the future: cache api some modern browsers support the new cache api. this api is designed for storing http responses to specific requests, and is very useful for doing things like storing website assets offline so the site can subsequently be used without a network connection. cache is usually used in combination with the service worker api, although it doesn't have to be. use of cache and s...
...And 32 more matches
SVG documentation index - SVG: Scalable Vector Graphics
Web › SVG › Index
s, vector graphics, web, l10n:priority scalable vector graphics (svg) are an xml-based markup language for describing two-dimensional based vector graphics.xml 2 applying svg effects to html content css, guide, html, svg modern browsers support using svg within css styles to apply graphical effects to html content. 3 compatibility sources svg the following sources are used for the compatibility tables on svg elements and attributes: 4 content type needstechnicalreview, svg, types, data types svg makes use of a number of data types. this article lists these types along with their syntax and descriptions of what they're used for. 5 linking guide, svg the target attribute on the svg <a> element doesn't work...
...or not the element on which it appears should be rendered. 15 svg core attributes attribute, intermediate, reference, svg the svg core attributes are all the common attributes that can be specified on any svg element. 16 svg event attributes advanced, attribute, draft, landing, needsupdate, svg event attributes always have their name starting with "on" followed by the name of the event for which they are intended. they specifies some script to run when the event of the given type is dispatched to the element on which the attributes are specified. 17 svg presentation attributes attribute, beginner, draft, reference, svg svg presentation attributes are css properties that can be used as attributes on svg elements. 18 svg ...
...ative. 21 additive needscompattable, needsexample, svg, svg attribute no summary! 22 alignment-baseline svg, svg attribute the alignment-baseline attribute specifies how an object is aligned with respect to its parent. this property specifies which baseline of this element is to be aligned with the corresponding baseline of the parent. for example, this allows alphabetic baselines in roman text to stay aligned across font size changes. it defaults to the baseline with the same name as the computed value of the alignment-baseline property. 23 alphabetic deprecated, svg, svg attribute the alphabetic attribute defines the lower baseline of a font. it has the same syntax and semantics as the baseline descriptor within an @font-face. ...
...And 32 more matches
TypeScript support in Svelte - Learn web development
objective: learn how to configure and use typescript when developing svelte applications. note that our application is fully functional and porting it to typescript is completely optional. there are different opinions about it, and in this chapter we will talk briefly about the pros and cons of using typescript. even if you are not planning to adopt it, this article will be useful for allowing you to learn what it has to offer and help you make your own decision. if you are not interested at all in typescript, you can skip to the next chapter, where we will look at different options for deploying our svelte applications, further resources, and more. code along with us git clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte...
...contributors, we have an official solution ready to be put to the test. in this section we'll show you how to setup a svelte project with typescript support to give it a try. why typescript? recently typescript has seen enormous growth. from last year's github octoverse report we can see that typescript is the 7th most used and 5th fastest growing language used on github. according to stackoverflow's 2019 developer survey it is the third most loved language, right behind rust and python. so typescript is going through a great phase of adoption. typescript's main advantages are: early spotted bugs: the compiler checks types at compile time and provides error reporting. readability: static typing gives the code more structure, making it self-documenting and more readable. rich ide supp...
... it is the third most loved language, right behind rust and python. so typescript is going through a great phase of adoption. typescript's main advantages are: early spotted bugs: the compiler checks types at compile time and provides error reporting. readability: static typing gives the code more structure, making it self-documenting and more readable. rich ide support: type information allows code editors and ides to offer features like code navigation, autocompletion, and smarter hints. safer refactoring: types allows ides to know more about your code, and assist you while refactoring large portions of your code base. type inference: enables you to take advantage of many typescript features even without declaring variable types. availability of new and future javascript features:...
...And 31 more matches
Details of the object model - JavaScript
this chapter attempts to clarify the situation. this chapter assumes that you are already somewhat familiar with javascript and that you have used javascript functions to create simple objects. class-based vs. ...
...e, such as javascript, does not make this distinction: it simply has objects. a prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object. any object can specify its own properties, either when you create it or at run time. in addition, any object can be associated as the prototype for another object, allowing the second object to share the first object's properties. defining a class in class-based languages, you define a class in a separate class definition. in that definition you can specify special methods, called constructors, to create instances of the class. a constructor method can specify initial values for the instance's properties and perform other processing appropriate at creation time...
...efine a class in a separate class definition. in that definition you can specify special methods, called constructors, to create instances of the class. a constructor method can specify initial values for the instance's properties and perform other processing appropriate at creation time. you use the new operator in association with the constructor method to create class instances. javascript follows a similar model, but does not have a class definition separate from the constructor. instead, you define a constructor function to create objects with a particular initial set of properties and values. any javascript function can be used as a constructor. you use the new operator with a constructor function to create a new object. note that ecmascript 2015 introduces a class declaration: jav...
...And 31 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
3c-compliant ones. before i go into the differences between mozilla and internet explorer, i'll cover some basic ways you can make a web application extensible in order to add new browser support later. since different browsers sometimes use different apis for the same functionality, you can often find multiple if() else() 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. ...
...ode that handles useragents often can make mistakes when new browser versions arrive, thus requiring code changes. it is much better and more reliable to sniff by browser capability or object feature support. you can usually do this by testing the required functionality in javascript. for example, rather than: if (ismozilla || isie5) you would use: if (document.getelementbyid) this would allow other browsers that support that w3c standard method, such as opera or safari, to work without any changes. useragent sniffing makes sense in very limited cases where you really do want to know the exact browser in use, such as when you need to work around a bug in a specific version of a specific browser. for all other purposes you should check for the feature you need rather than the browser...
...h as opera or safari, to work without any changes. useragent sniffing makes sense in very limited cases where you really do want to know the exact browser in use, such as when you need to work around a bug in a specific version of a specific browser. for all other purposes you should check for the feature you need rather than the browsers you think will support that feature. ...
...And 30 more matches
Introduction to CSS layout - Learn web development
and introduce some of the concepts we'll be covering throughout this module. prerequisites: the basics of html (study introduction to html), and an idea of how css works (study introduction to css.) objective: to give you an overview of css page layout techniques. each technique can be learned in greater detail in subsequent tutorials. ...
...ction to html), and an idea of how css works (study introduction to css.) objective: to give you an overview of css page layout techniques. each technique can be learned in greater detail in subsequent tutorials. css page layout techniques allow us to take elements contained in a web page and control where they are positioned relative to their default position in normal layout flow, the other elements around them, their parent container, or the main viewport/window. the page layout techniques we'll be covering in more detail in this module are normal flow the display property flexbox grid floats positioning table layout multiple-column layout each technique has its uses, advantages, and disadvantages, and no technique is designed to be used in isolation. by und...
... detail in this module are normal flow the display property flexbox grid floats positioning table layout multiple-column layout each technique has its uses, advantages, and disadvantages, and no technique is designed to be used in isolation. by understanding what each method is designed for you will be in a good place to understand which is the best layout tool for each task. normal flow normal flow is how the browser lays out html pages by default when you do nothing to control page layout. ...
...And 30 more matches
Index - Learn web development
tood our wai-aria basics article. 12 what is accessibility? at, accessibility, article, beginner, css, codingscripting, html, javascript, learn, tools, users, assistive technology, keyboard, screan reader, screenreader this article should have given you a useful high-level overview of accessibility, shown you why it's important, and looked at how you can fit it into your workflow. you should now also have a thirst to learn about the implementation details that can make sites accessible, and we'll start on that in the next section, looking at why html is a good basis for accessibility. 13 aprender y obtener ayuda beginner, learn, learning, web development, getting help it is great that you are putting some time into learning a new set of skills, but th...
...nical side. of course you must be familiar with the technique of your craft, but what really matters is what you want to accomplish. yes, it seems obvious, but too many projects fail not from a lack of technical know-how, but from lack of goals and vision. 17 how do i use github pages? beginner, github, guide, web, gh-pages, git, publish github is a "social coding" site. it allows you to upload code repositories for storage in the git version control system. you can then collaborate on code projects, and the system is open-source by default, meaning that anyone in the world can find your github code, use it, learn from it, and improve on it. you can do that with other people's code too! this article provides a basic guide to publishing content using github's gh-pages feat...
...thing on the web? beginner, webmechanics, cost, hosting, web development tools when launching a website, you may spend nothing, or your costs may go through the roof. in this article we discuss how much everything costs, and how you get what you pay (or don't pay). 24 what html features promote accessibility? accessibility, beginner, html, learn, needscontent the following content describes specific features of html that can be used to make a web page more accessible to people with different disabilities. 25 what are browser developer tools? beginner, browser, css, codingscripting, dev tools, html, javascript, learn the devtools live inside your browser in a subwindow that looks roughly like this, depending on what browser you are using: ...
...And 30 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
ll utilize some techniques for accessing dom nodes and executing methods like focus() and select(). we will also see how to declare and clean-up event listeners on dom elements. we also need to learn a bit about component lifecycle, to understand when these dom nodes get mounted and and unmounted from the dom and how we can access them. ...
... newtodo: displays the <input> field and add button for adding a new todo. ...
... charge of displaying the buttons and emitting the corresponding events. create a new file — components/moreactions.svelte. when the first button is clicked, we'll emit a checkall event to signal that all the todos should be checked/unchecked. when the second button is clicked, we'll emit a removecompleted event to signal that all of the completed todos should be removed. ...
...And 30 more matches
Positioning - Learn web development
previous overview: css layout next positioning allows you to take elements out of the normal document layout flow, and make them behave differently; for example sitting on top of one another, or always remaining in the same place inside the browser viewport. this article explains the different position values, and how to use them. prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css.) objective: to learn how css positioning works. we'd like you to follow along with the exercises on your local computer, if possible — grab a copy of 0_basic-flow.html from our github repo (source code here) and use that as a starting point. ...
...ction to html), and an idea of how css works (study introduction to css.) objective: to learn how css positioning works. we'd like you to follow along with the exercises on your local computer, if possible — grab a copy of 0_basic-flow.html from our github repo (source code here) and use that as a starting point. introducing positioning the whole idea of positioning is to allow us to override the basic document flow behavior described above, to produce interesting effects. what if you want to slightly alter the position of some boxes inside a layout from their default layout flow position, to give a slightly quirky, distressed feel? positioning is your tool. or if you want to create a ui element that floats over the top of other parts of the page, and/or always sits in ...
...positioning makes such layout work possible. there are a number of different types of positioning that you can put into effect on html elements. to make a specific type of positioning active on an element, we use the position property. ...
...And 29 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
discusses what they are useful for, and considers their inherent issues. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand asynchronous loops and intervals and what they are useful for. introduction for a long time, the web platform has offered javascript programmers a number of functions that allow them to asynchronously execute code after a certain time interval has elapsed, and to repeatedly execute a block of code asynchronously until you tell it to stop. these functions are: settimeout() execute a specified block of code once after a specified time has elapsed. setinterval() execute a specified block of code repeatedly with a fixed time delay between each call. requestanimationf...
...ronously until you tell it to stop. these functions are: settimeout() execute a specified block of code once after a specified time has elapsed. setinterval() execute a specified block of code repeatedly with a fixed time delay between each call. requestanimationframe() the modern version of setinterval(). executes a specified block of code before the browser next repaints the display, allowing an animation to be run at a suitable framerate regardless of the environment it is being run in. the asynchronous code set up by these functions runs on the main thread (after their specified timer has elapsed). it's important to know that you can (and often will) run other code before a settimeout() call executes, or between iterations of setinterval(). depending on how processor-intensiv...
...these operations are, they can delay your async code even further, as any async code will execute only after the main thread is available. (in other words, when the stack is empty.) you will learn more on this matter as you progress through this article. in any case, these functions are used for running constant animations and other background processing on a web site or application. in the following sections we will show you how they can be used. settimeout() as we said before, settimeout() executes a particular block of code once after a specified time has elapsed. it takes the following parameters: a function to run, or a reference to a function defined elsewhere. a number representing the time interval in milliseconds (1000 miliseconds equals 1 second) to wait before executing th...
...And 29 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. <input> types how an <input> works varies considerably depending on the value of its type attribute, hence the different types are covered in their own separate reference pages. if this attribute is not specified, the default type adopted is text. the available types are as follows: type description basic examples spec button a push button with no default behavior displaying the value of the value attribute, empty by default. <input type="button" name="button" /> checkbox a check box allowing single values to be selected/deselected. <input type="checkbox" name="checkbox"/> ...
...a number. displays a spinner and adds default validation when supported. displays a numeric keypad in some devices with dynamic keypads. <input type="number" name="number"/> html5 password a single-line text field whose value is obscured. will alert user if site is not secure. <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="...
...ement interface, they technically share the exact same set of attributes. however, in reality, most attributes have an effect on only a specific subset of input types. in addition, the way some attributes impact an input depends on the input type, impacting different input types in different ways. this section provides a table listing all the attributes with a brief description. this table is followed by a list describing each attribute in greater detail, along with which input types they are associated with.those that are common to most or all input types are defined in greater detail below. attributes that are unique to particular input types—or attributes which are common to all input types but have special behaviors when used on a given input type—are instead documented on those type...
...And 29 more matches
JXON - Archive of obsolete content
create a dom tree article. if you have already have a dom tree from using xmlhttprequest, skip to the next paragraph. note: if you are using an instance of xmlhttprequest in order to retrieve your xml file, please use the yourrequest.responsexml property to get a parsed xml document. don't use yourrequest.responsetext! the algorithms proposed here (see: #1, #2, #3, #4) will consider only the following types of nodes and their attributes: document (only as function argument), documentfragment (only as function argument), element, text (never as function argument), cdatasection (never as function argument), attr (never as function argument). this is a good and standardized compromise for a javascript usage, since all of the information of an xml document is contained in these node t...
...all of the information of an xml document is contained in these node types. all other information (like processing instructions, schemas, comments, etc.) will be lost. this type of algorithm is still considered lossless, since what is lost is meta-information and not information. ...
...still considered lossless, since what is lost is meta-information and not information. in order to avoid conflicts, the representation of nodes and attributes names is case insensitive (always rendered in lower case), so objects' local property names set using javascript must always have some kind of capitalization (that is, at least one capital letter somewhere in their names), as you can see below. the following algorithms are somewhat based on the parker convention, version 0.4, which prescribes the transformation of tags names into object properties names and the recognition of the typeof of all the collected text content of each tag (plain text parsing); but with some differences (so, one can say that we follow a our convention). moreover, all algorithms are equally lossless for the co...
...And 27 more matches
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 re...
...deciding if you should create a new function or object. one such technique is the single responsibility principle — that is, a component should ideally only do one thing. if it ends up growing, it should be split into smaller subcomponents. both approaches should complement each other, and help you decide how to better organize your components. eventually, we will split up our app into the following components: alert.svelte: a general notification box for communicating actions that have occurred. newtodo.svelte: the text input and button that allow you to enter a new todo item. filterbutton.svelte: the all, active, and completed buttons that allow you to apply filters to the displayed todo items. todosstatus.svelte: the "x out of y items completed" heading. todo.svelte: an individu...
... in this article we will concentrate on creating the filterbutton and todo components; we'll get to the others in future articles. let's get started. ...
...And 27 more matches
Working with Svelte stores - Learn web development
ing stores we will create an alert component that shows notifications on screen, which can receive messages from any component. in this case, the alert component is independent from the rest — it is not a parent or child of any other — so the messages don't fit into the component hierarchy. we will also see how to develop our own custom store to persist the todo information to web storage, allowing our todos to persist over page reloads. code along with us git clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/06-stores or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/06-stores remember to run npm install && npm r...
...t hierarchy gets complex, it might become too difficult for components to relay data between each other. in that case, moving to a global data store might be 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 ...
... whenever a notification arrives the alert component will be in charge of displaying it on screen. creating a store let's start by creating a writable store. any component will be able to write to this store, and the alert component will subscribe to it and display a message whenever the store is modified. create a new file — stores.js — inside your src directory. give it the following content: import { writable } from 'svelte/store' export const alert = writable('welcome to the to-do list app!') note: stores can be defined and used outside of svelte components, so you can organize them in any way you please. in the above code we import the writable() function from svelte/store and use it to create a new store called alert with an initial value of "welcome to the ...
...And 27 more matches
Performance best practices for Firefox front-end engineers
script to cause delays in event processing or painting. that means that the more code we can get off of the main thread, the more that thread can respond to user events, paint, and generally be responsive to the user. you might want to consider using a worker if you need to do some computation that can be done off of the main thread. if you need more elevated privileges than a standard worker allows, consider using a chromeworker, which is a firefox-only api which lets you create workers with more elevated privileges. use requestidlecallback() if you simply cannot avoid doing some kind of long job on the main thread, try to break it up into smaller pieces that you can run when the browser has a free moment to spare, and the user isn't doing anything. you can do that using requestidlecallb...
...pplied on demand rather than at load time, which makes initial construction of the xul document faster. get familiar with the pipeline that gets pixels to the screen learn how pixels you draw make their way to the screen. knowing the path they will take through the various layers of the browser engine will help you optimize your code to avoid pitfalls. the rendering process goes through the following steps: the above image is used under creative commons attribution 3.0, courtesy of this page from our friends at google, which itself is well worth the read. for a very down-to-earth explanation of the style, layout, paint and composite steps of the pipeline, this hacks blog post does a great job of explaining it. to achieve a 60 fps frame rate, all of the above has to happen in 16 mill...
...l worth the read. for a very down-to-earth explanation of the style, layout, paint and composite steps of the pipeline, this hacks blog post does a great job of explaining it. to achieve a 60 fps frame rate, all of the above has to happen in 16 milliseconds or less, every frame. note that requestanimationframe() lets you queue up javascript to run right before the style flush occurs. ...
...And 26 more matches
Web Replay
replaying processes preserve all the same js behavior, dom structures, graphical updates, and most other behaviors that occurred while recording. devtools' debugger and console can be used to inspect and control the replay. getting started to enable web replay (macos and firefox nightly only), go to devtools settings and select "enable webreplay". ...
...ger and console can be used to inspect and control the replay. getting started to enable web replay (macos and firefox nightly only), go to devtools settings and select "enable webreplay". web replay's features can only be used in a tab that is recording or replaying. there are a few ways to start recording a tab: record current tab open the developer tools and click the button indicated below. this will refresh the tab and start recording. the button will be colored blue when the tab is being recorded. it can be clicked again to stop recording. open a new tab in recording mode click the 'tools -> web developer -> web replay -> reload and record tab' menu item. this has the same effect as above but can be used when the developer tools are not open. open a saved recording in ...
...en the rewind button. while replaying old behavior, the tab can't be interacted with. to resume recording and interacting with the tab, press the pause button and then the play button to run forward to the end of the recording. save recording and replay on the same machine clicking the 'tools -> web developer -> web replay -> save recording' menu item when a recording tab is open will allow the entire recording to be saved to a file. clicking the 'tools -> web developer -> web replay -> load recording in new tab' menu item will start a new tab which replays the recording to the end. the developer tools can be used to interact with this tab in the same way as a recording tab, though playing forward to the end will pause the tab instead of allowing further recording. save recording...
...And 26 more matches
Migrating from Firebug - Firefox Developer Tools
for the latest developer tools and features, try firefox developer edition. download firefox developer edition general activation firebug's activation is url based respecting the same origin policy. that means that when you open a page on the same origin in a different tab, firebug gets opened automatically. ...
.../ cmd+opt+c. the devtools share the same shortcuts, but also provide shortcuts for the different panels. e.g. the network monitor can be opened via ctrl+shift+q / cmd+opt+q, the web console via ctrl+shift+k / cmd+opt+k and the debugger via ctrl+shift+s / cmd+opt+s. web console the web console is the equivalent of firebug's console panel. it shows log information associated with a web page and allows you to execute javascript expressions via its command line. the display between both is somewhat different. this may be changed in bug 1269730. filter log messages firebug offers two ways to filter log messages, via the options menu and via the filter buttons within the toolbar. the developer tools console offers similar functionality via the filter buttons inside its toolbar — centralized a...
...ge. the developer tools share the same api, so your console.* statements will continue to work. persist logs in firebug you can click the persist button within the toolbar to keep the logged messages between page navigations and reloads. in the devtools this option is called enable persistent logs and is available within the toolbox options panel. server logs firebug extensions like firephp allow to log server-side messages to the firebug console. this functionality is already integrated into the devtools using the chromelogger protocol and doesn't require any extensions to be installed. command history the command history available through a button in firebug's command line, is available by pressing ↑/↓ within the devtools command line. inspect object properties by clicking on an...
...And 26 more matches
Using Feature Policy - HTTP
the feature-policy header is still in an experimental state, and is subject to change at any time. ...
... the feature-policy header is still in an experimental state, and is subject to change at any time. ...
... the feature-policy header is still in an experimental state, and is subject to change at any time. ...
...And 26 more matches
Expressions and operators - JavaScript
this section describes the operators and contains information about operator precedence. ...
...example, x++ or ++x. assignment operators an assignment operator assigns a value to its left operand based on the value of its right operand. the simple assignment operator is equal (=), which assigns the value of its right operand to its left operand. that is, x = y assigns the value of y to x. ...
...t attempts to convert them to an appropriate type for the comparison. this behavior generally results in comparing the operands numerically. the sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. these operators do not attempt to convert the operands to compatible types before checking equality. the following table describes the comparison operators in terms of this sample code: var var1 = 3; var var2 = 4; comparison operators operator description examples returning true equal (==) returns true if the operands are equal. 3 == var1 "3" == var1 3 == '3' not equal (!=) returns true if the operands are not equal. var1 != 4 var2 != "3" ...
...And 26 more matches
Theme changes in Firefox 2 - Archive of obsolete content
browsing/browser-protection.css new file containing the overlay that's drawn over the browser when you browse to a suspected phishing site. search/enginemanager.xul enginemanager.css new file containing the ui for the search engine manager window. toolkit/mozapps/preferences/fontscaling.xul - removed from firefox 2. changes to the default theme the table below lists all the changes made in the default theme for firefox 2; you can use this information as a starting point for figuring out the changes you need to make. file description of change browser/bookmarks/addbookmark.css updated to include microsummary-related css changes. browser/bookmarks/bookmarksproperties.css new file; includes microsummary-related css. ...
... indicates a site may be fraudulent. browser/safebrowsing/close16x16.png new file; this is the icon displayed in the safe browsing warning window as a close box for the window. browser/safebrowsing/dim.png new file; this is a graphic overlaid on top of the contents of the window to "dim" it when the safe browsing warning window is displayed. it should use translucency to allow the window contents to be visible through it. browser/safebrowsing/tail.png new file; this is the "tail" of the talk-bubble style window used to indicate that a site may be fraudulent. browser/safebrowsing/warning16x16.png new file; this is the 16x16 pixel version of the warning icon displayed in the url bar when the safe browsing warning window is displayed. brow...
...rowser/search-provider-bkgnd.png new file; the background drawn behind the search provider icon when it's located at the right end of the search bar. global/about.css new file; css used in the application's about box. global/alltabs-box-bkgnd.png new file; the background for the "all tabs" drop-down menu at the right side of the tab bar. global/alltabs-box-overflow-bkgnd.png new file; the background for the "all tabs" drop-down menu when there are enough tabs to activate tab bar scrolling. global/browser.css revised to support new styles for the main browser window. global/globalbindings.xml updated to support changes to the tab bar, including per-tab close buttons. global/icons/alltabs.png not actually used; left over...
...And 25 more matches
Starting WebLock
the xpcom shutdown observation, asubject and adata are not defined, and atopic is defined as the string "xpcom-shutdown". if your object would like to register for this or other events, it first must implement the nsiobserver interface. once you do this, the observer service implementing nsiobserverservice can notify your object of registered events by means of this interface, as in the figure below. the observer interfaces the above figure shows the observer service maintaining a list of all registered nsiobserver objects. when the notification is made, the nsiobserverservice broadcasts the notification from the caller of the notifyobserver() to the nsiobserver object's observe() method. this is a very useful decoupling of different objects. the nsiobserver is a generic interface for pa...
...l decoupling of different objects. the nsiobserver is a generic interface for passing messages between two or more objects without defining a specific frozen interface, and it's one of the ways in which extensibility is built into xpcom. the implementation of the nsiobserver interface in the weblock component is similar to the implementation for the nsifactory interface. xxx what is example 2?following example 2, you change the class definition to support the nsiobserver interface and change ns_impl_isupports1 so that the queryinterface implementation knows that the component also supports nsiobserver. the weblock class definition with support for startup observation is below. class weblock: public nsiobserver { public: weblock(); virtual ~weblock(); ns_decl_isupports ns_...
..., we want to have the component start up every time the application does). this is where a new service that manages sets of related data comes in handy. this service, the nsicategoryservice, is what xpcom and gecko embedding applications use to persist lists of nsiobserver components that want to have startup notification. the nsicategoryservice maintains sets of name-value pairs like the one below. the category manager every category is identified by a string that represents the name of the category. each category contains a set of name-value pairs. for example, you might have a category named "important people" in which the name-value pairs would be names and phone numbers. the format of the name-value pair is left up to you. this data structure is more than enough to support the per...
...And 25 more matches
Block and Line Layout Cheat Sheet - Archive of obsolete content
the details of block and line layout are tricky; this document serves as a "cheat sheet" that describes how the vagary of different state flags control what's going on. it's a work-in-progress, with questions in red highlight. if you know the answer, please pass it along to me so i can update the document. ...
...cument serves as a "cheat sheet" that describes how the vagary of different state flags control what's going on. it's a work-in-progress, with questions in red highlight. if you know the answer, please pass it along to me so i can update the document. objects this section presents some of the classes involved in block and line reflow, along with important members of each object that control reflow processing. nsframe the base class for all frames. mflags flags set on the frame to indicate its state. these flags can be grouped into two categories: flags which affect all frames ("public" flags), and flags that are reserved for an individual frame's private use ("private" flags). ns_frame_in_reflow this bit is set when the frame is being actively being reflowed. by default it is set ...
...g. nsframe the base class for all frames. mflags flags set on the frame to indicate its state. these flags can be grouped into two categories: flags which affect all frames ("public" flags), and flags that are reserved for an individual frame's private use ("private" flags). ns_frame_in_reflow this bit is set when the frame is being actively being reflowed. by default it is set in willreflow(), and unset in didreflow(). many frames' reflow() method verifies that the bit is set with an assertion. ns_frame_first_reflow this flag is set on a newly created frame, and later cleared by the frame's reflow() method when the frame has had its initial reflow. ns_frame_sync_frame_and_view ns_frame_outside_children this flag is set if the combined area of a frame's children extend past the...
...And 24 more matches
Secure Development Guidelines
the following content will likely see significant revision, though can be used as a reference for security best practices to follow when developing code for mozilla. introduction provide developers with information on specific security issues cover common coding mistakes and how they affect a product how to avoid making them how to mitigate them everything is oriented toward c/c++ introduction: gaining control specifics about the underlying architecture, using x86 as an example 6 basic registers (eax, ebx, ecx, edx, edi, esi) 2 stack-related registers (esp, ebp) mark top and bottom of current stack frame status register (eflags) contains various state information instruction pointer (eip) points to register being executed; can’t be modif...
...modified using call or jump instructions attacks usually rely on obtaining control over the eip otherwise the attacker can try to control memory pointed to by an existing function pointer a vulnerability is required to modify the eip or sensitive memory saved return addr or function pointer get altered introduction: gaining control (3) common issues used to gain control buffer overflows format string bugs integer overflows/underflows writing secure code: input validation input validation most vulnerabilities are a result of un-validated input always perform input validation could save you without knowing it examples: if it doesn’t have to be negative, store it in an unsigned int if the input doesn’t have to be > 512, cut it off there if the i...
...nput should only be [a-za-z0-9], enforce it cross site scripting (xss) xss is a type of code injection attack typically occurs in web applications injection of arbitrary data into an html document from another site victim’s browser executes those html instructions could be used to steal user credentials think: webmail, online auction, cms, online banking... xss: example the following snippet of javascript: document.write("welcome to " + document.location); ... is exploitable (in some browsers) with a simple request such as: http://www.victim.com?something=<script>alert('oops')</script> xss: prevention escape all dynamic input that will be sent back to the user html encoding &amp; → & &lt; → < &gt; → > &quot; → " &apos; → ' url...
...And 24 more matches
Using IndexedDB - Web APIs
iar with indexeddb, you should first read basic concepts about indexeddb. for the reference documentation on the indexeddb api, see the indexeddb article and its subpages. this article documents the types of objects used by indexeddb, as well as the methods of the asynchronous api (the synchronous api was removed from spec). basic pattern the basic pattern that indexeddb encourages is the following: open a database. create an object store in the database. start a transaction and make a request to do some database operation, like adding or retrieving data. wait for the operation to complete by listening to the right kind of dom event. do something with the results (which can be found on the request object). with these big concepts under our belts, we can get to more co...
... operation to complete by listening to the right kind of dom event. do something with the results (which can be found on the request object). with these big concepts under our belts, we can get to more concrete stuff. creating and structuring the store using an experimental version of indexeddb in case you want to test your code in browsers that still use a prefix, you can use the following code: // in the following line, you should include the prefixes of implementations you want to test. window.indexeddb = window.indexeddb || window.mozindexeddb || window.webkitindexeddb || window.msindexeddb; // don't use "var indexeddb = ..." if you're not in a function. // moreover, you may need references to some window.idb* objects: window.idbtransaction = window.idbtransaction || windo...
...therefore, it is not recommended to use it in production code. it may be preferable to not support a browser than to claim to support it and fail: if (!window.indexeddb) { console.log("your browser doesn't support a stable version of indexeddb. such and such feature will not be available."); } opening a database we start the whole process like this:...
...And 24 more matches
Web video codec guide - Web media technologies
ess codecs do exist, but they are typically used for archival and storage for local playback rather than for use on a network. this guide introduces the video codecs you're most likely to encounter or consider using on the web, summaries of their capabilities and any compatibility and utility concerns, and advice to help you choose the right codec for your project's video. common codecs the following video codecs are those which are most commonly used on the web. for each codec, the containers (file types) that can support them are also listed. each codec provides a link to a section below which offers additional details about the codec, including specific capabilities and compatibility issues you may need to be aware of. codec name (short) full codec name container support...
...contents on the encoded video quality and size feature effect on quality effect on size color depth (bit depth) the higher the color bit depth, the higher the quality of color fidelity is achieved in the 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. 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 ima...
...epths 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 following frame. the more successive frames di...
...And 24 more matches
Legacy layout methods - Learn web development
derstanding how they work, and why they are different to css grid layout. this lesson will explain 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...
...jects 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. ...
...lly 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, filling it with a simple html template, and inserting the below code into it at the appropriate places. at the bottom of the section you can see a live example of what the final code should look like. first of all, we need some content to put into our columns. replace whatever is inside the body currently with the following: <h1>2 column layout example</h1> <div> <h2>first column</h2> <p> lorem ipsum dolor sit amet, consectetur adipiscing elit. nulla lu...
...And 23 more matches
Introducing a complete toolchain - Learn web development
dy 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 do things like defining component structures inside javascript. 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 impor...
...ntribute to our toolchain, we mentioned two web services in the above list of tools. let's take this opportunity to make sure we are set up with them before we continue. you will need to create accounts with each of github and netlify if you wish to complete the tutorial. as mentioned previously, github is a source code repository service that adds community features such as issue tracking, following project releases and much more. in the next chapter we will push to a github code repository, which will cause a cascade effect that (should) deploy all the software to a home on the web. netlify is a hosting service for static websites (that is, websites that entirely consist of files that do not change in real time), which lets us deploy multiple times a day and freely hosts static sites of...
...t is, websites that entirely consist of files that do not change in real time), which lets us deploy multiple times a day and freely hosts static sites of all kinds. netlify is what provides the "home on the web" mentioned above — free hosting for us to deploy our test app to. once you've signed up for github (click the sign up link on the homepage if you don't already have an account, and follow the instructions), you can use your github account for authentication on netlify (click sign up, then choose github from the "sign up with one of the following" list), so technically you only need to create one new account. later on you'll need to connect your netlify account to your github repository to deploy this project; we'll see how to do that in the next chapter. three stages of tools a...
...And 23 more matches
display - CSS: Cascading Style Sheets
Web › CSS › display
some values of display are fully defined in their own individual specifications; for example the detail of what happens when display: flex is declared is defined in the css flexible box model specification. see the table at the end of this document for all of the individual specifications. ...
...some values of display are fully defined in their own individual specifications; for example the detail of what happens when display: flex is declared is defined in the css flexible box model specification. see the table at the end of this document for all of the individual specifications. ...
...s. syntax the css display property is specified using keyword values. ...
...And 23 more matches
filter - CSS: Cascading Style Sheets
Web › CSS › filter
if they have different lengths, the missing ...
...if they have different lengths, the missing equivalent filter functions from the longer list are added to the end of the shorter list using their lacuna values, the...
...ions are interpolated according to their specific rules. if one filter is none, it is replaced with the filter functions list of the other one using the filter function default values, then all filter functions are interpolated according to their specific rules. otherwise, discrete interpolation is used. functions the filter property is specified as none or one or more of the functions listed below. if the parameter for any function is invalid, the function returns none. except where noted, the functions that take a value expressed with a percent sign (as in 34%) also accept the value expressed as decimal (as in 0.34). when a single filter property has two or more functions it's results will be different from when two or more filter properties are separately applied with the same functions...
...And 23 more matches
Autoplay guide for media and Web Audio APIs - Web media technologies
t affected by autoplay blocking. autoplay and autoplay blocking the term autoplay refers to any feature that causes audio to begin to play without the user specifically requesting that playback begin. this includes both the use of html attributes to autoplay media as well as the user of javascript code to start playback outside the context of handling user input. ...
...g that playback begin. this includes both the use of html attributes to autoplay media as well as the user of javascript code to start playback outside the context of handling user input. that means that both of the following are considered autoplay behavior, and are therefore subject to the browser's autoplay blocking policy: <audio src="/music.mp4" autoplay> and audioelement.play(); the following web features and apis may be affected by autoplay blocking: the html <audio> and <video> elements the web audio api from the user's perspective, a web page or app that spontaneously starts making noise without warning can be jarring, inconvenient, or off-putting. because of that, browsers generally only allow autoplay to occur successfully under specific circumstances. autoplay availabi...
...g: the html <audio> and <video> elements the web audio api from the user's perspective, a web page or app that spontaneously starts making noise without warning can be jarring, inconvenient, or off-putting. because of that, browsers generally only allow autoplay to occur successfully under specific circumstances. ...
...And 23 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
ters are dual-boot (windows 7 and linux fedora 19 by 2013). all users have a personal account on a windows server (ad) and an ldap account for linux authentication. objective the objective is to provide users with a mailer agent, a web browser, and a news reader which are automatically configured (preferences) at startup to the current user connected on the computer. choosing mozilla products allow us to use the same apps while running either windows or linux systems (i suspect mac osx would be fine too). instead of configuring end user individual preferences files (~/.mozilla/default/randomdir/prefs.js) we now use a centralized default set of preferences. this centralized preference file can lock preferences (lockpref) or initialize them (defaultpref) based on environment variables (user,...
...ppropriate .js file dedicated to autoconfig (here autoconf.js). the name of the file can be anything you want because it is named by a general.config preference that should be added at the end of file mozilla_home/default/pref/autoconf.js or mozilla_home/greprefs/autoconf.js: pref("general.config.filename", "mozilla.cfg");. file api that centralized preference file uses a javascript api that allows us to do what we need. that prefcalls.js is now archive in omni.jar file located at the root of the mozilla apps installation, example of tb5: # jar -tvf /usr/lib/thunderbird/omni.jar | grep prefcalls.js 7499 sat nov 05 09:21:34 cet 2011 defaults/autoconfig/prefcalls.js traditionally (previous apps versions) is was in mozilla_home/default/autoconfig/prefcalls.js. the presence of pref("gen...
...ef/tb-autoconf.js // 20100526 - modification autoconfig jehan. // pref("general.config.obscure_value", 0); // for mcd .cfg files pref('general.config.filename', 'thunderbird.cfg'); // for mcd .cfg files it used to be in previous releases (up until 7.0) in /usr/lib/thunderbird-x.0/default/pref/autoconf.js the first pref just tells us that we won't encode the file (no more rotary 13 or 7 cf below), the second pref is the name of the file to be read: /usr/lib/thunderbird/thunderbird.cfg. (or firefox.cfg if for firefox...) file encoding if needed, the encoding can be done with the perl script: moz-byteshift.pl available at http://www.alain.knaff.lu/howto/mozi...z-byteshift.pl. for netscape 4.x the convert function from the client customization kit (cck) could also do that (and other thin...
...And 22 more matches
Client-side form validation - Learn web development
, the browser and/or the web server will check to see that the data is in the correct format and within the constraints set by the application. validation done in the browser is called client-side validation, while validation done on the server is called server-side validation. in this chapter we are focusing on client-side validation. if the information is correctly formatted, the application allows the data to be submitted to the server and (usually) saved in a database; if the information isn't correctly formatted, it gives the user an error message explaining what needs to be corrected, and lets them try again. we want to make filling out web forms as easy as possible. so why do we insist on validating our forms? there are three main reasons: we want to get the right data, in the rig...
...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 in a form field follows all of the rules specified by the above attributes, it is considered valid. if not, it is considered invalid. when an element is valid, the following things are true: the element matches the :valid css pseudo-class, which lets you apply a specific style to valid elements. if the user tries to send the data, the browser will submit the form, prov...
... if the user tries to send the data, the browser will block the form and display an error message. ...
...And 22 more matches
Video and Audio APIs - Learn web development
back, seeking, etc. this article shows you how to do common tasks such as creating custom playback controls. prerequisites: javascript basics (see first steps, building blocks, javascript objects), the basics of client-side apis objective: to learn how to use browser apis to control video and audio playback. html5 video and audio the <video> and <audio> elements allow us to embed video and audio into web pages. as we showed in video and audio content, a typical implementation looks like this: <video controls> <source src="rabbit320.mp4" type="video/mp4"> <source src="rabbit320.webm" type="video/webm"> <p>your browser doesn't support html5 video. here is a <a href="rabbit320.mp4">link to the video</a> instead.</p> </video> this creates a video player in...
...e 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. ...
...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. ...
...And 22 more matches
Handling common JavaScript problems - Learn web development
ality 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 javascript features (for example ecmascript 6 / ecmascript next features, modern web apis...) in their code, and find that such features don't work in older browsers. we'll explore all these problems and more below. 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...
... html and css, you can ensure better quality, less error-prone javascript code using a linter, which points out errors and can also flag up warnings about bad practices, etc., and be customized to be stricter or more relaxed in their error/warning reporting. the javascript/ecmascript linters we'd recommend are jshint and eslint; these can be used in a variety of ways, some of which we'll detail below. online the jshint 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 standa...
...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. ...
...And 22 more matches
Index
val 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_jsval converts a c integer, i, to a jsval. 22 js::add*root...
...m a text string chars, bytes, or srcbuf. 33 js::compileoffthread jsapi reference, reference, référence(2), spidermonkey js::compileoffthread compiles a script, chars for execution. 34 js::compileoptions jsapi reference, reference, référence(2), spidermonkey some methods of js::owningcompileoptions and js::compileoptions return the instance itself to allow method chain. 35 js::construct jsapi reference, reference, référence(2), spidermonkey js::construct calls a specified function as a constructor, fun. 36 js::createerror jsapi reference, reference, référence(2), spidermonkey js::createerror creates an error object with specified properties. 37 js::currentglobalornull jsapi reference, ref...
... jsapi reference, reference, référence(2), spidermonkey here, ptr represents the private member of js::rooted<t>, typed with t. 67 js::setlargeallocationfailurecallback jsapi reference, reference, référence(2), spidermonkey if a large allocation fails when calling pod_{calloc,realloc}cangc, the js engine may call the large-allocation- failure callback, if set, to allow the embedding to flush caches, possibly perform shrinking gcs, etc. to make some room. the allocation will then be retried (and may still fail.) 68 js::setoutofmemorycallback jsapi reference, reference, référence(2), spidermonkey unlike the error reporter, which is only called if the exception for an oom bubbles up and is not caught, the js::outofmemorycallback is called im...
...And 22 more matches
JIT Optimization Strategies
browsable documentation of optimization strategies, how they work, how they are defeated, and options for how to re-enable them. spidermonkey's optimizing jit, ionmonkey, uses various strategies to optimize operations. the most commonplace operations that are relevant for fast program execution are property accesses and function calls. optimization information is currently collected for the following operations: getproperty (obj.prop) setproperty (obj.prop = val) getelement (obj[elemname]) setelement (obj[elemname] = val) call (func(...)) at each operation site, ionmonkey tries a battery of strategies, from the most optimized but most restrictive to the least optimized but least restrictive. for each strategy attempted, its outcome is tracked. an outcome is either success or a rea...
...ide, what kind of program characteristics can prevent them from being used, and common ways to enable the engine to utilize that optimization. getproperty getproperty_argumentslength attempts to optimize an arguments.length property access. this optimization only works if the arguments object is used in well-understood ways within the function. the function containing the arguments.length is allowed to use the arguments object in the following ways without disabling this optimization: access arguments.length access arguments.callee access individual args using arguments[i] save arguments into variables, as long as those variables cannot be accessed by any nested function, and as long as there exists no eval anywhere within the function or nested function definitions. call a function...
...ation will be suppressed. in particular, arguments cannot be returned from the function, or passed as an argument into calls (except for the apply case above). getprop_argumentscallee attempts to optimize an arguments.callee property access. this optimization only works if the arguments object is used in well-understood ways within the function. the function containing the arguments.callee is allowed to use the arguments object in the following ways without disabling this optimization: access arguments.length access arguments.callee access individual args using arguments[i] save arguments into variables, as long as those variables cannot be accessed by any nested function, and as long as there exists no eval anywhere within the function or nested function definitions. call a function...
...And 22 more matches
Feature-Policy - HTTP
the http feature-policy header provides a mechanism to allow and deny the use of browser features in its own frame, and in content within any <iframe> elements in the document. this header is still in an experimental state, and is subject to change at any time. be wary of this when implementing it on your website. the header has now been renamed to permissions-policy in the spec, and this article will eventually be updated to reflect that change. for more information, see the main feature policy article. header type response header forbidden header name yes syntax feature-policy: <directive> <allowlist> <directive> the feature policy directive to apply the allowlist to. ...
...been renamed to permissions-policy in the spec, and this article will eventually be updated to reflect that change. for more information, see the main feature policy article. header type response header forbidden header name yes syntax feature-policy: <directive> <allowlist> <directive> the feature policy directive to apply the allowlist to. see directives below for a list of the permitted directive names. ...
...his article will eventually be updated to reflect that change. for more information, see the main feature policy article. header type response header forbidden header name yes syntax feature-policy: <directive> <allowlist> <directive> the feature policy directive to apply the allowlist to. see directives below for a list of the permitted directive names. ...
...And 22 more matches
Functions - JavaScript
elationship between the input and the output. to use a function, you must define it somewhere in the scope from which you wish to call it. see also the exhaustive reference chapter about javascript functions to get to know the details. defining functions function declarations a function definition (also called a function declaration, or function statement) consists of the function keyword, followed by: the name of the function. a list of parameters to the function, enclosed in parentheses and separated by commas. the javascript statements that define the function, enclosed in curly brackets, {...}. for example, the following code defines a simple function named square: function square(number) { return number * number; } the function square takes one parameter, called number. t...
...functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function. if you pass an object (i.e. ...
...ove is syntactically a statement, functions can also be created by a function expression. such a function can be anonymous; it does not have to have a name. for example, the function square could have been defined as: const square = function(number) { return number * number } var x = square(4) // x gets the value 16 however, a name can be provided with a function expression. ...
...And 22 more matches
Grammar and types - JavaScript
ou use variables as symbolic names for values in your application. the names of variables, called identifiers, conform to certain rules. a javascript identifier must start with a letter, underscore (_), or dollar sign ($). subsequent characters can also be digits (0–9). because javascript is case sensitive, letters include the characters "a" through "z" (uppercase) as well as "a" through "z" (lowercase). you can use most of iso 8859-1 or unicode letters such as å and ü in identifiers. (for more details, see this blog post.) you can also use the unicode escape sequences as characters in identifiers. some examples of legal names are number_hits, temp99, $credit, and _name. declaring variables you can declare a variable in two ways: with the keyword var. for example, var x = 42. thi...
...umber_hits, temp99, $credit, and _name. declaring variables you can declare a variable in two ways: with the keyword var. for example, var x = 42. this syntax can be used to declare both local and global variables, depending on the execution context. with the keyword const or let. for example, let y = 13. this syntax can be used to declare a block-scope local variable. (see variable scope below.) you can also simply assign a value to a variable for example, x = 42. this form creates an undeclared global variable. it also generates a strict javascript warning. undeclared global variables can often lead to unexpected behavior. thus, it is discouraged to use undeclared global variables. evaluating variables a variable declared using the var or let statement with no assigned value speci...
... var or let statement with no assigned value specified has the value of undefined. ...
...And 22 more matches
Understanding WebAssembly text format - WebAssembly
format to wasm), we’ll see just the 8 byte module header described in the binary format: 0000000: 0061 736d ; wasm_binary_magic 0000004: 0100 0000 ; wasm_binary_version adding functionality to your module ok, that’s not very interesting, let’s add some executable code to this module. all code in a webassembly module is grouped into functions, which have the following pseudo-code structure: ( func <signature> <locals> <body> ) the signature declares what the function takes (parameters) and returns (return values). the locals are like vars in javascript, but with explicit types declared. the body is just a linear list of low-level instructions. so this is similar to functions in other languages, even if it looks different because it is an s-expressio...
...it is worth noting here that: the absence of a (result) means the function doesn’t return anything. ...
... return type declarations. it is worth noting here that: the absence of a (result) means the function doesn’t return anything. in the current iteration, there can be at most 1 return type, but later this will be relaxed to any number. each parameter has a type explicitly declared; wasm currently has four available number types (plus reference types; see the reference types) section below): i32: 32-bit integer i64: 64-bit integer f32: 32-bit float f64: 64-bit float a single parameter is written (param i32) and the return type is written (result i32), hence a binary function that takes two 32-bit integers and returns a 64-bit float would be written like this: (func (param i32) (param i32) (result f64) ... ) after the signature, locals are listed with their type, for examp...
...And 22 more matches
CSS values and units - Learn web development
in this lesson we will take a look at some of the most common values and units in use. 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 different types of values and units used in css properties. ...
... type, it is really just a fancy way of saying value. note: yes, css values tend to be denoted using angle brackets, to differentiate them from css properties (e.g. the color property, versus the <color> data type). you might get confused between css data types and html elements too, as they both use angle brackets, but this is unlikely — they are used in very different contexts. in the following example we have set the color of our heading using a keyword, and the background using the rgb() function: h1 { color: black; background-color: rgb(197,93,161); } a value in css is a way to define a collection of allowable sub-values. 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, rg...
... 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 out different possible values. numbers, lengths, and percentages there are various numeric data types that you might find yourself using in css. the following are all classed as numeric: data type description <integer> an <integer> is a whole number such as 1024 or -55. <number> a <number> represents a decimal number — it may or may not have a decimal point with a fractional component, for example 0.255, 128, or -1.2. <dimension> a <dimension> is a <number> with a unit attached to it, for exampl...
...And 21 more matches
Floats - Learn web development
rned to its original purpose, as this article explains. prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css.) objective: to learn how to create floated features on webpages, and to use the clear property and other methods of clearing floats. the background of floats the float property was introduced to allow web developers to implement simple layouts involving an image floating inside a column of text, with the text wrapping around the left or right of it. the kind of thing you might get in a newspaper layout. but web developers quickly realized that you can float anything, not just images, so the use of float broadened, for example to fun layout effects such as drop-caps. floats have commonly been...
...get in a newspaper layout. but web developers quickly realized that you can float anything, not just images, so the use of float broadened, for example to fun layout effects such as drop-caps. floats have commonly been used to create entire web site layouts featuring multiple columns of information floated so they sit alongside one another (the default behavior would be for the columns to sit below one another, in the same order as they appear in the source). there are newer, better layout techniques available and so use of floats in this way should be regarded as a legacy technique. in this article we'll just concentrate on the proper uses of floats. a simple float example let's explore how to use floats. we'll start with a really simple example involving floating a block of text around...
...e order as they appear in the source). there are newer, better layout techniques available and so use of floats in this way should be regarded as a legacy technique. in this article we'll just concentrate on the proper uses of floats. a simple float example let's explore how to use floats. we'll start with a really simple example involving floating a block of text around an element. ...
...And 21 more matches
OS.File for the main thread
this page details how to use file i/o from the main thread. for other uses of os.file, please see the corresponding page. using os.file from a jsm to import os.file into your chrome code, add the following line at the start of your script: components.utils.import("resource://gre/modules/osfile.jsm") promises before using os.file from the main thread, you need some understanding of the promise library. see the promise object documentation for details. also, os.file plays very nicely with task.jsm. example: read the contents of a file as text the following snippet opens a file "file.txt" and read its contents as a string, using the default encoding (utf-8). the content is read asynchronously. the result is a promise. let decoder = new textdecoder(); // this decoder can...
...coder = new textdecoder(); // this decoder can be reused for several reads let promise = os.file.read("file.txt"); // read the complete file as an array promise = promise.then( function onsuccess(array) { return decoder.decode(array); // convert this array to a text } ); this example requires firefox 18 or a more recent version. example: write a string to a file the following snippet writes the text "this is some text" to a string "file.txt", using the default encoding (utf-8). it uses an atomic write to ensure that the file is not modified if, for some reason, the write cannot complete (typically because the computer is turned off, the battery runs out, or the application is stopped.) let encoder = new textencoder(); // this enco...
... // this encoder can be reused for several writes let array = encoder.encode("this is some text"); // convert the text to an array let promise = os.file.writeatomic("file.txt", array, // write the array atomically to "file.txt", using as temporary {tmppath: "file.txt.tmp"}); // buffer "file.txt.tmp". ...
...And 21 more matches
Variable fonts guide - CSS: Cascading Style Sheets
be contained in a single file. that file would be larger than a single font, but in most cases smaller or about the same size as the 4 you might load for body copy. the advantage in choosing the variable font is that you have access to the entire range of weights, widths, and styles available, rather than being constrained to only the few that you previously would have loaded separately. this allows for common typographic techniques such as setting different size headings in different weights for better readability at each size, or using a slightly narrower width for data-dense displays. for comparison, it is typical in a typographic system for a magazine to use 10–15 or more different weight and width combinations throughout the publication — giving a much wider range of styles than cu...
...e about font families, weights, and variants you might notice that we have been talking about having a specific font file for every weight and style (i.e. bold and italic and bold italic), rather than relying upon the browser to synthesize them. the reason for this is that most typefaces have very specific designs for bolder weights and italics that often include completely different characters (lower-case 'a' and 'g' are often quite different in italics, for example). in order to most accurately reflect the typeface design and avoid differences between browsers and how they may or may not synthesize the different styles, it's more accurate to load the specific font files where needed when using a non-variable font. you may also find that some variable fonts come split into two files: one f...
...ions. this is sometimes done to reduce the overall file size in cases where the italics aren't needed or used. in all cases, it is still possible to link them with a common font-family name so you can call them using the same font-family and appropriate font-style. introducing the 'variation axis' the heart of the new variable fonts format is the concept of an axis of variation describing the allowable range of that particular aspect of the typeface design. so the 'weight axis' describes how light or how bold the letterforms can be; the 'width axis' describes how narrow or how wide they can be; the 'italic axis' describes if italic letterforms are present and can be turned on or off accordingly, etc. note that an axis can be a range or a binary choice. weight might range from 1–999, where...
...And 20 more matches
Eclipse CDT
s complete). therefore, it is not recommended for use if your machine only has 4 gb of ram. installing eclipse regarding llvm4eclipsecdt, do not install or select this toolchain for mozilla development. this plugin is intended mainly for managed projects but we use an unmanaged project for mozilla (since it has its own build system). using this plugin will result in parts of the ui described below being hidden or disabled. download "eclipse ide for c/c++ developers" (not eclipse ide for enterprise java developers) from the eclipse download page, install it, and add the directory containing the eclipse binary to your path (/applications/eclipse.app/contents/eclipse/ on mac). (while package managers like snap sometimes provide an eclipse package, they do not include the c++ developer tool...
...you must increase its memory limits. when eclipse's indexer tries to process the mozilla source, eclipse will need considerably more memory than the limits imposed by its default configuration. you can increase eclipse's memory limits using the eclipse.ini that lives alongside the eclipse binary. set an initial heap space of 1 gb and max heap space of 5 gb, say, by modifying the values of the following two lines in eclipse.ini: -xms1g -xmx5g if you fail to increase these limits, then you will likely find that eclipse either hangs when it tries to index the mozilla source or else that the code intelligence is very broken after the indexing "completes". express setup for the eclipse indexer to work well you must first build mozilla, so that it includes headers from the objdir etc. these ca...
...ually, use the context menu in the project explorer tab on the left side of the window. to rebuild for changes in an individual directory (for example, to take account of some changes that you yourself made) select "index > freshen all files" on that directory. to rebuild the entire index (for example when you pull from mozilla-central) select "index > rebuild" on the project root. usage tips below are some of the more useful user tips. (if you're thinking of adding tips, please first consider how widely useful they'll be before adding to this already lengthy page.) for further documentation see the official eclipse user guide and eclipse cdt user guide. keyboard shortcuts regarding key bindings (keyboard shortcuts), the bindings given below are the defaults. you can change the key bindin...
...And 19 more matches
NSS Tools modutil
. for information on certificate database and key database management, see using the certificate database tool. availability this tool is known to build on solaris 2.5.1 (sunos 5.5.1) and windows nt 4.0. syntax to run the security module database tool, type the command modutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section. each command takes one option. each option may take zero or more arguments. to see a usage string, issue the command without options. options and arguments options specify an action. option arguments modify an action. the options and arguments for the modutil command are defined as follows: options -create create new secmod.db, key3.db, and cert8.db files. use the -dbdir ...
...le library-file specify a path to the dll or other library file containing the implementation of the pkcs #11 interface module that is being added to the database. -ciphers cipher-enable-list enable specific ciphers in a module that is being added to the database. the cipher-enable-list is a colon-delimited list of cipher names. enclose this list in quotation marks if it contains spaces. the following cipher is currently available: fortezza. -mechanisms mechanism-list specify the security mechanisms for which a particular module will be flagged as a default provider. the mechanism-list is a colon-delimited list of mechanism names. enclose this list in quotation marks if it contains spaces. the module becomes a default provider for the listed mechanisms when those mechanisms are enabled. i...
...e will be flagged as a default provider. the mechanism-list is a colon-delimited list of mechanism names. enclose this list in quotation marks if it contains spaces. the module becomes a default provider for the listed mechanisms when those mechanisms are enabled. if more than one module claims to be a particular mechanism's default provider, that mechanism's default provider is undefined. ...
...And 19 more matches
WebGL best practices - Web APIs
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. ...
...ay_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. ...
...gs about fb completeness invalidations. and to a lesser degree, vao attachments (vertexattribpointer, disable/enablevertexattribarray) drawing from static, unchanging vaos is faster than mutating the same vao for every draw call. for unchanged vaos, browsers can cache the fetch limits, whereas when vaos change, browsers must revalidate and recalculate limits. the overhead for this is relatively low, but re-using vaos means fewer vertexattribpointer calls too, so it's worth doing wherever it's easy. delete objects eagerly don't wait for the garbage collector/cycle collector to realize objects are orphaned and destroy them. implementations track the liveness of objects, so 'deleting' them at the api level only releases the handle that refers to the actual object. (conceptually releasing the...
...And 19 more matches
Web audio codec guide - Web media technologies
their encoding and decoding of media, and may support additional codecs as well, for optimal cross-platform support of video and audio conferencing, and to integrate better with legacy telecommunication solutions. see codecs used by webrtc for details. for information about the fundamental concepts behind how digital audio works, see the article digital audio concepts. common codecs the list below denotes the codecs most commonly used on the web and which containers (file types) support them. if all you need to know is which codecs are even possible to use, this is for you. of course, individual browsers may or may not choose to support all of these codecs, and their support for which container types can use them may vary as well. in addition, browsers may choose to support additional code...
..., 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 less impact on the encoded audio size than one might expect. however, a number of factors do still affect the encoded audio quality and size. the table below lists a number of key source audio file format factors and their impact on the encoded audio. the effect of source audio format and contents on the encoded audio quality and size feature effect on quality effect on size channel count the number of channels affects only the perception of directionality, not the quality. each channel may substantially increase th...
...essed audio than lossless codecs do. generally speaking, the most common reasons to choose lossless audio are because you require archival-quality storage, or because the audio samples will be remixed and recompressed, and you wish to avoid the amplification of artifacts in the audio due to recompression. for real-time streaming of audio, a lossy codec is usually required in order to ensure the flow of data can keep up with the audio playback rate regardless of network performance. maximum number of channels the audio delivered to each speaker in a sound system is provided by one audio channel in a stream. monaural sound is a single channel. stereo sound is two. 5.1 surround sound has five audio channels, plus one low frequency enhancement (lfe) channel. lfe channels are specifically desi...
...And 19 more matches
Practical positioning examples - Learn web development
he corresponding panel when a tab is pressed, and style the tab itself. you won't need to understand the javascript itself at this stage, but you should think about learning some basic javascript as soon as possible — the more complex your ui features become, the more likely it is that you'll need some javascript to implement your desired functionality. ...
...t to implement your desired functionality. general setup to begin with, add the following between your opening and closing <style> tags: html { font-family: sans-serif; } * { box-sizing: border-box; } body { margin: 0; } this is just some general setup to set a sans-serif font on our page, use the border-box box-sizing model, and get rid of the default <body> margin. next, add the following just below your previous css: .info-box { width: 450px; height: 400px; margin: 0 auto; } this sets a specific width and height on the content, and centers it on the screen using the old margin: 0 auto trick. previously in the course we advised against setting a fixed height on content containers if at all possible; it is ok in this circumstance because we have fixed content in our tabs...
...ntent in our tabs. it also looks a bit jarring to have different tabs at different heights. styling our tabs now we want to style tabs to look like tabs — basically, these are a horizontal navigation menu, but instead of loading different web pages when they are clicked on like we've seen previously in the course, they cause different panels to be displayed on the same page. ...
...And 18 more matches
Fundamental text and font styling - Learn web development
objective: to learn the fundamental properties and techniques needed to style text on web pages. what is involved in styling text in css? as you'll have already experienced in your work with html and css, text inside an element is laid out inside the element's content box. it starts at the top left of the content area (or the top right, in the case of rtl language content), and flows towards the end of the line. once it reaches the end, it goes down to the next line and continues, then the next line, until all the content has been placed in the box. text content effectively behaves like a series of inline elements, being laid out on lines adjacent to one another, and not creating line breaks until the end of the line is reached, or unless you force a line break manually usin...
..., before carrying on. the css properties used to style text generally fall into two categories, which we'll look at separately in this article: 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 (...
...y into his mighty throat. many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. truly a wonder of nature this urban predator — tommy the cat had many a story to tell. but it was a rare occasion such as this that he did.</p> font families to set a different font on your text, you use the font-family property — this allows you to specify a font (or list of fonts) for the browser to apply to the selected elements. the browser will only apply a font if it is available on the machine the website is being accessed on; if not, it will just use a browser default font. a simple example looks like so: p { font-family: arial; } this would make all paragraphs on a page adopt the arial font, which is found on any compute...
...And 18 more matches
Making decisions in your code — conditionals - Learn web development
e: to understand how to use conditional structures in javascript. ...
... (perhaps the outcome of "ate one cookie" might be "still felt hungry", and the outcome of "ate two cookies" might be "felt full, but mom scolded me for eating all the cookies".) if...else statements let's look at by far the most common type of conditional statement you'll use in javascript — the humble if...else statement. basic if ... else syntax basic if...else syntax looks like the following in pseudocode: if (condition) { code to run if condition is true } else { run some other code instead } here we've got: the keyword if followed by some parentheses. a condition to test, placed inside the parentheses (typically "is this value bigger than this other value?", or "does this value exist?"). the condition makes use of the comparison operators we discussed in the last modul...
...set of curly braces, inside which we have some more code — this can be any code we like, and it only runs if the condition is not true — or in other words, the condition is false. this code is pretty human-readable — it is saying "if the condition returns true, run code a, else run code b" you should note that you don't have to include the else and the second curly brace block — the following is also perfectly legal code: if (condition) { code to run if condition is true } run some other code however, you need to be careful here — in this case, the second block of code is not controlled by the conditional statement, so it always runs, regardless of whether the condition returns true or false. this is not necessarily a bad thing, but it might not be what you want — often yo...
...And 18 more matches
Handling common HTML and CSS problems - Learn web development
(generating dom elements is expensive). in other cases, nascent features are not supported consistently across browsers, which can make some features and styles not work for some users. responsive design problems are also common — a site that looks good in a desktop browser might provide a terrible experience on a mobile device, because the content is too small to read, or perhaps the site is slow because of expensive animations. let's go forth and look at how we can reduce cross browser errors that result from html/css. first things first: fixing general problems we said in the first article of this series that a good strategy to begin with is to test in a couple of modern browsers on desktop/mobile, to make sure your code is working generally, before going on to concentrate on the cro...
...nside the widget with this class, so conflicts are less likely. for example .audio-player ul a. validation for html, validation involves making sure all your tags are properly closed and nested, you are using a doctype, and you are using tags for their correct purpose. a good strategy is to validate your code regularly. one service that can do this is the w3c markup validation service, which allows you to point to your code, and returns a list of errors: css has a similar story — you need to check that your property names are spelled correctly, property values are spelled correctly and are valid for the properties they are used on, you are not missing any curly braces, and so on. the w3c has a css validator available too, for this purpose. linters another good option to choose is a ...
...so-called linter application, which not only points out errors, but can also flag up warnings about bad practices in your css, and other points 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 wa...
...And 18 more matches
Command line crash course - Learn web development
ou can read a bit of the history on wikipedia’s entry for computer terminal. since then, the terminal has remained a constant feature of all operating systems — from desktop machines, to servers tucked away in the cloud (it’s not really a cloud), to microcomputers like the raspberry pi zero, and even to mobile phones. it provides direct access to the computer’s underlying file system and low-level features, and is therefore incredibly useful for performing complex tasks rapidly, if you know what you are doing. it is also useful for automation — for example to write a command to update the titles of hundreds of files instantly, say from “ch01-xxxx.png” to “ch02-xxxx.png”. if you updated the file names using your finder or explorer gui app, it would take you a long time. a...
...if you know what you are doing. it is also useful for automation — for example to write a command to update the titles of hundreds of files instantly, say from “ch01-xxxx.png” to “ch02-xxxx.png”. if you updated the file names using your finder or explorer gui app, it would take you a long time. anyway, the terminal is not going away anytime soon. what does the terminal look like? below you can see some of the different flavours of programs that are available that can get you to a terminal. the next images show the command prompts available in windows — there’s a good range of options from the "cmd" program to "powershell" — which can be run from the start menu by typing the program name. and below, you can see the macos terminal application. how do you access the t...
...on most systems. in this section, we’ll look at how to get access to the terminal on your chosen system. linux/unix as hinted at above, linux/unix systems have a terminal available by default, listed among your applications. macos macos has a system called darwin that sits underneath the graphical user interface. darwin is the unix-like system, which provides the terminal, and access to the low-level tools. macos darwin mostly has parity with unix, certainly good enough to not cause us any worries as we work through this article. the terminal is available on macos at applications/utilities/terminal. windows as with some other programming tools, using the terminal (or command line) on windows has traditionally not been as simple or easy as on other operating systems. but things are ge...
...And 18 more matches
Creating localizable web applications
in some cases, the code snippets were slightly changed to better illustrate the recommendations or for clarity. cheatsheet don't hardcode english text, formats (numbers, dates, addresses, etc.), word order or sentence structure. don't put text or numbers in images. ...
...in some cases, the code snippets were slightly changed to better illustrate the recommendations or for clarity. cheatsheet don't hardcode english text, formats (numbers, dates, addresses, etc.), word order or sentence structure. don't put text or numbers in images. ...
...rintf() (or equivalents) and use variables in the english strings. write semantic code (e.g. don't use text and <img/> for decorations; instead, use css). document your code so that localizers know what they're translating (e.g. in gettext use comments and contexts). app logic detect the locale correctly be smart about detecting the user's locale correctly. you can use one or more of the following techniques: http accept-language headers, the ua string, ip geolocation. see examples of the addons.mozillaorg code at /addons/trunk/site/app/config/language.php and /addons/trunk/site/app/config/language.inc.php. the language_config class expects arrays of valid languages & supported languages. always give the user a possibility to change the locale (e.g. by adding locale dropdown men...
...And 18 more matches
Bytecode Descriptions
give us. format: jof_ic other expressions globalthis stack: ⇒ this push the global this value. not to be confused with the globalthis property on the global. this must be used only in scopes where this refers to the global this. newtarget stack: ⇒ new.target push the value of new.target. the result is a constructor or undefined. this must be used only in scripts where new.target is allowed: non-arrow function scripts and other scripts that have a non-arrow function script on the scope chain. implements: getnewtarget. dynamicimport stack: moduleid ⇒ promise dynamic import of the module specified by the string value 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. obje...
...rmat: jof_class_ctor derivedconstructor operands: (uint32_t nameindex, uint32_t sourcestart, uint32_t sourceend) stack: proto ⇒ constructor create and push a default constructor for a derived class. a default derived-class constructor behaves like constructor(...args) { super(...args); }. implements: classdefinitionevaluation for classtail, steps 10.a. and 12-17. sourcestart and sourceend follow the same rules as for jsop::classconstructor. format: jof_class_ctor functionproto stack: ⇒ %functionprototype% pushes the current global's functionprototype. kind must be in range for jsprotokey (and must not be jsproto_limit). calls call, calliter, funapply, funcall, callignoresrv operands: (uint16_t argc) stack: callee, this, args[0], ..., args[argc-1] ⇒ rval invoke callee with thi...
...unction ("x[symbol.iterator] is not a function"). the argc operand must be 0 for this variation. jsop::funapply hints to the vm that this is likely a call to the builtin method function.prototype.apply, an easy optimization target. jsop::funcall similarly hints to the vm that the callee is likely function.prototype.call. jsop::callignoresrv hints to the vm that the return value is ignored. this allows alternate faster implementations to be used that avoid unnecesary allocations. implements: evaluatecall steps 4, 5, and 7. format: jof_argc, jof_invoke, jof_typeset, jof_ic spreadcall stack: callee, this, args ⇒ rval like jsop::call, but the arguments are provided in an array rather than a span of stack slots. used to implement spread-call syntax: f(...args). args must be an array object co...
...And 18 more matches
Mozilla internal string guide
]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. ...
...not be thought of as different types. nsliteral[c]string which should rarely be constructed explicitly but usually through the ""_ns and u""_ns user-defined string literals. nsliteral[c]string is trivially constructible and destructible, and therefore does not emit construction/destruction code when stored in statics, as opposed to the other string classes. the major string classes the list below describes the main base classes. once you are familiar with them, see the appendix describing what class to use when. nsastring/nsacstring: the abstract base class for all strings. it provides an api for assignment, individual character access, basic manipulation of characters in the string, and string comparison. this class corresponds to the xpidl astring parameter type. nsastring is not nec...
.... nsastring/nsacstring: the abstract base class for all strings. it provides an api for assignment, individual character access, basic manipulation of characters in the string, and string comparison. this class corresponds to the xpidl astring parameter type. nsastring is not necessarily null-terminated. nsstring/nscstring: builds on nsastring by guaranteeing a null-terminated storage. this allows for a method (.get()) to access the underlying character buffer. the remainder of the string classes inherit from either nsastring or nsstring. thus, every string class is compatible with nsastring. since every string derives from nsastring (or nsacstring), they all share a simple api. common read-only methods: .length() - the number of code units (bytes for 8-bit string classes and char16...
...And 18 more matches
Web Video Text Tracks Format (WebVTT) - Web APIs
ased format, which must be encoded using utf-8. where you can use spaces you can also use tabs. there is also a small api available to represent and manage these tracks and the data needed to perform the playback of the text at the correct times. webvtt files the mime type of webvtt is text/vtt. a webvtt file (.vtt) contains cues, which can be either a single line or multiple lines, as shown below: 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. webvtt body the structure of a webvtt consists of the following components, some of them optional, in this order: an optional byte order mark (bom). the string "webvtt". an optional text header to the right of webvtt. there must be at least one...
..., which is the ending time for showing the associated text. we can then have one or more lines that 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 bu...
...udo-element. within site css video::cue { background-image: linear-gradient(to bottom, dimgray, lightgray); color: papayawhip; } video::cue(b) { color: peachpuff; } here, all video elements are styled to use a gray linear gradient as their backgrounds, with a foreground color of "papayawhip". in addition, text boldfaced using the <b> element are colored "peachpuff". ...
...And 18 more matches
Lexical grammar - JavaScript
e space characters, line terminator characters are used to improve the readability of the source text. however, in some cases, line terminators can influence the execution of javascript code as there are a few places where they are forbidden. line terminators also affect the process of automatic semicolon insertion. line terminators are matched by the \s class in regular expressions. only the following unicode code points are treated as line terminators in ecmascript, other line breaking characters are treated as white space (for example, next line, nel, u+0085 is considered as white space). line terminator characters code point name abbreviation description escape sequence u+000a line feed <lf> new line character in unix systems. \n ...
... wikipedia comments comments are used to add hints, notes, suggestions, or warnings to javascript code. this can make it easier to read and understand. they can also be used to disable code to prevent it from being executed; this can be a valuable debugging tool. javascript has two long-standing ways to add comments to code. the first way is the // comment; this makes all text following it on the same line into a comment. for example: function comment() { // this is a one line javascript comment console.log('hello world!'); } comment(); the second way is the /* */ style, which is much more flexible. for example, you can use it on a single line: function comment() { /* this is a one line javascript comment */ console.log('hello world!'); } comment(); you can also...
...h #! and is only valid at the absolute start of a script or module. note also that no whitespace of any kind is permitted before the #!. the comment consists of all the characters after #! up to the end of the first line; only one such comment is permitted. the hashbang comment specifies the path to a specific javascript interpreter that you want to use to execute the script. an example is as follows: #!/usr/bin/env node console.log("hello world"); note: hashbang comments in javascript mimic shebangs in unix used to run files with proper interpreter. although bom before hashbang comment will work in a browser it is not advised to use bom in a script with hasbang. bom will not work when you try to run the script in unix/linux. so use utf-8 without bom if you want to run scripts direct...
...And 18 more matches
Layout System Overview - Archive of obsolete content
presentation, where the width of the presentation is constrained by the dimensions of the printed output (paper) and the height of each page is fixed. this paged presentation presents several challenges not present in the galley presentation, namely how to break up elements that are larger than a single page, and how to handle changes to page dimensions. the original design of the layout system allowed for multiple, possibly different, presentations to be supported simultaneously from the same content model. in other words, the same html or xml document could be viewed as a normal galley presentation in a browser window, while simultaneously being presented in a paged presentation to a printer, or even an aural presentation to a speech-synthesizer. to date the only real use of this multiple p...
... have been better to use a copy of the content model for each presentation, and to remove the complexity of managing separate presentations - analysis is needed here). the idea of supporting a non-visual presentation is interesting. layout's support for aural presentations is undeveloped, though conceptually, it is possible and supported by the architecture. how layout does its job: frames and reflow so, layout is concerned with providing a presentation, in galley or paged mode. given a content model, how does the layout system actually create the presentation? through the creation and management of frames. frames are an encapsulation of a region on the screen, a region that contains geometry (size and location, stacking order). generally frames correspond to the content elements, though ther...
...odule 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. ...
...And 17 more matches
Space Manager High Level Design - Archive of obsolete content
overview the space manager and associated classes and structures are used by block and line layout to manage rectangular regions that are occupied and available, for correct handling of floated elements and the elements that flow around them. when elements are floated to the left or right in a layout, they take up space and influence where other elements can be placed. the space manager 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. the space manager works in concert with several other classes to do its job. the classes that are considered part...
... are considered part of the space manager are: nsspacemanager nsbanddata nsblockbanddata bandrect / bandlist (private structs) frameinfo (private struct) nsbandtrapezoid outside of the space manager itself, the clients of the space manager also play an important part in the management of he available and used space. ...
...rivate struct) nsbandtrapezoid outside of the space manager itself, the clients of the space manager also play an important part in the management of he available and used space. the primary classes that interact with the space manager are: nsblockreflowstate nsblockframe nsboxtoblockadaptor the general interaction model is to create a space manager for a block frame in the context of a reflow, and to associate it with the blockreflowstate so it is passed down to child frames' reflow methods. after reflow, the space manager is destroyed. during reflow, the space manager stores the space taken up by floats (updatespacemanager in nsblockframe) and provides information about the space available for other elements (getavailablespace in nsblockreflowstate). additionally, there is a need to ...
...And 17 more matches
Getting started with HTML - Learn web development
tructure 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 another page, italicize words, and so on. for example, consider the following line of text: my cat is very grumpy if we wanted the text to stand by itself, we could specify that it is a paragraph by enclosing it in a paragraph (<p>) element: <p>my cat is very grumpy</p> note: tags in html are case-insensitive. this means they can be written in uppercase or lowercase. for example, a <title> tag could be written as <title>, <title>, <title>, <title>, etc., and it wi...
...text to stand by itself, we could specify that it is a paragraph by enclosing it in a paragraph (<p>) element: <p>my cat is very grumpy</p> note: tags in html are case-insensitive. this means they can be written in uppercase or lowercase. for example, a <title> tag could be written as <title>, <title>, <title>, <title>, etc., and it will work. however, it is best practice to write all tags in lowercase for consistency, readability, and other reasons. anatomy of an html element let's further explore our paragraph element from the previous section: the anatomy of our element is: the opening tag: this consists of the name of the element (in this example, p for paragraph), wrapped in opening and closing angle brackets. this opening tag marks where the element begins or starts to take...
...the paragraph text. the content: this is the content of the element. in this example, it is the paragraph text. the closing tag: this is the same as the opening tag, except that it includes a forward slash before the element name. this marks where the element ends. failing to include a closing tag is a common beginner error that can produce peculiar results. the element is the opening tag, followed by content, followed by the closing tag. active learning: creating your first html element edit the line below in the input area by wrapping it with the tags <em> and </em>. to open the element, put the opening tag <em> at the start of 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 upda...
...And 17 more matches
What is JavaScript? - Learn web development
s 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 technologies, two of ...
...content = '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. ''player 1: chris". ru...
...le 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. so-called application programming interfaces (apis) provide you with extra superpowers to use in your javascript code. apis are ready-made sets of code building blocks that allow a developer to implement programs that would otherwise be hard or impossible to implement. they do the same thing for programming that ready-made furniture kits do for home building — it is much easier to take ready-cut panels and screw them together to make a bookshelf than it is to work out the design yourself, go and find the correct wood, cut all the panels to the right size and shape, find...
...And 17 more matches
Web Console remoting - Firefox Developer Tools
introduction this document describes the way web console remoting works. the web console is split between a client with its user interface, and the server which has listeners for all the things that happen in the tab. for communication between the server and the client we use the remote debugging protocol. this architecture allows you to connect a web console client instance to a server running on b2g, fennec or some other firefox instance. to better understand the architecture of the web console we recommend learning about the debugger architecture. the remote web console is a feature introduced in firefox 18. this document describes the latest protocol, with changes that have been made since then. the webconsoleactor and the webconsoleclient the webconsoleactor lives in dbg-w...
...it/devtools/webconsole folder. the webconsoleclient lives in webconsoleclient.jsm (in toolkit/devtools/webconsole) and it is used by the web console when working with the web console actor. to see how the debugger is used in the web console code, look in browser/devtools/webconsole/webconsole.js, and search for webconsoleconnectionproxy. ...
...n browser/devtools/webconsole/webconsole.js, and search for webconsoleconnectionproxy. the new web console actors are: the webconsoleactor allows js evaluation, autocomplete, start/stop listeners, etc. the networkeventactor is used for each new network request. the client can request further network event details - like response body or request headers. to attach to the webconsoleactor, follow these steps: connecttoserver() // the usual listtabs() pickthetabyouwant() debuggerclient.attachconsole(tab.consoleactor, listeners, onattachconsole) the listeners argument is an array which specifies listeners you want to start in the web console. these can be: page errors, window.console api messages, network activity, and file activity. for example: ["pageerror", "consoleapi", "networkacti...
...And 17 more matches
Drag Operations - Web APIs
the following describes the steps that occur during a drag and drop operation. the drag operations described in this document use the datatransfer interface. this document does not use the datatransferitem interface nor the datatransferitemlist interface. the draggable attribute in a web page, there are certain cases where a default drag behavior is used. these include text selections, images, and links. when an image or link is dragged, the url of the image or link is set as the drag data, and a drag begins. for other elements, they must be part of a selection for a default drag to occur. to see this in effect, select an area of a webpage, and then click and hold the mouse and drag the selection. ...
...ude text selections, images, and links. when an image or link is dragged, the url of the image or link is set as the drag data, and a drag begins. for other elements, they must be part of a selection for a default drag to occur. to see this in effect, select an area of a webpage, and then click and hold the mouse and drag the selection. an os-specific rendering of the selection will appear and follow the mouse pointer as the drag occurs. however, this behavior is only the default drag behavior, if no listeners adjust the data to be dragged. in html, apart from the default behavior for images, links, and selections, no other elements are draggable by default. to make other html elements draggable, three things must be done: set the draggable="true" on the element that you wish to make dra...
...the data to be dragged. in html, apart from the default behavior for images, links, and selections, no other elements are draggable by default. to make other html elements draggable, three things must be done: set the draggable="true" on the element that you wish to make draggable. add a listener for the dragstart event. set the drag data in the above listener. here is an example which allows a section of content to be dragged. <p draggable="true" ondragstart="event.datatransfer.setdata('text/plain', 'this text may be dragged')"> this text <strong>may</strong> be dragged. </p> the draggable attribute is set to "true", so this element becomes draggable. if this attribute were omitted or set to "false", the element would not be dragged, and instead the text would be selected. the...
...And 17 more matches
Using CSS transitions - CSS: Cascading Style Sheets
transitions provide a way to control animation speed when changing css properties. instead of having property changes take effect immediately, you can cause the changes in a property to take place over a period of time. for example, if you change the color of an element from white to black, usually the change is instantaneous. with css transitions enabled, changes occur at time intervals that follow an acceleration curve, all of which can be customized. animations that involve transitioning 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 ...
...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 animated is changing as the specification develops. the au...
...the browser and its version, and should be avoided. defining transitions css transitions are controlled using the shorthand transition property. this is the best way to configure transitions, as it makes it easier to avoid out of sync parameters, which can be very frustrating to have to spend lots of time debugging in css. you can control the individual components of the transition with the following sub-properties: (note that these transitions loop infinitely only for the purpose of our examples; css transitions only visualize a property change from start to finish. if you need visualizations that loop, look into the css animation property.) transition-property specifies the name or names of the css properties to which transitions should be applied. only properties listed here are an...
...And 17 more matches
Adapting to the new two-value syntax of display - CSS: Cascading Style Sheets
play property. what happens when we change the value of the display property? one of the first things we learn about css is that some elements are block-level and some are inline-level. for example, an <h1> or a <p> are block-level by default, and a <span> is inline-level. using the display property we can switch between block and inline. for example to make a heading inline we would use the following css: h1 { display: inline; } more recently we have gained css grid layout and flexbox. to access these we also use values of the display property — display: grid and display: flex. only when the value of display is changed do the children become flex or grid items and begin to respond to the other properties in the grid or flexbox specifications. changing an element's display value cha...
... in a flex formatting context. you can see this if you take a <span> — normally an inline-level element — and apply display: flex to it. the <span> becomes a block-level element. it behaves as block-level things do in relationship to other boxes in the layout. it’s as if you had applied display: block to the span, however we also get the changed behavior of the children. the live example below has a <span> with display: flex applied. it has become a block-level box taking up all available space in the inline direction. you can now use justify-content: space-between; to put this space between the two flex items. we can create inline flex containers. if you create a flex container using the single value of inline-flex you will have an inline-level box with flex children. the children ...
...e-flex you will have an inline-level box with flex children. the children behave in the same way as the flex children of a block-level container. the only thing that has changed is that the parent is now an inline-level box. it therefore behaves like other inline-level things, and doesn't take up the full width (or size in the inline dimension) that a block-level box does. this means that some following text could come up alongside the flex container. the same is true when working with grid layout. using display: grid will give you a block-level box, which creates a grid formatting context for the direct children. using display: inline-grid will create an inline-level box, which creates a grid formatting context for the children. the two-value syntax as you can see from the above explana...
...And 17 more matches
The "codecs" parameter in common media types - Web media technologies
ere, this format was once commonly used on the web but no longer is, since it required a plugin to use. however, each of these mime types is vague. all of these file types support a variety of codecs, and those codecs may have any number of profiles, levels, and other configuration factors. for this reason, you can add the codecs parameter to the media type. to do so, append a semicolon (;) followed by codecs= and then the string describing the format of the contents of the file. some media types only let you specify the names of the codecs to use, while others allow you to specify various constraints on those codecs as well. you can specify multiple codecs by separating them with commas. audio/ogg; codecs=vorbis an ogg file containing a vorbis audio track. video/webm; codecs="vp8, vo...
...nsions. you can use the javascript encodeuri() function to encode the parameter list; similarly, you can use decodeuri() to decode a previously encoded parameter list. when the codecs parameter is used, the specified list of codecs must include every codec used for the contents of the file. the list may also contain codecs not present in the file.= codec options by container the containers below support extended codec options in their codecs parameters: 3gp av1 iso bmff mpeg-4 quicktime webm several of the links above go to the same section; that's because those media types are all based on iso base media file format (iso bmff), so they share the same syntax. av1 the syntax of the codecs parameter for av1 is defined the av1 codec iso media file format binding specification,...
...s because those media types are all based on iso base media file format (iso bmff), so they share the same syntax. av1 the syntax of the codecs parameter for av1 is defined the av1 codec iso media file format binding specification, section 5: codecs parameter string. av01.p.llt.dd[.m[.ccc[.cp[.tc[.mc[.f]]]]]] this codec parameter string's components are described in more detail in the table below. each component is a fixed number of characters long; if the value is less than that length, it must be padded with leading zeros. av1 codec parameter string components component details p the one-digit profile number: av1 profile numbers profile number description 0 "main" profile; su...
...And 17 more matches
CSS3 - Archive of obsolete content
nd :first-line becomes ::first-line. the new general sibling combinator ( h1~pre ). the next iteration of the selectors specification is already in progress, though it still hasn't reached the first public working draft stage. ...
...detection of ecmascript support, using the script media features is also proposed. ...
...ia the css font-synthesis property. css basic 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 16 more matches
How CSS is structured - Learn web development
in the example above, the css file is in the same folder as the html document, but you could place it somewhere else and adjust the path. here are three examples: <!-- inside a subdirectory called styles inside the current directory --> <link rel="stylesheet...
...esheet an internal stylesheet resides within an html document. to create an internal stylesheet, you place css inside a <style> element contained inside the html <head>. the html for an internal stylesheet might look like this: <!doctype html> <html> <head> <meta charset="utf-8"> <title>my css experiment</title> <style> h1 { color: blue; background-color: yellow; border: 1px solid black; } p { color: red; } </style> </head> <body> <h1>hello world!</h1> <p>this is my first css example</p> </body> </html> in some circumstances, internal stylesheets can be useful. for example, perhaps you're working with a content management system where you are blocked from modifying external css files. but for sites w...
...uire edits to multiple web pages. inline styles inline styles are css declarations that affect a single html element, contained within a style attribute. the implementation of an inline style in an html document might look like this: <!doctype html> <html> <head> <meta charset="utf-8"> <title>my css experiment</title> </head> <body> <h1 style="color: blue;background-color: yellow;border: 1px solid black;">hello world!</h1> <p style="color:red;">this is my first css example</p> </body> </html> avoid using css in this way when possible. it is the opposite of a best practice. first, it is the least efficient implementation of css for maintenance. one styling change might require multiple edits within in a single web page. second, inline css also mixes (css) presentati...
...And 16 more matches
Styling lists - Learn web development
for reference.</p> <ul> <li>hummus</li> <li>pita</li> <li>green salad</li> <li>halloumi</li> </ul> <h2>recipe (ordered) list</h2> <p>paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference.</p> <ol> <li>toast pita, leave to cool, then slice down the edge.</li> <li>fry the halloumi in a shallow, non-stick pan, until browned on both sides.</li> <li>wash and chop the salad.</li> <li>fill pita with salad, hummus, and fried halloumi.</li> </ol> <h2>ingredient description list</h2> <p>paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference.</p> <dl> <dt>hummus</dt> <dd>a thick dip/sauce ge...
.... handling list spacing when styling lists, you need to adjust their styles so they keep the same vertical spacing as their surrounding elements (such as paragraphs and images; sometimes called vertical rhythm), and the same horizontal spacing as each other (you can see the finished styled example on github, and find the source code too.) the css used for the text styling and spacing is as follows: /* general styles */ html { font-family: helvetica, arial, sans-serif; font-size: 10px; } h2 { font-size: 2rem; } ul,ol,dl,p { font-size: 1.5rem; } li, p { line-height: 1.5; } /* description list styles */ dd, dt { line-height: 1.5; } dt { font-weight: bold; } the first rule sets a sitewide font and a baseline font size of 10px. these are inherited by everything on th...
...know about to start with, which can be set on <ul> or <ol> elements: list-style-type: sets the type of bullets to use for the list, for example, square or circle bullets for an unordered list, or numbers, letters or roman numerals for an ordered list. list-style-position: sets whether the bullets appear inside the list items, or outside them before the start of each item. ...
...And 16 more matches
UI pseudo-classes - Learn web development
hen the return/enter key is being pressed down in the case of a keyboard activation). these basic pseudo-classes should be familiar to you now. more recently, the css selector level 3 and css basic ui level 3 added more pseudo-classes related to html forms that provide several other useful targetting conditions that you can take advantage of. we'll discuss these in more detail in the sections below, but briefly, the main ones we'll be looking at are: :required and :optional: targets required or optional form controls. :valid and :invalid, and :in-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 contro...
... <label for="email">email address (include if you want a response): </label> <input id="email" name="email" type="email"> </div> <div><button>submit</button></div> </fieldset> </form> here, the first name and last name are required, but the email address is optional. you can match these two states using the :required and :optional pseudo-classes. for example, if we apply the following css to the above html: input:required { border: 1px solid black; } input:optional { border: 1px solid silver; } the required controls would have a black border, and the optional control will have a silver border, like so: you can also try submitting the form without filling it in, to see the client-side validation error messages browsers give you by default. the above form isn't bad...
... placed relative to an element's formatting box, but form inputs work more like replaced elements and therefore don't have one), we will add an empty <span> to hang the generated content on: <div> <label for="fname">first name: </label> <input id="fname" name="fname" type="text" required> <span></span> </div> the immediate problem with this was that the span was dropping onto a new line below the input because the input and label are both set with width: 100%. to fix this we style the parent <div> to become a flex container, but also tell it to wrap its contents onto new lines if the content becomes too long: fieldset > div { margin-bottom: 20px; display: flex; flex-flow: row wrap; } the effect this has is that the label and input sit on separate lines because they are both wi...
...And 16 more matches
React interactivity: Events and state - Learn web development
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. ...
...ttribute has special meaning here: it tells react to run a given function when the user clicks on the button. there are a couple of other things to note: the camel-cased nature of onclick is important — jsx will not recognize onclick (again, it is already used in javascript for a specific purpose, which is related but different — standard onclick handler properties). all browser events follow this format in jsx – on, followed by the name of the event. let's apply this to our app, starting in the form.js component. handling form submission at the top of the form() component function, create a function named handlesubmit(). this function should prevent the default behavior of the submit event. after that, it should trigger an alert(), which can say whatever you’d like. it should...
...named addtask() which has a single parameter of name: function addtask(name) { alert(name); } next, we'll pass addtask() into <form /> as a prop. the prop can have whatever name you want, but pick a name you’ll understand later. something like addtask works, because it matches the name of the function as well as what the function will do. ...
...And 16 more matches
Getting started with Vue - Learn web development
erstand the basics of how it works. a clearer vue vue is a modern javascript framework that provides useful facilities for progressive enhancement — unlike many other frameworks, you can use vue to enhance existing html. this lets you use vue as a drop-in replacement for a library like jquery. that being said, you can also use vue to write entire single page applications (spas). this allows you to create markup managed entirely by vue, which can improve developer experience and performance when dealing with complex applications. it also allows you to take advantage of libraries for client-side routing and state management when you need to. additionally, vue takes a "middle ground" approach to tooling like client-side routing and state management. while the vue core team maintains s...
...like most frameworks, vue lets you create reusable blocks of markup via components. ...
...de routing and state management when you need to. additionally, vue takes a "middle ground" approach to tooling like client-side routing and state management. while the vue core team maintains suggested libraries for these functions, they are not directly bundled into vue. this allows you to select a different routing/state management library if they better fit your application. ...
...And 16 more matches
Eclipse CDT Manual Setup
ld be integrated back into that page, but a large amount of it is now taken care of by the mach project generation code. for now it's stored here until that integration happens in order that the eclipse cdt page isn't hugely cluttered with mostly redundant information, make setting up eclipse look much more complicated than it is nowadays. setup time some points in the rest of this document below are old and taken care of by the mach commands described above (although some of the project configuration is not done automatically yet). some of it like the section on building the index and usage tips are still relevant, and other parts still may provide useful background information to understand it in more detail on how eclipse works. you can expect it to take an hour or so to work through...
...s. you can expect it to take an hour or so to work through these instructions if you're doing so for the first time. (this assumes that you already have a copy of the mozilla source, and that you have also built the source so that you have a pre-existing object directory. if that is not the case, then get your build going now so that it can be running while you continue with the instructions below. ...
...xisting object directory. if that is not the case, then get your build going now so that it can be running while you continue with the instructions below. faq: wait, why does eclipse need an object directory?) code assistance out of the box, eclipse can provide some code assistance for the mozilla source, but it will be incomplete and often just plain broken. if you set up eclipse as detailed below, you will experience much better results. important background to help you make sense of the instructions that follow (and so that you can modify them to meet your own needs if necessary), this section provides some background on what ides need in order to provide advanced code assistance, and what eclipse cdt needs in particular. to be able to provide really good code assistance for a project...
...And 16 more matches
NSS API Guidelines
e you with some of the ways things can be done in the nss code. this will help you understand existing nss code. it should also help you understand how to write new code, and where to place it. some of the guidelines in this document, are more forward-looking than documentary. these rules are here to help us all immediately achieve more consistent and usable code, but some existing code won't follow all these rules. nss api structure this section explains the structure and relationships of the nss libraries. the layering section explains how the nss code is layered, and how higher-level functions wrap low-level functions. the libraries section descibes the nss libraries, the functionality each provides, and the layer in which the library (mostly) operates. layering each separate comp...
...that is, access to these functions should only be provided by the api directly above them. the nss apis are layered, as shown in this diagram: the boxes in the gray section, towards the center, are exported only through pkcs #11. ...
... are layered, as shown in this diagram: the boxes in the gray section, towards the center, are exported only through pkcs #11. pkcs #11 is only exported through the wrappers. the areas which need the most work (both here and throughout the code) is: the relationship of the certificate library with just about every other component (most noticeably pkcs #12, pkcs #7, and pkcs #11) splitting low key and high key components more clearly the crypto wrappers (pkcs #11 wrappers) and high key pkcs #12 and pkcs #5 libraries nss compiles into the libraries described below. the layer indicates the main layer, seen in the previous diagram, in which the library operates. the directory is the location of the library code in the nss source tree. the public headers is a list of header files ...
...And 16 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
third party assistive technology, such as screen readers, screen magnifiers and voice input software, want to track what's happening inside mozilla. they need to know about focus changes and other events, and it needs to know what objects are contained in the current document or dialog box. ...
...finally, voice dictation software needs to know what's in the current document or ui in order to implement "say what you see" kinds of features. ...
...finally, voice dictation software needs to know what's in the current document or ui in order to implement "say what you see" kinds of features. ...
...And 16 more matches
HTTP headers - HTTP
Web › HTTP › Headers
whitespace before the value is ignored. custom proprietary headers have historically been used with an x- prefix, but this convention was deprecated in june 2012 because of the inconveniences it caused when nonstandard fields became standard in rfc 6648; others are listed in an iana registry, whose original content was defined in rfc 4229. iana also maintains a registry of proposed new http headers. ...
...n 9.1.1 of [css2]) on the device. device-memory technically a part of device memory api, this header represents an approximate amount of ram client has. save-data a boolean that indicates the user agent's preference for reduced data usage. viewport-width a number that indicates the layout viewport width in css pixels. the provided pixel value is a number rounded to the smallest following integer (i.e. ceiling value). if viewport-width occurs in a message more than once, the last value overrides all previous occurrences. width the width request header field is a number that indicates the desired resource width in physical pixels (i.e. intrinsic size of an image). the provided pixel value is a number rounded to the smallest following integer (i.e. ceiling value...
...er with the set-cookie header. set-cookie send cookies from the server to the user-agent. cookie2 contains an http cookie previously sent by the server with the set-cookie2 header, but has been obsoleted. use cookie instead. set-cookie2 sends cookies from the server to the user-agent, but has been obsoleted. use set-cookie instead. cors learn more about cors here. ...
...And 16 more matches
Working with objects - JavaScript
teristics of the object. you access the properties of an object with a simple dot-notation: objectname.propertyname like all javascript variables, both the object name (which could be a normal variable) and property name are case sensitive. you can define a property by assigning it a value. ...
...ect are undefined (and not null). mycar.color; // undefined properties of javascript objects can also be accessed or set using a bracket notation (for more details see property accessors). objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it. so, for example, you could access the properties of the mycar object as follows: mycar['make'] = 'ford'; mycar['model'] = 'mustang'; mycar['year'] = 1969; an object property name can be 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...
...ng 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). ...
...And 16 more matches
The building blocks of responsive design - Progressive web apps (PWAs)
y, this means using a combination of percentages and ems/rems to size your containers and text, not fixed widths such as pixels. this has a lot of advantages in that the layout will adapt to different viewport dimensions. let's look at an example. we've written a simple-but-fun prototype for an application called snapshot, which takes a video stream from your webcam (using getusermedia()) then allows you to capture stills from that video stream (using html5 <canvas>), and save them to a gallery. you can then view previously-captured images and delete them. other articles will discuss the functionality in more detail, but here we're interested in the layout. note: you can find the snapshot app on github; check out the code and help improve it. you can also see snapshot running live. note th...
...ery, respectively. the markup is very simple: <x-deck selected-index="0"> <x-card> … </x-card> <x-card> … </x-card> <x-card> … </x-card> </x-deck> note: these weird x- elements may be unfamiliar; they are part of brick, mozilla's ui element library for mobile web apps. we have used brick to create the mobile layout for snapshot, which you will read more about below. ...
...ected-index="0"> <x-card> … </x-card> <x-card> … </x-card> <x-card> … </x-card> </x-deck> note: these weird x- elements may be unfamiliar; they are part of brick, mozilla's ui element library for mobile web apps. we have used brick to create the mobile layout for snapshot, which you will read more about below. to get these sitting side-by-side we have used the following rules: x-card { width: 100%; } x-card:nth-child(1), x-card:nth-child(2) { width: 30%; float: left; padding: 2rem; } x-card:nth-child(3) { width: 40%; float: left; height: 100%; overflow: auto; padding: 2rem; } so we're giving the first two columns a width of 30%, and the third a width of 40%, floating the columns all left. this way they end up side-by-side, and their prop...
...And 16 more matches
Content type - SVG: Scalable Vector Graphics
for properties defined in css2, an angle unit identifier must be provided. ...
...or properties defined in css2, an angle unit identifier must be provided. for angle values in svg-specific properties and their corresponding presentation attributes, the angle unit identifier is optional. if not provided, the angle value is assumed to be in degrees. in presentation attributes for all properties, whether defined in svg1.1 or in css2, the angle identifier, if specified, must be in lower case. when angles are used in an svg attribute, <angle> is instead defined as follows: angle ::= number ("deg" | "grad" | "rad")? the unit identifiers in such <angle> values must be in lower case. in the svg dom, <angle> values are represented using svgangle or svganimatedangle objects. anything <anything> the basic type <anything> is a sequence of zero or more characters. spe...
...:= "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). ...
...And 16 more matches
Introduction to Public-Key Cryptography - Archive of obsolete content
r an overview of ssl, see "introduction to ssl." for an overview of encryption and decryption, see "encryption and decryption." information on digital signatures is available from "digital signatures." public-key cryptography is a set of well-established techniques and standards for protecting communications from eavesdropping, tampering, and impersonation attacks. ...
...vesdropping, tampering, and impersonation attacks. encryption and decryption allow two communicating parties to disguise information they send to each other. the sender encrypts, or scrambles, information before sending it. the receiver decrypts, 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 ...
...y 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 identifies someone or something authentication confirms an identity how certificates are used contents of a certificate how ca certificates are used to establish trust a certificate identifies someone...
...And 15 more matches
Backgrounds and borders - Learn web development
in the tutorial, but first let's have a look at the different things you can do with backgrounds in css, by looking at the individual background properties. background colors the background-color property defines the background color on any element in css. the property accepts any valid <color>. a background-color extends underneath the content and padding box of the element. ...
... this example demonstrates two things about background images. ...
...example above to see that in action. controlling background-repeat the background-repeat property is used to control the tiling behavior of images. the available values are: no-repeat — stop the background from repeating altogether. repeat-x — repeat horizontally. repeat-y — repeat vertically. repeat — the default; repeat in both directions. try these values out in the example below. we have set the value to no-repeat so you will only see one star. try out the different values — repeat-x and repeat-y — to see what their effects are. sizing the background image in the example above, we have a large image that has ended up being cropped as it is larger than the element it is a background of. in this case we could use the background-size property, which can take length ...
...And 15 more matches
The box model - Learn web development
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 types of boxes — block boxes and inline boxes. these characteristics refer to how the box behaves in terms of page flow, and in relation to other boxes on the page: if a box is defined as a block, it will behave in the following ways: the box will break onto a new line. the box will extend in the inline direction to fill the space available in its container. in most cases this means that the box will become as wide as its container, filling up 100% of the space available. the width and height properties are ...
... display. aside: inner and outer display types at this point, we'd better also explain inner and outer display types. as mentioned above, boxes in css have an outer display type, which details whether the box is block or inline. boxes also have an inner display type, however, which dictates how elements inside that box are laid out. by default, the elements inside a box are laid out in normal flow, which means that they behave just like any other block and inline elements (as explained above). we can, however, change the inner display type by using display values like flex. if we set display: flex; on an element, the outer display type is block, but the inner display type is changed to flex. any direct children of this box will become flex items and will be laid out according to the rules...
...xes work in block and inline layout, take a look at the mdn guide to block and inline layout. when you move on to learn about css layout in more detail, you will encounter flex, and various other inner values that your boxes can have, for example grid. block and inline layout, however, is the default way that things on the web behave — as we said above, it is sometimes referred to as normal flow, because without any other instruction, our boxes lay out as block or inline boxes. examples of different display types let's move on and have a look at some examples. below we have three different html elements, all of which have an outer display type of block. the first is a paragraph, which has a border added in css. the browser renders this as a block box, so the paragraph begins on a new l...
...And 15 more matches
Flexbox - Learn web development
how css works (study introduction to css.) objective: to learn how to use the flexbox layout system to create web layouts. why flexbox? for a long time, the only reliable cross browser-compatible tools available for creating css layouts were things like floats and positioning. these are fine and they work, but in some ways they are also rather limiting and frustrating. the following simple layout requirements are either difficult or impossible to achieve with such tools, in any kind of convenient, flexible way: vertically centering a block of content inside its parent. making all the children of a container take up an equal amount of the available width/height, regardless of how much width/height is available. making all columns in a multiple column layout adopt 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 direction your browser's default language works in (left to right, in the case of an english browser). try adding the following declaration to your <section> rule: flex-direction: column; you'll see that this puts the items back in a column layout, much like they were before we added any css. before you move on, delete this declaration from your example. note: you can also lay out flex items in a reverse direction using the row-reverse and column-reverse values. experiment with these values too! wrapping one iss...
...ch like they were before we added any css. before you move on, delete this declaration from your example. note: you can also lay out flex items in a reverse direction using the row-reverse and column-reverse values. ...
...And 15 more matches
The HTML5 input types - Learn web development
prerequisites: basic computer literacy, and a basic understanding of html. ...
...d tutorial: how to build custom form widgets. e-mail address field this type of field is set using the value email for the type attribute: <input type="email" id="email" name="email"> when this type is used, the user is required to type a valid email address into the field. any other content causes the browser to display an error when the form is submitted. ...
...value email for the type attribute: <input type="email" id="email" name="email"> when this type is used, the user is required to type a valid email address into the field. any other content causes the browser to display an error when the form is submitted. you can see this in action in the below screenshot. ...
...And 15 more matches
Third-party APIs - Learn web development
displaying your twitter stream on your blog) or services (e.g. 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. ...
...ter. prerequisites: javascript basics (see first steps, building blocks, javascript objects), the basics of client-side apis objective: to learn how third-party apis work, and how to use them to enhance your websites. what are third party apis? third party apis are apis provided by third parties — generally companies such as facebook, twitter, or google — to allow you to access their functionality via javascript and use it on your site. one of the most obvious examples is using mapping apis to display custom maps on your pages. let's look at a simple mapquest api example, and use it to illustrate how third-party apis differ from browser apis. note: you might want to just get all our code examples at once, in which case you can then just search the repo ...
...ally require api keys security for browser apis tends to be handled by permission prompts, as discussed in our first article. the purpose of these is so that the user knows what is going on in the websites they visit and is less likely to fall victim to someone using an api in a malicious way. ...
...And 15 more matches
Server-side web frameworks - Learn web development
er-side web application. prerequisites: basic computer literacy. basic understanding of how server-side code handles and responds to http requests (see client-server overview). objective: to understand how web frameworks can simplify development/maintenance of server-side code and to get readers thinking about selecting a framework for their own development. the following sections illustrate some points using code fragments taken from real web frameworks. don't be concerned if it doesn't all make sense now; we'll be working you through the code in our framework-specific modules. overview server-side web frameworks (a.k.a. "web application frameworks") are software frameworks that make it easier to write, maintain and scale web applications. they provide tools...
...cusses some of the functionality that is often provided by web frameworks (not every framework will necessarily provide all of these features!). work directly with http requests and responses as we saw in the last article, web servers and browsers communicate via the http protocol — servers wait for http requests from the browser and then return information in http responses. web frameworks allow you to write simplified syntax that will generate server-side code to work with these requests and responses. this means that you will have an easier job, interacting with easier, higher-level code rather than lower level networking primitives. the example below shows how this works in the django (python) web framework. every "view" function (a request handler) receives an httprequest object con...
...to store information both to be shared with users, and about users. web frameworks often provide a database layer that abstracts database read, write, query, and delete operations. this abstraction layer is referred to as an object-relational mapper (orm). using an orm has two benefits: you can replace the underlying database without necessarily needing to change the code that uses it. this allows developers to optimize for the characteristics of different databases based on their usage. basic validation of data can be implemented within the framework. this makes it easier and safer to check that data is stored in the correct type of database field, has the correct format (e.g. an email address), and isn't malicious in any way (crackers can use certain patterns of code to do bad things s...
...And 15 more matches
Strategies for carrying out testing - Learn web development
oroughly and provide full support. b grade: older/less capable browsers — known not to be capable. test, and provide a more basic experience that gives full access to core information and services. c grade: rare/unknown browsers — don't test, but assume they are capable. serve the full site, which should work, at least with the fallbacks provided by our defensive coding. throughout the following sections, we'll build up a support chart in this format. note: yahoo first made this approach popular, with their graded browser support approach. educated guesses you could call these "assumptions", or "gut feelings". this is not an accurate, scientific approach, but as someone who has experience with the web industry you'll have a pretty good idea of at least some of the browsers you sh...
...latest versions of ios safari, the last couple of versions of the old android stock browser, and chrome and firefox for ios and android. you should ideally test these on both a phone and a tablet, to make sure that responsive designs are working ok. you might also know that a number of people still use ie 9. this is old and less capable, so let's put it in the b grade tier. ...
...ve finished filling in everything, press the get tracking id button, then accept the terms of service that appear. the next page provides you with some code snippets and other instructions. for a basic website, what you need to do is copy the website tracking code block and paste it into all the different pages you want to track using google analytics on your site. you could place the snippets below your closing </body> tag, or somewhere else appropriate that keeps it from getting muddled up with your application code. upload the changes to the development server, or wherever else you need your code. that's it! your site should now be ready to start reporting analytics data. studying analytics data now you should be able to go back to the analytics web homepage, and start looking at the...
...And 15 more matches
Key Values - Web APIs
corresponding virtual keycodes for common platforms are included where available. learn how to use these key values in javascript using keyboardevent.key special values | modifier keys | whitespace keys | navigation keys | editing keys | ui keys | device keys | ime and composition keys | function keys | phone keys | multimedia keys | audio control keys | tv control keys | media controller keys | speech recognition keys | document keys | application selector keys | browser control keys | numeric keypad keys special values values of key which have special meanings other than identifying a specific key or character. ...
...key_iso_level5_lock (0xfe13) qt::key_altgr (0x01001103 qt::key_mode_switch (0x0100117e) "capslock" the caps lock key. toggles the capital character lock on and off for subsequent input. vk_capital (0x14) kvk_capslock (0x39) gdk_key_caps_lock (0xffe5) qt::key_capslock (0x01000024) keycode_caps_lock (115) "control" the control, ctrl, or ctl key. ...
...often handled in hardware so that events aren't generated for this key. ...
...And 15 more matches
Migrating from webkitAudioContext - Web APIs
d 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 webkitaudiocontext monkeypatch, which automatically fixes some of these changes to make most code targetting webkitaudiocontext to work on the standards based audiocontext out of the box, but it currently doesn't handle all of the cases below. please consult the readme file for that library to see a list of apis that are automatically handled by it. changes to the creator methods three of the creator methods on webkitaudiocontext have been renamed in audiocontext. creategainnode() has been renamed to creategain. createdelaynode() has been renamed to createdelay. createjavascriptnode() has been renamed to createscriptprocessor...
...audiocontext have been renamed in audiocontext. creategainnode() has been renamed to creategain. createdelaynode() has been renamed to createdelay. createjavascriptnode() has been renamed to createscriptprocessor. these are simple renames that were made in order to improve the consistency of these method names on audiocontext. ...
...ainon()/noteoff() methods were the original way to start/stop output in these nodes, and in the newer versions of the specification, the noteon() and notegrainon() methods were consolidated into a single start() method, and the noteoff() method was renamed to the stop() method. in order to port your code, you can just rename the method that you're using. ...
...And 15 more matches
Basic concepts of flexbox - CSS: Cascading Style Sheets
zontal and left-to-right writing modes. modern layout methods encompass the range of writing modes and so we no longer assume that a line of text will start at the top left of a document and run towards the right hand side, with new lines appearing one under the other. you can read more about the relationship between flexbox and the writing modes specification in a later article; however, the following description should help explain why we do not talk about left and right and top and bottom when we describe the direction that our flex items flow in. if the flex-direction is row and i am working in english, then the start edge of the main axis will be on the left, the end edge on the right. if i were to work in arabic, then the start edge of my main axis would be on the right and the end...
...e on the right and the end edge on the left. in both cases the start edge of the cross axis is at the top of the flex container and the end edge at the bottom, as both languages have a horizontal writing mode. after a while, thinking about start and end rather than left and right becomes natural, and will be useful to you when dealing with other layout methods such as css grid layout which follow the same patterns. the flex container an area of a document laid out using flexbox is called a flex container. to create a flex container, we set the value of the area's container's display property to flex or inline-flex. as soon as we do this the direct children of that container become flex items. as with all properties in css, some initial values are defined, so when creating a flex contain...
...ument laid out using flexbox is called a flex container. to create a flex container, we set the value of the area's container's display property to flex or inline-flex. as soon as we do this the direct children of that container become flex items. as with all properties in css, some initial values are defined, so when creating a flex container all of the contained flex items will behave in the following way. items display in a row (the flex-direction property's default is row). the items start from the start edge of the main axis. the items do not stretch on the main dimension, but can shrink. the items will stretch to fill the size of the cross axis. the flex-basis property is set to auto. the flex-wrap property is set to nowrap. the result of this is that your items will all line ...
...And 15 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
character is represented by either 1 or 2 code units. if you want to represent a single character, you just use a string consisting of that single character. ...
...alue hasn't even been assigned yet. we'll talk about variables later, but in javascript it is possible to declare a variable without assigning a value to it. if you do this, the variable's type is undefined. undefined is actually a constant. javascript has a boolean type, with possible values true and false (both of which are keywords.) any value can be converted to a boolean according to the following rules: false, 0, empty strings (""), nan, null, and undefined all become false. all other values become true. you can perform this conversion explicitly using the boolean() function: boolean(''); // false boolean(234); // true however, this is rarely necessary, as javascript will silently perform this conversion when it expects a boolean, such as in an if statement (see below). for t...
...ts a boolean, such as in an if statement (see below). for this reason, we sometimes speak simply of "true values" and "false values," meaning values that become true and false, respectively, when converted to booleans. alternatively, such values can be called "truthy" and "falsy", respectively. boolean operations such as && (logical and), || (logical or), and ! ...
...And 15 more matches
Loops and iteration - JavaScript
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 condition evaluates to false. the javascript for loop is similar to the java and c for loop. a for statement looks as follows: for ([initialexpression]; [conditionexpression]; [incrementexpression]) statement when a for loop executes, the following occurs: the initializing expression initialexpression, if any, is executed. 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 conditionexpre...
...s 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 of selected options in a scrolling list (a <select> element that allows multiple selections). the for statement declares the variable i and initializes it to 0. it checks that i is less than the number of options in the <select> element, performs the succeeding if statement, and increments i by after each pass through the loop. <form ...
... (a <select> element that allows multiple selections). the for statement declares the variable i and initializes it to 0. it checks that i is less than the number of options in the <select> element, performs the succeeding if statement, and increments i by after each pass through the loop. ...
...And 15 more matches
JavaScript modules - JavaScript
ality natively, and this is what this article is all about. this can only be a good thing — browsers can optimize loading of modules, making it more efficient than having to use a library and do all of that extra client-side processing and extra round trips. ...
...bpage, and then draw (and report information about) different shapes on the canvas. these are fairly trivial, but have been kept deliberately simple to demonstrate modules clearly. note: if you want to download the examples and run them locally, you'll need to run them through a local web server. ...
...cally, you'll need to run them through a local web server. basic example structure in our first example (see basic-modules) we have a file structure as follows: index.html main.js modules/ canvas.js square.js note: all of the examples in this guide have basically the same structure; the above should start getting pretty familiar. the modules directory's two modules are described below: canvas.js — contains functions related to setting up the canvas: create() — creates a canvas with a specified width and height inside a wrapper <div> with a specified id, which is itself appended inside a specified parent element. returns an object containing the canvas's 2d context and the wrapper's id. createreportlist() — creates an unordered list appended inside a specifie...
...And 15 more matches
Performance fundamentals - Web Performance
ts (possibly multiple ones) in response to user inputs. for example, when a user taps the screen, they expect the pixels to change in a certain way. for this interaction, the responsiveness metric is the time elapsed between the tap and the pixel change. responsiveness sometimes involves multiple stages of feedback. application launch is one particularly important case discussed in more detail below. responsiveness is important simply because people get frustrated and angry when they're ignored. your app is ignoring the user every second that it fails to respond to the user's input. framerate framerate is the rate at which the system changes pixels displayed to the user. this is a familiar concept: everyone prefers, say, games that display 60 frames per second over ones that display 10 fr...
...le meeting other upp goals. that doesn't mean the system should waste memory. when a system uses more memory than necessary to maintain some particular user state, the system is wasting a resource it could use to retain some other user state. in practice, 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 s...
...ive 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. ...
...And 15 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
a string which is passed to the search component. autofill obsolete since gecko 1.9.1 type: boolean note: applies to: thunderbird and seamonkeyif set to true, the best match will be filled into the textbox as the user types. if false, the default, the value will not be filled in until the user selects an item. as of gecko 1.9.1, this attribute is now always specified in lower case. autofillaftermatch obsolete since gecko 1.9.1 type: boolean if set to true, the entire text of the best match will be displayed at the end of the input. if false, only the text that hasn't been entered yet will be filled in. the textbox.autofill attribute must be set to true to use this feature. as of gecko 1.9.1, this attribute is superseded by the completedefaultindex attribute...
...boolean this attribute is not used and is only provided for compatibility with the menulist element. disableautocomplete obsolete since gecko 1.9.1 type: boolean if true, the autocomplete behavior will be disabled. you might use a script to change this attribute. if false, the default, autocomplete is enabled. as of gecko 1.9.1, this attribute is now always specified in lower case. disableautocomplete new in thunderbird 3requires seamonkey 2.0 type: boolean if true, the autocomplete behavior will be disabled. you might use a script to change this attribute. if false, the default, autocomplete is enabled. disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is disabled. disab...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. disable...
...And 14 more matches
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
organizations implement internal procedural 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. ...
...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 standards all the time. memos, time cards, and accounting procedures are all standardized across groups. in the development world, there is a need for standards because applications are designed across multiple development groups. many organizations publ...
... may decide that c++, java, and javascript will be the primary coding languages. they may require that each project be comprised of marketing requirements documents, product requirements documents, functional requirements documents, quality assurance test plans, and certification documents. as organizations mature, they discover that they need more processes to give them greater control, which allows them to more easily plan and predict. with processes, organizations can make release schedules, implement marketing plans, analyze resource allocations, and make adjustments when needed. adherence to standards and processes can actually provide a level of flexibility because development does become predictable. in addition to predictability, standard processes improve understanding and streamlin...
...And 14 more matches
Useful string methods - Learn web development
page! now, before your brain starts melting, don't worry! you really don't need to know about most of these early on in your learning journey. but there are a few that you'll potentially use quite often that we'll look at here. let's enter some examples into the browser developer console. finding the length of a string this is easy — you simply use the length property. try entering the following lines: let browsertype = 'mozilla'; browsertype.length; this should return the number 7, because "mozilla" is 7 characters long. this is useful for many reasons; for example, you might want to find the lengths of a series of names so you can display them in order of length, or let a user know that a username they have entered into a form field is too long if it is over a certain length. ret...
... variable name. inside the square brackets you include the number of the character you want to return, so for example to retrieve the first letter you'd do this: browsertype[0]; remember: computers count from 0, not 1! you could use this to, for example, find the first letter of a series of strings and order them alphabetically. to retrieve the last character of any string, we could use the following line, combining this technique with the length property we looked at above: browsertype[browsertype.length-1]; the length of "mozilla" is 7, but because the count starts at 0, the character position is 6; using length-1 gets us the last character. finding a substring inside a string and extracting it sometimes you'll want to find if a smaller string is present inside a larger one (we gene...
...wsertype.indexof('zilla'); this gives us a result of 2, because the substring "zilla" starts at position 2 (0, 1, 2 — so 3 characters in) inside "mozilla". such code could be used to filter strings. for example, we may have a list of web addresses and only want to print out the ones that contain "mozilla". this can be done in another way, which is possibly even more effective. try the following: browsertype.indexof('vanilla'); this should give you a result of -1 — this is returned when the substring, in this case 'vanilla', is not found in the main string. you could use this to find all instances of strings that don't contain the substring 'mozilla', or do, if you use the negation operator, as shown below. you could do something like this: if(browsertype.indexof('mozill...
...And 14 more matches
Ember interactivity: Events, classes and state - Learn web development
s and use events to control interactivity, and keep track of app state using a service. adding interactivity now we've got a refactored componentized version of our todo app, lets walk through how we can add the interactivity we need to make the app functional. when beginning to think about interactivity, it's good to declare what each component's goals and responsibilities are. in the below sections we’ll do this for each component, and then walk you through how the functionality can be implemented. creating todos for our card-header / todo input, we'll want to be able to submit our typed in todo task when we press the enter key and have it appear in the todos list. we want to be able to capture the text typed into the input. we do this so that our javascript code knows what we...
...e able to capture the text typed into the input. we do this so that our javascript code knows what we typed in, and we can save our todo and pass that text along to the todo list component to display. we can capture the keydown event via the on modifier, which is just ember syntactic sugar around addeventlistener and removeeventlistener (see this explanation if needed). add the new line shown below to your header.hbs file: <input class='new-todo' aria-label='what needs to be done?' placeholder='what needs to be done?' autofocus {{on 'keydown' this.onkeydown}} > this new attribute is inside double curly braces, which tells you it is part of ember's dynamic templating syntax. the first argument passed to on is the type of event to respond to (keydown), and the last argument is the...
...t'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. ...
...And 14 more matches
Getting started with Svelte - Learn web development
es 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 with svelte have smaller bundle sizes, which is ideal for devices with slow network connections and limited processing power. less code means less kb to download, parse, execute, and keep hanging around in memory. highly interactive pages or complex visualizations: if you are building data-visualizations that n...
...execute, and keep hanging around in memory. highly interactive pages or complex visualizations: if you are building data-visualizations that need to display a large number of dom elements, the performance gains that come from a framework with no runtime overhead will ensure that user interactions are snappy and responsive. onboarding people with basic web development knowledge: svelte has a shallow learning curve. web developers with basic html, css, and javascript knowledge can easily grasp svelte specifics in a short time and start building web applications. moreover, with the help of sapper (a framework based on svelte), you can also develop applications with advanced features like server-side rendering, code splitting, file-based routing and offline support. and then there's also svel...
...d features like server-side rendering, code splitting, file-based routing and offline support. and then there's also svelte native, which lets you build native mobile applications. how does svelte work? being a compiler, svelte can extend html, css, and javascript, generating optimal javascript code without any runtime overhead. to achieve this, svelte extends vanilla web technologies in the following ways: it extends html by allowing javascript expressions in markup and providing directives to use conditions and loops, in a fashion similar to handlebars. it extends css by adding a scoping mechanism, 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 t...
...And 14 more matches
Gecko info for Windows accessibility vendors
istive technology vendors. events such as focus changes must be tracked through msaa events, rather than dom events. xul: extensible user-interface language the xml-based language used by firefox and mozilla to develop the ui. similar to html in that it can be combined with css and javascript to make powerful applications. contains more desktop-style widgets than html and follows a box layout model, rather than being text-flow based. ajax: asynchronous javascript and xml ajax is a method of building interactive web applications that process user requests, user actions immediately in real time, unlike an http request, during which users must wait for a whole page to reload or for a new page to load. data is therefore stored and retrieved dynamically ...
...msaa) xul-based clients make full use of the gecko architecture, not only for html content, as well as for menus, dialogs and the entire user interface via an xml language called xul (extensible user-interface language). none of the user interface contains standard windows controls -- not even the menus! this is done to ensure a common look and feel across all supported platforms, and to allow for different skins (appearances). firefox (please use version 1.1 alpha builds or later) thunderbird (please use version 1.1 alpha builds or later) mozilla seamonkey (please use 1.8 alpha builds or later) how to find the content window and load the document screen readers need to find the content window so that they know where to start grabbing the msaa tree, i...
...ozilla seamonkey (please use 1.8 alpha builds or later) how to find the content window and load the document screen readers need to find the content window so that they know where to start grabbing the msaa tree, in order to load the current document into a buffer in their own process. the content window always has the class mozillacontentwindowclass. ...
...And 14 more matches
Experimental features in Firefox
ox along with information on how to activate them, if necessary. you can test your web sites and applications before these features get released and ensure everything will still work with the latest web technology capabilities. to test these experimental features, you need to download firefox nightly or firefox developer edition. which you need is described alongside each feature's description below. editor's note: when adding features to these tables, please try to include a link to the relevant bug or bugs using the bug macro: {{bug(bug-number)}}. html element: <dialog> the html <dialog> element and its associated dom apis provide support for html-based modal dialog boxes. the current implementation is a little inelegant but is basically functional. see bug 840640 for more details. ...
... see bug 1223880 for more details. release channel version added enabled by default? nightly 50 no developer edition 50 no beta 50 no release 50 no preference name layout.css.initial-letter.enabled conic gradients coni...
...and sunken initial letters are displayed. see bug 1223880 for more details. release channel version added enabled by default? nightly 50 no developer edition 50 no beta 50 no release 50 no preference name layout.css.initial-letter.enabled conic gradients conic gradients expand css gradients to allow the color transitions to be rendered circling around a center point rather than radiating from it. see bug 1175958 for more details. release channel version added enabled by default? nightly 75 no developer edition 75 no beta 75 no release 75 no preference name layout.css.conic-gradient.enabled and gfx.web...
...And 14 more matches
sslcrt.html
mes nss_cmpcertchainwcanames cert_verifycertnow checks that the current date is within the certificate's validity period and that the ca signature on the certificate is valid. syntax #include <cert.h> secstatus cert_verifycertnow( certcertdbhandle *handle, certcertificate *cert, prbool checksig, seccertusage certusage, void *wincx); parameters this function has the following parameters: handle a pointer to the certificate database handle. cert a pointer to the certificate to be checked. checksig indicates whether certificate signatures are to be checked. pr_true means certificate signatures are to be checke...
...esslserverwithstepup certusagesslca certusageemailsigner certusageemailrecipient certusageobjectsigner certusageusercertimport certusageverifyca certusageprotectedobjectsigner wincx the pin argument value to pass to pk11 functions. see description below for more information. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to obtain the error code. description the cert_verifycertnow function must call one or more pk11 functions to obtain the services of a pkcs #11 module. some of the pk11 functions require a pin argument (see ssl_setpkcs11pin...
...tails), which must be specified in the wincx parameter. to obtain the value to pass in the wincx parameter, call ssl_revealpinarg. cert_verifycertname compares the common name specified in the subject dn for a certificate with a specified hostname. syntax #include <cert.h> secstatus cert_verifycertname( certcertificate *cert, char *hostname); parameters this function has the following parameters: cert a pointer to the certificate against which to check the hostname referenced by hostname. hostname the hostname to be checked. returns the function returns one of these values: if the common name in the subject dn for the certificate matches the domain...
...And 14 more matches
An Overview of XPCOM
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. ...
...ore familiarity in the tutorial itself, which describes the creation of a mozilla component called weblock. the xpcom solution the cross platform component object module (xpcom) is a framework which allows developers to break up monolithic software projects into smaller modularized pieces. these pieces, known as components, are then assembled back together at runtime. the goal of xpcom is to allow different pieces of software to be developed and built independently of one another. in order to allow interoperability between components within an application, xpcom separates the implementation of a component from the interface, which we discuss in interfaces. but xpcom also provides several tools and libraries that enable the loading and manipulation of these components, services that help th...
...ing web browsers and other applications. xpcom is the means of accessing gecko library functionality and embedding or extending gecko. this book focuses on the latter - extending gecko - but the fundamental ideas in the book will be important to developers embedding gecko as well. gecko is used in many internet applications, mostly browsers and most notably mozilla firefox. components 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 softwa...
...And 14 more matches
Mozilla
the articles below include content about downloading and building mozilla code. in addition, you'll find helpful articles about how the code works, how to build add-ons for mozilla applications and the like. a bird's-eye view of the mozilla framework the purpose of this article is to provide a high-level technical overview of the architecture of the extensible, object-based mozilla application framework. accessibility and mozilla accessibility is the idea that software (among other things) should be designed to be usable and, as much as possible, convenient to use for people with disabilities. ...
...al overview of the architecture of the extensible, object-based mozilla application framework. accessibility and mozilla accessibility is the idea that software (among other things) should be designed to be usable and, as much as possible, convenient to use for people with disabilities. mozilla strives to make its software accessible; the documents below cover the ways in which we do so. add-ons add-ons allow developers to extend and modify the functionality of firefox. adding a new css property this page describes how to add a new css property to the style system. the style system is the part of the code in gecko that is responsible for producing a computed value for every prop...
... hacking mozilla this guide introduces the mozilla project and provides an overview for developers interested in contributing to or exploring the various parts of the codebase. android-specific test suites there are several android-specific test suites that run on the firefox for android codebase: api change rules until further notice, the following rules govern api changes: application cache implementation overview this happens in nshttpchannel::opencacheentry(). all top level document loading (navigation) channels are set chooseapplicationcache flag, which happens in nsdocshell::douriload(). channels having that flag set are searching for nsiapplicationcache object prior inspecting normal h...
...And 14 more matches
Console messages - Firefox Developer Tools
most of the web console is occupied by the message display pane: each message is displayed as a separate row: time the time the message was recorded. this is not shown by default: you can opt to see timestamps by selecting show timestamps in the console settings menu (gear icon in the console toolbar). icon not all console messages contain icons. the following icons may be used: informational message warning error blocked; for network messages in addition, a disclosure triangle indicates that further information is available; clicking it displays or collapses that information. message the message itself. number of occurrences if a line that generates a warning or error is executed more than...
...ole api messages, the message can be traced to a specific line of code. the console then provides a link to the filename and line number that generated the message. by default, the console is cleared each time you navigate to a new page or reload the current page. to override this behavior, enable persist logs in the console settings menu (gear icon). the context menu options listed below are available on all message categories. additional context menu options are described in the subsection for the message category they apply to. copy message copies the selected message to the clipboard. select all selects all messages available in the message display pane. export visible messages to clipboard copies all messages available in the display pane to the clipboard. file ...
...r source generates will show up in the web console with a link back to the original source, not the compressed version. async stack frames stack traces show stack frames for async functions separately from those for synchronous functions. when you run code containing an async function, its traces (console.trace or thrown error) are shown with an async: prefix. ...
...And 14 more matches
Regular expressions - JavaScript
are used with the exec() and test() methods of regexp, and with the match(), matchall(), replace(), replaceall(), search(), and split() methods of string. this chapter describes javascript regular expressions. ...
...one of two ways: using a regular expression literal, which consists of a pattern enclosed between slashes, as follows: let re = /ab+c/; regular expression literals provide compilation of the regular expression when the script is loaded. if the regular expression remains constant, using this can improve performance. or calling the constructor function of the regexp object, as follows: let re = new regexp('ab+c'); using the constructor function provides runtime compilation of the regular expression. use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input. writing a regular expression pattern a regular expression pattern is composed of simple...
...bstring "abc". there is no match in the string "grab crab" because while it contains the substring "ab c", it does not contain the exact substring "abc". using special characters when the search for a match requires something more than a direct match, such as finding one or more b's, or finding white space, you can include special characters in the pattern. for example, to match a single "a" followed by zero or more "b"s followed by "c", you'd use the pattern /ab*c/: the * after "b" means "0 or more occurrences of the preceding item." in the string "cbbabbbbcdebc", this pattern will match the substring "abbbbc". the following pages provide lists of the different special characters that fit into each category, along with descriptions and examples. assertions assertions include boundarie...
...And 14 more matches
Codecs used by WebRTC - Web media technologies
abilities 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 resolution that is acceptable. the sender is not required to support this mechanism, however, so you have to be prepared to receive ...
...ort this mechanism, however, so you have to be prepared to receive media at a different resolution than you requested. beyond this simple maximum resolution request, specific codecs may offer further ways to ask for specific media configurations. supported video codecs webrtc establishes a baseline set of codecs which all compliant browsers are required to support. some browsers may choose to allow other codecs as well. below are the video codecs which are required in any fully webrtc-compliant browser, as well as the profiles which are required and the browsers which actually meet the requirement. mandatory video codecs codec name profile(s) browser compatibility vp8 — chrome, edge, firefox, safari (12.1+) avc / h.264 constrained baseline ...
..., firefox[1], safari [1] firefox for android 68 and later do not support avc (h.264) anymore. this is due to a change in google play store requirements that prevent firefox from downloading and installing the openh264 codec needed to handle h.264 in webrtc connections. see this article on sumo for details. for details on webrtc-related considerations for each codec, see the sub-sections below by following the links on each codec's name. complete details of what video codecs and configurations webrtc is required to support can be found in rfc 7742: webrtc video processing and codec requirements. it's worth noting that the rfc covers a variety of video-related requirements, including color spaces (srgb is the preferred, but not required, default color space), recommendations for webcam...
...And 14 more matches
Using the WebAssembly JavaScript API - WebAssembly
(func (export "exported_func") i32.const 42 call $i)) in the second line, you will see that the 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. 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. these methods are easier than their non-stream...
... directly into module/instance instances, cutting out the need to separately put the response into an arraybuffer. this example (see our instantiate-streaming.html demo on github, and view it live also) shows how to use instantiatestreaming() to fetch a wasm module, import a javascript function into it, compile and instantiate it, and access its exported function — all in one step. ...
...tance instances, cutting out the need to separately put the response into an arraybuffer. this example (see our instantiate-streaming.html demo on github, and view it live also) shows how to use instantiatestreaming() to fetch a wasm module, import a javascript function into it, compile and instantiate it, and access its exported function — all in one step. add the following to your script, below the first block: webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); the net result of this is that we call our exported webassembly function exported_func, which in turn calls our imported javascript function imported_func, which logs the value provided inside the webassembly instance (42) to the console. if you save your exa...
...And 14 more matches
Appendix: What you should know about open-source software licenses - Archive of obsolete content
mit from the copyright holder, or must be assigned partial rights by the author. this use permit for a copyrighted work is called a license. when we talk about a driver’s license, we mean a permit to drive a car. when we talk about a license to kill, we mean james bond. a license on a copyrighted work is a use permit that says “it’s ok to use this work within this scope, as long as you follow these conditions.” those conditions could be something like “if you pay me money” or “you can print up to 10,000 copies.” software licenses software is subject to copyright law. in order to use it (in the authorial sense), you need permission from the copyright holder. how software licenses work in order to duplicate, distribute, or modify software, you need a use permit. duplicati...
... use within permitted scope fixme: wow, the table is weird! so what’s an oss license? so now you’re wondering, what conditions does an oss license place on software? this can be briefly answered by the open source definition, which was determined by the open source initiative (osi). 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, distribute, and modify) the source code, following certain conditions. this means that the author is granting users the use of the work...
.... the user 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. these conditions will vary from one license to the next, but the open source definition stipulates the following minimum conditions: the integrity of the author’s source code must be preserved; no discrimination may be made against individuals or organizations; no discrimination may be made based on field of endeavor; no additional licensing can be required when redistributing; license must not be specific to a product; license must not interfere with other software. the “no discrimination ...
...And 13 more matches
HTML: A good basis for accessibility - Learn web development
e. good for seo — search engines give more importance to keywords inside headings, links, etc. than keywords included in non-semantic <div>s, etc., so your documents will be more findable by customers. let's get on and look at accessible html in more detail. note: it is a good idea to have a screen reader set up on your local computer so that you can do some testing of the examples shown below. see our screen readers guide for more details. good semantics we've already talked about the importance of proper semantics, and why we should use the right html element for the job. this cannot be ignored, as it is one of the main places that accessibility is badly broken if not handled properly. out there on the web, the truth is that people do some very strange things with html markup. so...
...t on your page (such as ad banners) over which you have no control. the goal isn't "all or nothing." however, — every improvement you can make will help the cause of accessibility. text content one of the best accessibility aids a screen reader user can have is an excellent content structure with headings, paragraphs, lists, etc. an excellent semantic example might look something like the following: <h1>my heading</h1> <p>this is the first section of my document.</p> <p>i'll add another paragraph here too.</p> <ol> <li>here is</li> <li>a list for</li> <li>you to read</li> </ol> <h2>my subheading</h2> <p>this is the first subsection of my document. i'd love people to be able to find this content!</p> <h2>my 2nd subheading</h2> <p>this is the second subsection of my content. ...
...at this is pretty easy to navigate: the screen reader reads each header out as you progress through the content, notifying you what a heading is, what is a paragraph, etc. it stops after each element, letting you go at whatever pace is comfortable for you. you can jump to the next/previous heading in many screen readers. you can also bring up a list of all headings in many screen readers, allowing you to use them as a handy table of contents to find specific content. people sometimes write headings, paragraphs, etc. using presentational html and line breaks, something like the following: <font size="7">my heading</font> <br><br> this is the first section of my document. <br><br> i'll add another paragraph here too. <br><br> 1. here is <br><br> 2. a list for <br><br> 3. you to read <b...
...And 13 more matches
HTML: A good basis for accessibility - Learn web development
e. good for seo — search engines give more importance to keywords inside headings, links, etc. than keywords included in non-semantic <div>s, etc., so your documents will be more findable by customers. let's get on and look at accessible html in more detail. note: it is a good idea to have a screen reader set up on your local computer so that you can do some testing of the examples shown below. see our screen readers guide for more details. good semantics we've already talked about the importance of proper semantics, and why we should use the right html element for the job. this cannot be ignored, as it is one of the main places that accessibility is badly broken if not handled properly. out there on the web, the truth is that people do some very strange things with html markup. so...
...t on your page (such as ad banners) over which you have no control. the goal isn't "all or nothing." however, — every improvement you can make will help the cause of accessibility. text content one of the best accessibility aids a screen reader user can have is an excellent content structure with headings, paragraphs, lists, etc. an excellent semantic example might look something like the following: <h1>my heading</h1> <p>this is the first section of my document.</p> <p>i'll add another paragraph here too.</p> <ol> <li>here is</li> <li>a list for</li> <li>you to read</li> </ol> <h2>my subheading</h2> <p>this is the first subsection of my document. i'd love people to be able to find this content!</p> <h2>my 2nd subheading</h2> <p>this is the second subsection of my content. ...
...at this is pretty easy to navigate: the screen reader reads each header out as you progress through the content, notifying you what a heading is, what is a paragraph, etc. it stops after each element, letting you go at whatever pace is comfortable for you. you can jump to the next/previous heading in many screen readers. you can also bring up a list of all headings in many screen readers, allowing you to use them as a handy table of contents to find specific content. people sometimes write headings, paragraphs, etc. using presentational html and line breaks, something like the following: <font size="7">my heading</font> <br><br> this is the first section of my document. <br><br> i'll add another paragraph here too. <br><br> 1. here is <br><br> 2. a list for <br><br> 3. you to read <b...
...And 13 more matches
Other form controls - Learn web development
objective: to understand the non-<input> form features, and how to implement them using html. multi-line text fields a multi-line text field is specified using a <textarea> element, rather than using the <input> element. <textarea cols="30" rows="8"></textarea> this renders like so: the main difference between a <textarea> and a regular single line text field is that users are allowed to include hard line breaks (i.e. pressing return) that will be included when the data is submitted. <textarea> also takes a closing tag, and any default text you want it to contain should be put between the opening and closing tags. in contrast, the <input> is an empty element with no closing tag — any default value is put inside the value attribute. note that even though you can put anyth...
...d javascript), because of its nature, it is all rendered as if it was plain text content. (using contenteditable on non-form controls provides an api for capturing html/"rich" content instead of plain text). visually, the text entered wraps and the form control is by default resizable. modern browsers provide a drag handle that you can drag to increase/decrease the size of the text area. the following screenshots show default, focused, and disabled <textarea> elements in firefox 71 and safari 13 on macos, and edge 18, yandex 14, firefox 71 and chrome 79 on windows 10. note: you can find a slightly more interesting example of text area usage in the example we put together in the first article of the series (see the source code also). controlling multi-line rendering <textarea> accepts...
...mitted is not wrapped but the text rendered by the browser is wrapped; hard (the cols attribute must be specified when using this value), which means both the submitted and rendered texts are wrapped, and off, which stops wrapping. controlling textarea resizability the ability to resize a <textarea> is controlled with the css resize property. ...
...And 13 more matches
CSS property compatibility table for form controls - Learn web development
due to the complexity of css and html forms, these tables can't be considered a perfect reference. however, they will give you good insight into what can and can't be done, which will help you learn how to do things. how to read the tables values for each property, there are four possible values: yes there's reasonably consistent support for the property across browsers. you may still face strange side effects in certain edge cases. partial while the property works, you may frequently face strange side effects or inconsistencies. you should probably avoid these properties unless you master those side effects first. ...
...perties unless you master those side effects first. no the property simply doesn't work or is so inconsistent that it's not reliable. n.a. the property has no meaning for this type of widget. ...
...rowsers at a global level: border, background, border-radius, height using one of these properties can partially or fully turn off the native look & feel of widgets on some browsers. be careful when you use them. line-height this property is supported inconsistently across browsers and you should avoid it. text-decoration this property is not supported by opera on form widgets. text-overflow opera, safari, and ie9 do not support this property on form widgets. text-shadow opera does not support text-shadow on form widgets and ie9 does not support it at all. text fields see the text, search, and password input types. property n t note css box model width yes yes height partial[1][2] yes webkit browser...
...And 13 more matches
From object to iframe — other embedding technologies - Learn web development
previous overview: multimedia and embedding next by now you should really be getting the hang of embedding things into your web pages, including images, video and audio. at this point we'd like to take somewhat of a sideways step, looking at some elements that allow you to embed a wide variety of content types into your webpages: the <iframe>, <embed> and <object> elements. <iframe>s are for embedding other web pages, and the other two allow you to embed pdfs, svg, and even flash — a technology that is on the way out, but which you'll still see semi-regularly. prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, familiarity with html fundamentals (as covered in getting started with html) and the previous articles in ...
... this module. objective: to learn how to embed items into web pages using <object>, <embed>, and <iframe>, like flash movies and other webpages. a short history of embedding a long time ago on the web, it was popular to use frames to create websites — small parts of a website stored in individual html pages. these were embedded in a master document called a frameset, which allowed you to specify the area on the screen that each frame filled, rather like sizing the columns and rows of a table. these were considered the height of coolness in the mid to late 90s, and there was evidence that having a webpage split up into smaller chunks like this was better for download speeds — especially noticeable with network connections being so slow back then. they did however have m...
...embedding these technologies was achieved through elements like <object>, and the lesser-used <embed>, and they were very useful at the time. ...
...And 13 more matches
HTML table basics - Learn web development
Learn › HTML › Tables › Basics
s and cells, headings, making cells span multiple columns and rows, and how to group together all the cells in a column for styling purposes. prerequisites: the basics of html (see introduction to 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...
...ty, 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 associations between row and column headers. look at the table below for example and find a jovian gas giant with 62 moons. you can find the answer by associating the relevant row and column headers. data about the planets of our solar system (planetary facts taken from nasa's planetary fact sheet - metric. name mass (1024kg) diameter (km) density (kg/m3) gravity (m/s2) length of day (hours) distance from sun (106km) mean temper...
...ooter, etc. you can find more details and an example at page layouts in our accessibility learning module. this was commonly used because css support across browsers used to be terrible; table layouts are much less common nowadays, but you might still see them in some corners of the web. in short, using tables for layout rather than css layout techniques is a bad idea. the main reasons are as follows: layout tables reduce accessibility for visually impaired users: screenreaders, used by blind people, interpret the tags that exist in an html page and read out the contents to the user. because tables are not the right tool for layout, and the markup is more complex than with css layout techniques, the screenreaders' output will be confusing to their users. tables produce tag soup: as menti...
...And 13 more matches
Graceful asynchronous programming with Promises - Learn web development
this is useful for setting up a sequence of async operations to work correctly. this article shows you how promises work, how you'll see them in use with web apis, and how to write your own. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand promises and how to use them. ...
...t example, we'll use the fetch() method to fetch an image from the web, the blob() method to transform the fetch response's raw body contents into a blob object, and then display that blob inside an <img> element. this is very similar to the example we looked at in the first article of the series, but we'll do it a bit differently as we get you building your own promise-based code. note: the following example will not work if you just run it directly from the file (i.e. via a file:// url). you need to run it through a local testing server, or use an online solution such as glitch or github pages. first of all, download our simple html template and the sample image file that we'll fetch. add a <script> element at the bottom of the html <body>. inside your <script> element,...
...will not work if you just run it directly from the file (i.e. via a file:// url). you need to run it through a local testing server, or use an online solution such as glitch or github pages. first of all, download our simple html template and the sample image file that we'll fetch. add a <script> element at the bottom of the html <body>. inside your <script> element, add the following line: let promise = fetch('coffee.jpg'); this calls the fetch() method, passing it the url of the image to fetch from the network as a parameter. this can also take an options object as an optional second parameter, but we are just using the simplest version for now. we are storing the promise object returned by fetch() inside a variable called promise. as we said before, this object rep...
...And 13 more matches
Fetching data from the server - Learn web development
isplayed on your computer. the trouble with this model is that whenever you want to update any part of the page, for example, to display a new set of products or load a new page, you've got to load the entire page again. this is extremely wasteful and results in a poor user experience, especially as pages get larger and more complex. ...
...erience, especially as pages get larger and more complex. enter ajax this led to the creation of technologies that allow web pages to request small chunks of data (such as html, xml, json, or plain text) and display them only when needed, helping to solve the problem described above. this is achieved by using apis like xmlhttprequest or — more recently — the fetch api. these technologies allow web pages to directly handle making http requests for specific resources available on a server and formatting the resulting data as needed before it is displayed. note: in the early days, this general technique was known as asynchronous javascript and xml (ajax), because it tended to use xmlhttprequest to request xml data. this is normally not the case these days (you'd be more likely to use xm...
...or quite a long time. to begin this example, make a local copy of ajax-start.html and the four text files — verse1.txt, verse2.txt, verse3.txt, and verse4.txt — in a new directory on your computer. in this example, we will load a different verse of the poem (which you may well recognize) via xhr when it's selected in the drop-down menu. just inside the <script> element, add the following code. this stores a reference to the <select> and <pre> elements in constants and defines an onchange event handler function so that when the select's value is changed, its value is passed to an invoked function updatedisplay() as a parameter. const versechoose = document.queryselector('select'); const poemdisplay = document.queryselector('pre'); versechoose.onchange = function() { const...
...And 13 more matches
Object building practice - Learn web development
finished this article you'll be interested in exploring them more. along the way we'll make use of some nifty objects, and show you a couple of nice techniques like bouncing balls off walls, and checking whether they have hit each other (otherwise known as collision detection). getting started to begin with, make local copies of our index.html, style.css, and main.js files. these contain the following, respectively: a very simple html document featuring an <h1> element, a <canvas> element to draw our balls on, and elements to apply our css and javascript to our html. some very simple styles, which mainly serve to style and position the <h1>, and get rid of any scrollbars or margin around the edge of the page (so that it looks nice and neat). some javascript that serves to set up the <c...
...anvas'); const ctx = canvas.getcontext('2d'); const width = canvas.width = window.innerwidth; const height = canvas.height = window.innerheight; this script gets a reference to the <canvas> element, then calls the getcontext() method on it to give us a context on which we can start to draw. the resulting constant (ctx) is the object that directly represents the drawing area of the canvas and allows us to draw 2d shapes on it. next, we set constants called width and height, and the width and height of the canvas element (represented by the canvas.width 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 multip...
...ed by the canvas.width 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 the...
...And 13 more matches
Introduction to client-side frameworks - Learn web development
solutions with others. this shared ecosystem of libraries helped shape the growth of the web. now, javascript is an essential part of the web, used on 95% of all websites, and the web is an essential part of modern life. users write papers, manage their budgets, stream music, watch movies, and communicate with others over great distances instantaneously, with text, audio or video chat. the web allows us to do things that used to be possible only in native applications installed on our computers. these modern, complex, interactive websites are often referred to as web applications. the advent of modern javascript frameworks has made it much easier to build highly dynamic, interactive applications. a framework is a library that offers opinions about how software gets built. these opinions all...
...talled on our computers. these modern, complex, interactive websites are often referred to as web applications. the advent of modern javascript frameworks has made it much easier to build highly dynamic, interactive applications. a framework is a library that offers opinions about how software gets built. these opinions allow for predictability and homogeneity in an application; predictability allows software to scale to an enormous size and still be maintainable; predictability and maintainability are essential for the health and longevity of software. javascript frameworks power much of the impressive software on the modern web – including many of the websites you likely use every day. mdn web docs, which you are currently reading this on, uses the react/reactdom framework to power its ...
...gevity of software. javascript frameworks power much of the impressive software on the modern web – including many of the websites you likely use every day. mdn web docs, which you are currently reading this on, uses the react/reactdom framework to power its front end. what frameworks are out there? there are many frameworks out there, but currently the "big four" are considered to be the following. ember ember was initially released in december 2011 as a continuation of work that started in the sproutcore project. it is an older framework that has less users than more modern alternatives such as react and vue, but it still enjoys a fair amount of popularity due to its stability, community support, and some clever coding principles. start learning ember angular angular is an open-s...
...And 13 more matches
Handling common accessibility problems - Learn web development
t about disabilities. really, the aim of accessibility is to make your websites/apps usable by as many people in as many contexts as possible, not just those users using high-powered desktop computers. some examples might include: users on mobile devices. users on alternative browsing devices such as tvs, watches, etc. users of older devices that might not have the latest browsers. users of lower spec devices that might have slow processors. in a way, this whole module is about accessibility — cross browser testing makes sure that your sites can be used by as many people as possible. what is accessibility? defines accessibility more completely and thoroughly than this article does. that said, this article will cover cross browser and testing issues surrounding people with disabilit...
...ly as sites get more complex. instead, it is more about making a reasonable effort to make as much of your content accessible to as many people as possible via defensive coding and sticking to best practices. common accessibility issues in this section we'll detail some of the main issues that arise around web accessibility, connected with specific technologies, along with best practices to follow, and some quick tests you can do to see if your sites are going in the right direction. note: accessibility is morally the right thing to do, and good for business (numbers of disabled users, users on mobile devices, etc. present significant market segments), but it is also a legal requirement in many parts of the world to make web content accessible to people with disabilities. read accessibil...
...then restart the browser. click the gear icon that will appear, then select css > disable all styles. edge: select view > style > no style from the main menu. using native keyboard accessibility certain html features can be selected using only the keyboard — this is default behavior, available since the early days of the web. the elements that have this capability are the common ones that allow user to interact with web pages, namely links, <button>s, and form elements like <input>. you can try this out using our native-keyboard-accessibility.html example (see the source code) — open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted def...
...And 13 more matches
IME handling guide
pical japanese ime can input two or more words into a composition string. when a user converts from hiragana characters to chinese characters the composition string, japanese ime separates the composition string into multiple clauses. ...
... (in the following screenshots, the composition string has a wavy underline and the only one clause is called "raw input clause"). when a user presses convert key, japanese ime separates the composition string as "わたしの" (my), "なまえは" (name is) and "なかのです" (nakano). then, converts each clause with chinese characters: "私の", "名前は" and "中野です" (in the following screenshot each clause is underlined and not connected adjacently. these clauses are called "converted clause"). if one or more clauses were not converted as expected, the user can choose one of the clauses with arrow keys and look for the expected result form the list in the drop down menu (in the following screenshot, the clause with the thicker underline is called "selected clause"). ...
...represented with selection in the editor. from chrome script, you can check it with nsiselectioncontroller. in native code, you can access it with either nsiselectioncontroller or mozilla::selectiontype (the latter is recommended because of type safer). and editor sets these ime selections from mozilla::textrangetype which are sent by mozilla::widgetcompositionevent as mozilla::textrangearray. following table explains the mapping between them. selection types of each clause of composition string or caret nsiselectioncontroller mozilla::selectiontype mozilla::textrangetype caret selection_normal enormal ecaret raw text typed by the user selection_ime_raw_input eimerawclause erawclause selected clause of raw text typed by the...
...And 13 more matches
IPDL Tutorial
ipdl, short for "inter-process-communication protocol definition language", is a mozilla-specific language allowing c++ code to pass messages between processes or threads in an organized and secure way. all messages for multi-process plugins and tabs in firefox are declared in the ipdl language. to experiment with adding a new ipdl protocol, see creating a new protocol. all ipdl messages are sent between parent and a child end points, called actors. an ipdl protocol declares how actors communicate: it declares the possible messages that may be sent between actors, as well as a state machine describing when messages are allowed to be sent. the parent actor is typically the more permanent side of the conversation: parent/child actors parent child ipc ta...
...ns content process plugin process each protocol is declared in a separate file. the ipdl compiler generates several c++ headers from each ipdl protocol. this generated code manages the details of the underlying communication layer (sockets and pipes), constructing and sending messages, ensuring that all actors adhere to their specifications, and handling many error conditions. the following ipdl code defines a very basic interaction of browser and plugin actors: async protocol pplugin { child: async init(nscstring pluginpath); async shutdown(); parent: async ready(); }; this code declares the pplugin protocol. two messages can be sent from the parent to the child, init() and shutdown(). one message can be sent from the child to the parent, ready(). ipdl protocols start...
...ction specifies whether the message can be sent from-parent-to-child, from-child-to-parent, or both ways. three keywords serve as direction specifiers; child was introduced above. the second is parent, which means that the messages declared under the parent label can only be sent from-child-to-parent. the third is both, which means that the declared messages can be sent in both directions. the following artificial example shows how these specifiers are used and how these specifiers change the generated abstract actor classes. // pdirection.ipdl async protocol pdirection { child: async foo(); // can be sent from-parent-to-child parent: async bar(); // can be sent from-child-to-parent both: async baz(); // can be sent both ways }; // pdirectionparent.h class pdirectionparent { prote...
...And 13 more matches
CustomizableUI.jsm
manage the areas in which these widgets are shown. ...
...with customizable buttons and items in firefox's main window ui. it is available in the firefox window as the customizableui property on the window. if you want to use it from a jsm or another context without a window reference, you need to import it yourself: components.utils.import("resource:///modules/customizableui.jsm"); introduction the module is intended for two primary purposes: allow adding, moving and removing customizable widgets. manage the areas in which these widgets are shown. note that it is expressly not really aware about the specific ui used by users to make customizations. this is handled by customizemode.jsm, which interacts with customizableui through a listener mechanism. areas areas are parts of the user interface in which customizable widgets can be place...
...rea. for each area, customizableui keeps track of a list of the widgets they contain, generally refered to as 'placements'. this is analogous to the old currentset attribute. if consumers make a change to the placements in an area, customizableui will update the actual nodes in each area instance for them. toolbars generally function the same way they always have. however, they can now be 'overflowable', that is, if there are too many widgets to fit in the toolbar's horizontal space, the excess widgets will be placed in a panel accessible from an anchor (chevron) in the toolbar. in order to register such a toolbar, set the 'overflowable' property to true, and provide the id of the anchor in the 'anchor' property. widgets widget is the term that customizableui uses for each of the items in...
...And 13 more matches
QA phase
kip 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. ...
...directories, one per l10n; often referred to as "l10n base")/ your-locale-code (a directory with your l10n files, in this example we'll use x-testing) example: root/mozilla-aurora & root/l10n-central/x-testing additionally, you will need to copy and translate the toolkit/defines.inc file directly from en-us before you can build. this is due to a bug in the build logic. ...
...e")/ your-locale-code (a directory with your l10n files, in this example we'll use x-testing) example: root/mozilla-aurora & root/l10n-central/x-testing additionally, you will need to copy and translate the toolkit/defines.inc file directly from en-us before you can build. 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. ...
...And 13 more matches
Shell global objects
rc/shell/js.cpp (around shell_functions) for more. this page lists variables and functions available on spidermonkey 53. there may be some difference between each versions. you can get the list of functions by help() function in js shell. variables scriptargs an array that contains arguments passed to js shell. scriptpath a string that is a path of script. console an object that has following property: log evaluate and print expressions to stdout. this function is an alias of the print() function. timesaccessed returns a number that indicates how many times this variable is accessed perfmeasurement see perfmeasurement.jsm. shell only functions functions always available version([number]) get or force a script compilation version number. options([option ...]) ...
...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.p...
... warning. clearlastwarning() clear the last warning. elapsed() execution time elapsed for the current thread. decompilefunction(func) decompile a function. decompilethis() decompile the currently executing script. thisfilename() return the filename of the current script newglobal([options]) return a new global object in a new compartment. if options is given, it may have any of the following properties: samezoneas the compartment will be in the same zone as the given object (defaults to a new zone) invisibletodebugger the global will be invisible to the debugger (default false) principal if present, its value converted to a number must be an integer that fits in 32 bits; use that as the new compartment's principal. shell principals are toys, meant only for testing; o...
...And 13 more matches
nsIDOMWindowUtils
of the window. the attribute's value must be one of the animationmode values from imgicontainer. imeisopen boolean returns the ime open state. true if it's open, otherwise false. this attribute only works when imestatus is ime_status_enabled. read only. imestatus unsigned long returns the current ime status. values correspond to the ime_status_* constants defined below. read only. ismozafterpaintpending boolean returns true if a mozafterpaint event has been queued but not yet fired. read only. layermanagertype astring what type of layer manager the widget associated with this window is using. "basic" is unaccelerated; other types are accelerated. throws an error if there is no widget associated with this window. read only. ...
..._momentum 0x0002 used for aoptions of sendwheelevent(). if this is set, the synthesized wheel event emulates momentum scroll event. wheel_event_customized_by_user_prefs 0x0004 used for aoptions of sendwheelevent(). if this is set, the synthesized wheel event emulates an event whose delta values are computed from user prefs in widget level. ...
...his is set, the synthesized wheel event emulates momentum scroll event. wheel_event_customized_by_user_prefs 0x0004 used for aoptions of sendwheelevent(). if this is set, the synthesized wheel event emulates an event whose delta values are computed from user prefs in widget level. ...
...And 13 more matches
nsIWindowMediator
nsisimpleenumerator getenumerator(in wstring awindowtype); nsidomwindow getmostrecentwindow(in wstring awindowtype); nsidomwindow getouterwindowwithid(in unsigned long long aouterwindowid); nsisimpleenumerator getxulwindowenumerator(in wstring awindowtype); pruint32 getzlevel(i...
...dowmediator = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); method overview void addlistener(in nsiwindowmediatorlistener alistener); boolean calculatezposition(in nsixulwindow inwindow, in unsigned long inposition, in nsiwidget inbelow, out unsigned long outposition, out nsiwidget outbelow); native code only! nsisimpleenumerator getenumerator(in wstring awindowtype); nsidomwindow getmostrecentwindow(in wstring awindowtype); nsidomwindow getouterwindowwithid(in unsigned long long aouterwindowid); nsisimpleenumerator getxulwindowenumerator(in wstring awindowtype); pruint32 getzlevel(in nsixulwindow awindow); native code only! nsi...
... zlevelbotto...
...And 13 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
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. 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 lo...
...equencer, 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 parameters particular to each technique we are using to create those voices. the techniques we are using are: name of voice technique associated web audio api feature "sweep" oscillator, periodic wave oscillatornode, periodicwave "pulse" multiple oscillators oscillatornode "noise" random noise buffer, b...
...requency.value = 440; osc.connect(audioctx.destination); osc.start(); osc.stop(audioctx.currenttime + 1); } controlling amplitude this 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 13 more matches
HTML attribute: rel - HTML: Hypertext Markup Language
Web › HTML › Attributes › rel
ttribute defines the relationship between a linked resource and the current document. valid on <link>, <a>, <area>, and <form>, the supported values depend on the element on which the attribute is found. ...
...e space-separated keywords, which are listed in the following table. every keyword within a space seperated value should be unique within that value. values for the rel attribute, and the elements for which each is relevant rel value description <link> <a> and <area> <form> alternate alternate representations of the current document. link link not allowed author author of the current document or article. link link not allowed bookmark permalink for the nearest ancestor section. not allowed link not allowed canonical preferred url for the current document. ...
...<area> <form> alternate alternate representations of the current document. link link not allowed author author of the current document or article. link link not allowed bookmark permalink for the nearest ancestor section. not allowed link not allowed canonical preferred url for the current document. link not allowed not allowed dns-prefetch tells the browser to preemptively perform dns resolution for the target resource's origin external resource not allowed not allowed external referenced document is not part of the same site as the current document. not allowed annotation annotation help link to context-sensitive help. link link link ...
...And 13 more matches
<input type="email"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › email
can be a list of properly-formed comma-separated e-mail addresses. any trailing and leading whitespace is removed from each address in the list. see validation for details on how e-mail addresses are validated to ensure that they're formatted properly. ...
...e 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 readonly a boolean attribute indicating whether or not the contents of the input should be read-only size a number indicating how ...
... input will fail constraint validation if the length of the text entered into the field is fewer than minlength utf-16 code units long. constraint validation is only applied when the value is changed by the user. multiple a boolean attribute which, if present, indicates that the user can enter a list of multiple e-mail addresses, separated by commas and, optionally, whitespace characters. see allowing multiple e-mail addresses for an example, or html attribute: multiple for more details. note: normally, if you specify the required attribute, the user must enter a valid e-mail address for the field to be considered valid. however, if you add the multiple attribute, a list of zero e-mail addresses (an empty string, or one which is entirely whitespace) is a valid value. in other words, the ...
...And 13 more matches
<input type="search"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › search
eve this using the htmlinputelement.value property in javascript. searchterms = mysearch.value; if no validation constraints are in place for the input (see validation for more details), the value can be any text string or an empty string (""). ...
...ower or wider than the specified number of characters, depending on the characters and the font (font settings in use). this does not set a limit on how many characters the user can enter into the field. it only specifies approximately how many can be seen at a time. to set an upper limit on the length of the input data, use the maxlength attribute. ...
...roximately how many can be seen at a time. to set an upper limit on the length of the input data, use the maxlength attribute. spellcheck non-standard attributes the following non-standard attributes are available to search input fields. as a general rule, you should avoid using them unless it can't be helped. attribute description autocorrect whether or not to allow autocorrect while editing this input field. safari only. incremental whether or not to send repeated search events to allow updating live search results while the user is still editing the value of the field. webkit and blink only (safari, chrome, opera, etc.). mozactionhint a string indicating the type of action that will be taken when the user presses the enter or return...
...And 13 more matches
Using the application cache - HTML: Hypertext Markup Language
to use service workers instead (bug 1204581). introduction html5 provides an application caching mechanism that lets web applications run offline. this application cache (appcache) interface lists resources that browsers should cache to be available offline. applications that are cached load and work correctly offline, even if users press the refresh button. an application cache gives the following benefits: offline browsing users can navigate a site even when they are offline. speed cached resources are local, and therefore load faster. reduced server load the browser only downloads resources that have changed from the server. how the application cache works enabling the application cache to enable the application cache for an application, include the manifest attribute in t...
..., the browser implicitly adds every page that the user visits and that has the manifest attribute set to the application cache. some browsers (e.g., firefox) display a notification bar the first time a user loads an application that uses the application cache. the notification bar displays a message such as: this website (example.com) is asking to store data on your computer for offline use. [allow] [never for this site] [not now] the term "offline(-enabled) applications" sometimes refers specifically to applications that the user has allowed to use offline capabilities. loading documents the use of an application cache modifies the normal process of loading a document: if an application cache exists, the browser loads the document and its associated resources directly from the cache,...
...e browser then checks to see if the cache manifest has been updated on the server. if the cache manifest has been updated, the browser downloads a new version of the manifest and the resources listed in the manifest. this is done in the background and does not affect performance significantly. the process for loading documents and updating the application cache is specified in greater detail below: when the browser visits a document that includes the manifest attribute, if no application cache exists, the browser loads the document and then fetches all the entries listed in the manifest file, creating the first version of the application cache. subsequent visits to that document cause the browser to load the document and other assets specified in the manifest file from the application ...
...And 13 more matches
async function - JavaScript
nc function's body, you will get a syntaxerror. the purpose of async/await is to simplify the syntax necessary to consume promise-based apis. the behavior of async/await is similar to combining generators and promises. async functions always return a promise. if the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. for example, the following: async function foo() { return 1 } ...is equivalent to: function foo() { return promise.resolve(1) } the body of an async function can be thought of as being split by zero or more await expressions. top-level code, up to and including the first await expression (if there is one), is run synchronously. in this way, an async function without an await expression will run synchronously...
.... for example: async function foo() { await 1 } ...is equivalent to: function foo() { return promise.resolve(1).then(() => undefined) } code after each await expression can be thought of as existing in a .then callback. in this way a promise chain is progressively constructed with each reentrant step through the function. the return value forms the final link in the chain. in the following example, we successively await two promises. progress moves through function foo in three stages. the first line of the body of function foo is executed synchronously, with the await expression configured with the pending promise. progress through foo is then suspended and control is yielded back to the function that called foo. some time later, when the first promise has either been fulfi...
...esult2 = 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((resolve) => settimeout(() => resolve('1'), 1000)) const p2 = new promise((_,reject) => settimeout(() => reject('2...
...And 13 more matches
jpm - Archive of obsolete content
jpm is a command-line tool that enables you to test, run, and package add-ons. this is the reference page for jpm. see also jpm tutorial for getting started. jpm usage is: jpm [command] [options] jpm supports the following global options: -h, --help - show a help message and exit -v, --version - print the jpm version number --addon-dir - directory for your source code, defaulting to the current directory installation jpm is distributed with the node package manager npm. 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 nod...
...nding 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. ...
...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. someone else may have had the same problem you do, so try searching the list. you are welcome to post a question, too. you can also chat with other sdk users in #jetpack on mozilla's irc network. command reference jpm supports the following commands: jpm init create a skeleton add-on as a starting point for your add-on. jpm run launch an instance of firefox with your add-on installed. jpm test runs your add-on's unit tests. jpm xpi package your add-on as an xpi file, which is the install file format for firefox add-ons. jpm post package your add-on as an xpi file, and t...
...And 12 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
ational 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 user interfaces behave similarly to non-web based applications such as contact management software. the basic implementation uses a resource such as the web page or the web application to control the navigation system. in other words, the page is the browsing device during the experience, and the user is "immersed" in that browsing device. what does this mean, practically speakin...
... does it look like? good candidates for inner-browsing include a spell check application, in which the text entered in a web page is checked as it is typed; a webmail application that uses the inner-browsing model to display the separate messages and message lists in an integrated way, much like a client mail app; and a stock ticker that spools the information across the web page. see the table below for a description of how applications like this exemplify inner-browsing and how they might be implemented using the inner-browsing approach. some examples: web page with ticker it is common to see web pages with a ticker element, often used to rotate news or stock quotes updates. a simple ticker element implemented in dhtml statically includes the data in the page. if the data changes, it will n...
...if the data changes, it will not update unless you reload the web page. this article includes a ticker example demonstrating that the inner-browsing model can be used to dynamically request new data from the server side and provide updates to the ticker. spell check suppose you have a web publishing system for a portal, and a spell check application on your server. today, this publishing system allows your users to modify content for the portal, but in order to have their text spell checked they must click somewhere and wait for the response page. the inner-browsing model is able to provide users with automatic spell check without leaving the page being edited, a similar experience to a word processor application. the incorrect words are highlighted while the user is typing. forms with nested...
...And 12 more matches
jspage - Archive of obsolete content
var mootools={version:"1.2.4",build:"0d9113241a90b9cd5643b926795852a2026710d4"};var native=function(k){k=k||{};var a=k.name;var i=k.legacy;var b=k.protect; var c=k.implement;var h=k.generics;var f=k.initialize;var g=k.afterimplement||function(){};var d=f||i;h=h!==false;d.constructor=native;d.$family={name:"native"}; if(i&&f){d.prototype=i.prototype;}d.prototype.constructor=d;if(a){var e=a.tolowercase();d.prototype.$family={name:e};native.typize(d,e);}var j=function(n,l,o,m){if(!b||m||!n.prototype[l]){n.prototype[l]=o; }if(h){native.genericize(n,l,b);}g.call(n,l,o);return n;};d.alias=function(n,l,p){if(typeof n=="string"){var o=this.prototype[n];if((n=o)){return j(this,l,n,p); }}for(var m in n){this.alias(m,n[m],l);}return this;};d.implement=function(m,l,o){if(typeof m=="string"){return ...
...,initialize:a[h],protect:true}); }var d={"boolean":boolean,"native":native,object:object};for(var c in d){native.typize(d[c],c);}var f={array:["concat","indexof","join","lastindexof","pop","push","reverse","shift","slice","sort","splice","tostring","unshift","valueof"],string:["charat","charcodeat","concat","indexof","lastindexof","match","replace","search","slice","split","substr","substring","tolowercase","touppercase","valueof"]}; for(var e in f){for(var b=f[e].length;b--;){native.genericize(a[e],f[e][b],true);}}})();var hash=new native({name:"hash",initialize:function(a){if($type(a)=="hash"){a=$unlink(a.getclean()); }for(var b in a){this[b]=a[b];}return this;}});hash.implement({foreach:function(b,c){for(var a in this){if(this.hasownproperty(a)){b.call(c,this[a],a,this); }}},getclean:funct...
...n $unlink(c){var b;switch($type(c)){case"object":b={};for(var e in c){b[e]=$unlink(c[e]); }break;case"hash":b=new hash(c);break;case"array":b=[];for(var d=0,a=c.length;d<a;d++){b[d]=$unlink(c[d]);}break;default:return c;}return b;}var browser=$merge({engine:{name:"unknown",version:0},platform:{name:(window.orientation!=undefined)?"ipod":(navigator.platform.match(/mac|win|linux/i)||["other"])[0].tolowercase()},features:{xpath:!!(document.evaluate),air:!!(window.runtime),query:!!(document.queryselector)},plugins:{},engines:{presto:function(){return(!window.opera)?false:((arguments.callee.caller)?960:((document.getelementsbyclassname)?950:925)); },trident:function(){return(!window.activexobject)?false:((window.xmlhttprequest)?((document.queryselectorall)?6:5):4);},webkit:function(){return(naviga...
...And 12 more matches
XUL accessibility guidelines - Archive of obsolete content
accessibility is not difficult, but does require a basic understanding of the different types of disabilities, commonly used assistive technologies, and special accessibility features built into the xul languages. most of all, accessibility requires a conscious effort on your part, and a desire to include everyone. ...
...ible operations. the column picker and column headers in xul trees are not keyboard accessible, consistent with the standard tree behavior on most contemporary operating systems. it is therefore necessary to provide a keyboard accessible alternative for accessing this functionality. the firefox "bookmarks manager" provides an example of how to make trees more accessible. the bookmark manager allows users to sort bookmarks by a particular column of information and choose which columns to display. because column headers and the column picker, in the upper right hand corner of the tree, can not receive focus, they are not operable with a keyboard. in the bookmark manager this functionality is available under the view menu which is accessible to a keyboard user. toolbarbuttons by default, to...
... keyboard access. there are many ways to provide keyboard shortcuts. they are well documented in the xul tutorial:keyboard shortcuts. careful attention should be taken when setting keyboard shortcuts. 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...
...And 12 more matches
Building up a basic demo with the PlayCanvas engine - Game development
nd one. there is one helper variable already included, which will store a reference to the <canvas> element. before reading on, copy this code to a new text file and save it in your working directory as index.html. playcanvas application to begin developing our game we have to create the playcanvas application first (using the given <canvas> element), and then start the update loop. add the following code to the bottom of your second <script> element: var app = new pc.application(canvas); app.start(); the pc global object contains all the playcanvas functions available in the engine. next, we'll set the canvas to fill the window, and automatically change its resolution to be the same as the canvas size. again, add the following lines at the bottom of your script. app.setcanvasfillmode...
... var camera = new pc.entity(); camera.addcomponent("camera", { clearcolor: new pc.color(0.8, 0.8, 0.8) }); app.root.addchild(camera); camera.setposition(0, 0, 7); the code above will create a new entity. ...
...object used in the scene — it can be an object like a box, cylinder or cone, but it can also be a camera, light or sound source. then it adds a camera component to it with the light gray clearcolor — the color will be visible as the background. next, the camera object is added to the root of our application and positioned to be 7 units away from the center of the scene on the z axis. this allows us to make some space to visualize the objects that we will create later on. note: the distance values (e.g. for the camera z position) are unitless, and can basically be anything you deem suitable for your scene — milimeters, meters, feet, or miles — it's up to you. try saving the file and loading it in your browser. you should now see a gray window. congratulations! geometry now the ...
...And 12 more matches
Building up a basic demo with Three.js - Game development
l renderer, setting its size to fit the whole available space on the screen, and appending the dom structure to the page. you might have noticed the antialias parameter in the first line — this renders the edges of shapes more smoothly. the setclearcolor() method sets our background to a light gray colour, instead of the default black one. ...
...ground to a light gray colour, instead of the default black one. add this code into our second <script> element, just below the javascript comment. scene a scene is the place where everything happens. when creating new objects in the demo, we add them all inside the scene to become visible on the screen. in three.js, the scene is represented by a scene object. let's create it, by adding the following line below our previous lines: var scene = new three.scene(); later, we will be using the .add() method, to add objects to this scene. camera we have the rendered scene, but we still need to add a camera to view our handiwork — imagine a movie set without any cameras. ...
...ble on the screen. in three.js, the scene is represented by a scene object. let's create it, by adding the following line below our previous lines: var scene = new three.scene(); later, we will be using the .add() method, to add objects to this scene. camera we have the rendered scene, but we still need to add a camera to view our handiwork — imagine a movie set without any cameras. the following lines put the camera in place in the 3d coordinate system, and point it in the direction of our scene, so we can finally see something: var camera = new three.perspectivecamera(70, width/height); camera.position.z = 50; scene.add(camera); add the above lines to your code, below those previously added. there are other types of camera available (cube, orthographic), but the simplest is persp...
...And 12 more matches
CSS and JavaScript accessibility best practices - Learn web development
or they can significantly harm accessibility if misused. this article outlines some css and javascript best practices that should be considered to ensure even complex content is as accessible as possible. prerequisites: basic computer literacy, a basic understanding of html, css, and javascript, and understanding of what accessibility is. objective: to gain familiarity with using css and javascript appropriately in your web documents to maximise accessibility and not detract from it. ...
...igate a page via heading elements if the developer hasn't appropriately used heading elements to markup the content. by the same token, a heading loses its visual purpose if you style it so it doesn't look like a heading. the rule of thumb is that you can update the styling of a page feature to fit in your design, but don't change it so much that it no longer looks or behaves as expected. the following sections summarize the main html features to consider. "standard" text content structure headings, paragraphs, lists — the core text content of your page: <h1>heading</h1> <p>paragraph</p> <ul> <li>my list</li> <li>has two items.</li> </ul> some typical css might look like this: h1 { font-size: 5rem; } p, li { line-height: 1.5; font-size: 1.6rem; } you should: select se...
...</strong>.</p> you might want to add some simple coloring to your emphasised text: strong, em { color: #a60000; } you will however rarely need to style emphasis elements in any significant way. the standard conventions of bold and italic text are very recognisable, and changing the style can cause confusion. for more on emphasis, see emphasis and importance. abbreviations an element that allows an abbreviation, acronym, or initialization to be associated with its expansion: <p>web content is marked up using <abbr title="hypertext markup language">html</abbr>.</p> again, you might want to style it in some simple way: abbr { color: #a60000; } the recognised styling convention for abbreviations is a dotted underline, and it is unwise to significantly deviate from this. for more on a...
...And 12 more matches
Styling tables - Learn web development
r table let's work through styling our table example together. to start with, make a local copy of the sample markup, download both images (noise and leopardskin), and put the three resulting files in a working directory somewhere on your local computer. next, create a new file called style.css and save it in the same directory as your other files. ...
... computer. next, create a new file called style.css and save it in the same directory as your other files. ...
...normally, table columns tend to be sized according to how much content they contain, which produces some strange results. ...
...And 12 more matches
JavaScript basics - Learn web development
e 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 providers, such as twitter or facebook. third-party frameworks and libraries that you can apply to html to accelerate the work of building sites and applications. it's outside the scope of this article—as a light introduction to javascript—to present the details of how the core javascript language is different from the too...
...y frameworks and libraries that you can apply to html to accelerate the work of building sites and applications. it's outside the scope of this article—as a light introduction to javascript—to present the details of how the core javascript language is different from the tools listed above. you can learn more in mdn's javascript learning area, as well as in other parts of mdn. the section below introduces some aspects of the core language, and offers an opportunity to play with a few browser api features too. have fun! a hello world! example javascript is one of the most popular modern web technologies! as your javascript skills grow, your websites will enter a new dimension of power and creativity. however, getting comfortable with javascript is more challenging than getting comfort...
...dimension of power and creativity. however, getting comfortable with javascript is more challenging than getting comfortable with html and css. you may have to start small, and progress gradually. to begin, let's examine how to add javascript to your page for creating a hello world! example. (hello world! is the standard for introductory programming examples.) important: if you haven't been following along with the rest of our course, download this example code and use it as a starting point. go to your test site and create a new folder named scripts. within the scripts folder, create a new file called main.js, and save it. in your index.html file, enter this code on a new line, just before the closing </body> tag: <script src="scripts/main.js"></script> this is doing the same jo...
...And 12 more matches
HTML text fundamentals - Learn web development
ad 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 lead to weird results. of the six heading levels available, you should aim to use no more than three per page, unless you feel it is necessary. documents with many ...
...ngs, your page will perform poorly in terms of seo (search engine optimization). severely visually impaired people often don't read web pages; they listen to them instead. this is done with software called a screen reader. this software provides ways to get fast access to given text content. among the various techniques used, they provide an outline of the document by reading out the headings, allowing their users to find the information they need quickly. if headings are not available, they will be forced to listen to the whole document read out loud. to style content with css, or make it do interesting things with javascript, you need to have elements wrapping the relevant content, so css/javascript can effectively target it. we therefore need to give our content structural markup. act...
...rced to listen to the whole document read out loud. to style content with css, or make it do interesting things with javascript, you need to have elements wrapping the relevant content, so css/javascript can effectively target it. we therefore need to give our content structural markup. active learning: giving our content structure 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"...
...And 12 more matches
Looping code - Learn web development
s being associated with popular breakfast cereals, roller coasters, and musical production, they are also a critical concept in programming. programming loops are all to do with doing the same thing over and over again — which is termed iteration in programming speak. let'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 "h...
...but we could think about the farmer being able to collect say 2 portions of food per hour. after each hour, the amount of food he has collected is incremented by two, and he checks whether he has enough food. if he has reached 10 portions (the point where the condition is no longer true, so the loop exits), he can stop collecting and go home. in pseudocode, this would look something like the following: loop(food = 0; foodneeded = 10) { if (food >= foodneeded) { exit loop; // we have enough food; let's go home } else { food += 2; // spend an hour collecting 2 more food // loop will then run again } } so the amount of food needed is set at 10, and the amount the farmer currently has is set at 0. in each iteration of the loop, we check whether the amount of food the far...
...the width and height of the inner browser window. you should get the basic idea — we are using a loop to run 100 iterations of this code, each one of which draws a circle in a random position on the page. the amount of code needed would be the same whether we were drawing 100 circles, 1000, or 10,000. only one number has to change. if we weren't using a loop here, we'd have to repeat the following code for every circle we wanted to draw: ctx.beginpath(); ctx.fillstyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); ctx.fill(); this would get very boring and difficult to maintain very quickly. loops really are the best. the standard for loop let's start exploring some specific loop constructs. the first, which you'll use most of the time, is...
...And 12 more matches
Manipulating documents - Learn web development
centering around security. imagine if a web site could get access to your stored passwords or other sensitive information, and log into websites as if it were you? despite the limitations, web apis still give us access to a lot of functionality that enable us to do a great many things with web pages. there are a few really obvious bits you'll reference regularly in your code — consider the following diagram, which represents the main parts of a browser directly involved in viewing web pages: the window is the browser tab that a web page is loaded into; this is represented in javascript by the window object. using methods available on this object you can do things like return the window's size (see window.innerwidth and window.innerheight), manipulate the document loaded into that win...
...l node (other markup vocabularies like svg and custom xml will have different root elements). child node: a node directly inside another node. for example, img is a child of section in the above example. descendant node: a node anywhere inside another node. for example, img is a child of section in the above example, and it is also a descendant. img is not a child of body, as it is two levels 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 terminol...
...tion 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 along with it. add a <script></script> element just above the closing </body> tag. to manipulate an element inside the dom, you first need to select it and store a reference to it inside a variable. inside your script element, add the following line: const link = document.queryselector('a'); now we have the element reference stored in a variable, we can start to manipulate it using properties and methods available to it (these are defined on interfaces like htmlanchorelement in the case of <a> element, its more general parent interface htmlelement, and node — which represents all nodes in a dom). first of all, let's change the...
...And 12 more matches
What went wrong? Troubleshooting JavaScript - Learn web development
have your own version of the game example that doesn't work, which you might want to fix! we'd still like you to work through the article with our version, so that you can learn the techniques we are teaching here. then you can go back and try to fix your example. at this point, let's consult the developer console to see if it reports any syntax errors, then try to fix them. you'll learn how below. fixing syntax errors earlier on in the course we got you to type some simple javascript commands into the developer tools javascript console (if you can't remember how to open this in your browser, follow the previous link to find out how). what's even more useful is that the console gives you error messages whenever a syntax error exists inside the javascript being fed into the browser's java...
...from left to right, we've got: a red "x" to indicate that this is an error. ...
...ght, we've got: a red "x" to indicate that this is an error. an error message to indicate what's gone wrong: "typeerror: guesssubmit.addeventlistener is not a function" a "learn more" link that links through to an mdn page that explains what this error means in greater detail. the name of the javascript file, which links through to the debugger tab of the developer tools. if you follow this link, you'll see the exact line where the error is highlighted. the line number where the error is, and the character number in that line where the error is first seen. in this case, we've got line 86, character number 3. if we look at line 86 in our code editor, we'll find this line: guesssubmit.addeventlistener('click', checkguess); the error message says "guesssubmit.addeven...
...And 12 more matches
Getting started with Ember - Learn web development
ue, and angular. the service side provides long-lived shared state, behavior, and an interface to integrating with other libraries or systems. for example, the router (which will be mentioned later in this tutorial) is a service. components and services make up the majority of any emberjs application. use cases generally, emberjs works well for building apps that desire either or both of the following traits: single page applications, including native-like web apps, and progressive web apps (pwas) ember works best when it is the entire front end of your application. increasing cohesion among many team's technology stacks community-backed "best practices" allow for faster long-term development speed. ember has clear conventions that are useful for enforcing consist...
...ations 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 loosely based on handlebars. the templating language is used to make build and runtime optimizations that otherwise wouldn't be possible. most importantly, it is a superset of html — meaning that anyone who know...
...mplates without any knowledge of javascript, and interactivity can be added later. this language also enables lighter asset payloads due to compiling the templates into a "byte code" that can be parsed faster than javascript. the glimmer vm enables extremely fast dom change tracking without the need to manage and diff a cached virtual representation (which is a common approach to mitigating the slow i/o of dom changes). for more information on the technical aspects of the glimmer vm, the github repository has some documentation — specifically, references and validators may be of interest. everything else in ember is just javascript. in particular, javascript classes. this is where most of the "framework" parts come into play, as there are superclasses, where each type of thing has a diff...
...And 12 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
previous overview: client-side javascript frameworks next now that we have our markup and styles ready we can start developing the required features for our svelte to-do list app. 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...
...making it a bit more dynamic. we'll take the tasks information from the markup and store it in a todos array. we'll also create two variables to keep track of the total number of tasks and the completed tasks. the state of our component will be represented by these three top-level variables. ...
...item. also, a key expression can be provided, which will uniquely identify each item. svelte will use it to diff the list when data changes, rather than adding or removing items at the end, and it's a good practice to always specify one. finally, an :else block can be provided, which will be rendered when the list is empty. let's give it a try. replace the existing <ul> element with the following simplified version to get an idea of how it works: <ul> {#each todos as todo, index (todo.id)} <li> <input type="checkbox" checked={todo.completed}/> {index}. {todo.name} (id: {todo.id}) </li> {:else} nothing to do here! {/each} </ul> go back to the app; you'll see something like this: now we've seen that this is working, let's generate a complete todo item with ea...
...And 12 more matches
Package management basics - Learn web development
the form of a package registry. the registry is a central place that a package is published to and thus can be installed from. npm, as well as being a package manager, is also the name of the most commonly-used package registry for javascript packages. the npm registry exists at npmjs.com. npm is not the only option. you could manage your own package registry — products like microsoft azure allow you to create proxies to the npm registry (so you can override or lock certain packages), github also offers a package registry service, and there will be likely more options appearing as time goes on. what is important is that you ensure you've chosen the best registry for you. many projects will use npm, and we’ll stick to this in our examples throughout the rest of the module. using the pa...
...xperimental app. setting up the app as an npm package first of all, create a new directory to store our experimental app in, somewhere sensible that you’ll find again. ...
...all it whatever you like: mkdir parcel-experiment cd parcel-experiment next, let's initialise our app as an npm package, which creates a config file — package.json — that allows us to save our configuration details in case we want to recreate this environment later on, or even publish the package to the npm registry (although this is somewhat beyond the scope of this article). type the following command, making sure you are inside the parcel-experiment directory: npm init you will now be asked some questions; npm will then create a default package.json file based on the answers: name: a name to identify the app. just press return to accept the default parcel-experiment. version: the starting version number for the app: again, just press return to accept the default 1.0.0. descr...
...And 12 more matches
Introduction to Layout in Mozilla
overview basic data flow key data structures detailed walk-through incrementalism future tech-talks wrap-up, q&a basic data flow source document arrives via network apis incrementally “pumped” through the single-threaded layout engine parse, compute style, render; repeat css used for rendering all content content theoretically separate from “presentation” key data structures content node elements, attributes, leaves dom frame rectangular formatting primitive geometric information [0..n] per content node 2nd thru nth are “continuations” style context non-geometric information may be shared by adjacent frames reference counted, owned by frame ...
...t model, and one or more presentations exposed programmatically via dom apis the presentation owns the frame hierarchy frames own the style contexts, views, widgets presentation has media type, dimensions, etc. ...
...tyle resolution compute stylistic information based on the style rules that apply for the frame’s content node style data broken into different structures display, visibility, font, color, background, … inherit vs. ...
...And 12 more matches
source-editor.jsm
changes, the "dirtychanged" event is sent. editorelement element the element containing the editor. when using the default orion editor, this is a xul <xul:iframe> element. read only. lastfind object an object describing the result of the last find operation performed using the find(), findnext(), or findprevious() method. read only. this object has the following properties: property type description str string the last string that was searched for. index number an integer value indicating the result of the most recent find operation; this is the index into the text at which str was found, or -1 if the string wasn't found. ...
...tring that was searched for. index number an integer value indicating the result of the most recent find operation; this is the index into the text at which str was found, or -1 if the string wasn't found. lastfound number the index of the previous location at which str was found, for multiple find operations (such as find() followed by findnext()). this can be -1 if the string was never found. ignorecase boolean true if the search was case sensitive; otherwise false. readonly boolean set this value to true to make the editor read only, thereby preventing the user from making changes. set it to false to allow editing. constants preference name c...
...the search string. aoptions optional an optional object containing properties customizing the search operation. see find options for details. return value returns an integer indicating the offset into the text at which the first character of the found string is located, or -1 if the string wasn't found. find options the aoptions object can customize the search operation. it may have the following properties: property type description backwards boolean if true, the search begins at start (or the end of the text, if start is not specified) and progresses toward the beginning of the text. otherwise the search progresses forward. the default is false. ignorecase boolean if true, the search is performed in a case-insensitive manner; otherwise ca...
...And 12 more matches
Application Translation with Mercurial
and that the translated texts fit into the available, the translation progress should be tracked. this can be done in a text editor or word processor or any other tool in which you can attach different kind of states to the individual texts to translate. the firefox extension scrapbook is used in this guide. install it into your default firefox profile (you will have more than one profile when following this guide). getting the current texts in english and your locale obtaining the english texts with the source code get the source code by downloading the following file: firefox desktop or firefox for android: download the mozilla-<branch>.hg file (e.g. mozilla-aurora.hg) from https://ftp.mozilla.org/pub/mozilla.org/firefox/bundles/ the file is not small, but after initially downloading ...
...y repacks of the application (changing the localization of the program), and compiling the application likely won't work. you are now in the mozilla development environment which emulates a linux environment. now go to the directory where you want to put the source code. it's highly recommended to put it onto the fastest hard drive in the device. file paths here work starting with a slash (/) followed by the drive letter, and then the directory structure like on windows, but using slashes (/) instead of backslashes (\). so let's go to c:\mozilla by typing cd /c/mozilla/ create a new directory for the source code: mkdir mozilla-aurora initialize the new directory as new repository: hg init mozilla-aurora go into the new directory: cd mozilla-aurora unpack the source code: hg unb...
... hg update obtaining the texts of your localization go back to the parent folder of mozilla-aurora: cd .. find the localization repository for your branch and language on http://hg.mozilla.org/ e.g. for aurora and german (language code 'de'), it is http://hg.mozilla.org/releases/l10n/mozilla-aurora/de/ copy that url to the clipboard. copy the repository to your computer by running the following command: hg clone http://hg.mozilla.org/releases/l10n/mozilla-aurora/de/ de-mozilla-aurora this should proceed pretty fast. on windows, you can paste the url by calling the paste command from the window menu in the upper left corner of the window. configuring your mercurial user settings still in the command prompt, go to your home directory in the file system, e.g. for a windows user...
...And 12 more matches
Profiling with the Firefox Profiler
/. in addition to profiler.firefox.com, the firefox devtools have a simplified interface targeted towards web developers, but does not include as much information as the firefox profiler web app. it is available from the menu at tools > web developer > performance. understanding profiles the firefox profiler has more current documentation available at profiler.firefox.com/docs/. however the following could have some potentially useful information for gecko-specific problems. you can check out some frequently asked questions about the firefox profilers. reporting a performance problem has a step-by-step guide for obtaining a profile when requested by firefox developers. interface 1. timeline the timeline has several rows of tracing markers (colored segments) which indicate interesti...
... gecko-specific problems. you can check out some frequently asked questions about the firefox profilers. reporting a performance problem has a step-by-step guide for obtaining a profile when requested by firefox developers. interface 1. timeline the timeline has several rows of tracing markers (colored segments) which indicate interesting events. hover over them to see more information. below the tracing markers are rows corresponding with activity on a variety of threads. tip: threads that are annotated with "[default]" are in the parent (aka "ui", aka "browser chrome", aka "main") process and those annotated with "[tab]" are in the web content (aka "child") processes. tip: long-running tasks in the parent process will block all input or drawing with the browser ui (aka "ui jank...
...re annotated with "[default]" are in the parent (aka "ui", aka "browser chrome", aka "main") process and those annotated with "[tab]" are in the web content (aka "child") processes. tip: long-running tasks in the parent process will block all input or drawing with the browser ui (aka "ui jank") whereas long-running tasks in the content process will block interactivity with the page but still allowing the user to pan and zoom around thanks to apz. tracing markers red: these indicate that the event loop is being unresponsive. note that high priority events such as vsync are not included here. also note that this indicates what would have happened had there been an event waiting and not necessarily that there was an event pending for that long. black: these indicate synchronous ipc call...
...And 12 more matches
NSS PKCS11 Functions
d_closeuserdb pk11_findcertfromnickname pk11_findkeybyanycert pk11_getslotname pk11_gettokenname pk11_ishw pk11_ispresent pk11_isreadonly pk11_setpasswordfunc secmod_loadusermodule load a new pkcs #11 module based on a modulespec. syntax #include "secmod.h" extern secmodmodule *secmod_loadusermodule(char *modulespec, secmodmodule *parent, prbool recurse); parameters this function has the following parameters: modulespec is a pkcs #11 modulespec. parent is the moduledb that presented this module spec. for applications this value should be null. recurse is a boolean indicates whether or not the module should also launch additional pkcs #11 modules. this is only applicable if the loaded module is actually a moduledb rather than a pkcs #11 module (see pkcs11_module_specs). returns the func...
... available at pkcs11_module_specs. nss parameters may be specified in module specs used by secmod_loadusermodule. module will continue to function in the nss infrastructure until unloaded with secmod_unloadusermodule. secmod_unloadusermodule unload a pkcs #11 module. syntax #include "secmod.h" extern secstatus secmod_unloadusermodule(secmodmodule *module); parameters this function has the following parameters: module is the module to be unloaded. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. description secmod_unloadusermodule detaches a module from the nss trust domain and unloads it. the module should have previously been loaded by secmod_loadusermodule. secmod_closeuserdb close an already opened user database. note: the dat...
...ermodule. secmod_closeuserdb close an already opened user database. note: the database must be in the internal token, and must be one created with secmod_openuserdb(). once the database is closed, the slot will remain as an empty slot until it's used again with secmod_openuserdb(). syntax #include <pk11pub.h> secstatus secmod_closeuserdb(pk11slotinfo *slot) parameters this function has the following parameter: slot a pointer to a slot info structure. this slot must a a slot created by secmod_openuserdb() at some point in the past. returns the function returns one of these values: if successful, secsuccess). if unsuccessful, secfailure. secmod_openuserdb open a new database using the softoken. syntax #include "pk11pub.h" pk11slotinfo *secmod_openuserdb(const char *modulespec) paramet...
...And 12 more matches
Debugger - Firefox Developer Tools
the debugger object when called as a constructor, the debugger object creates a new debugger instance. new debugger([global, …]) create a debugger object, and apply its adddebuggee method to each of the givenglobal objects to add them as the initial debuggees. accessor properties of the debugger prototype object a debugger instance inherits the following accessor properties from its prototype: enabled a boolean value indicating whether this debugger instance’s handlers, breakpoints, and the like are currently enabled. it is an accessor property with a getter and setter: assigning to it enables or disables this debugger instance; reading it produces true if the instance is enabled, or false otherwise. this property is initially true in a freshly created debugger insta...
...igning to it enables or disables this debugger instance; reading it produces true if the instance is enabled, or false otherwise. this property is initially true in a freshly created debugger instance. this property gives debugger code a single point of control for disentangling itself from the debuggee, regardless of what sort of events or handlers or “points” we add to the interface. allowunobservedasmjs a boolean value indicating whether asm.js code running inside this debugger instance’s debuggee globals is invisible to debugger api handlers and breakpoints. setting this to false inhibits the ahead-of-time asm.js compiler and forces asm.js code to run as normal javascript. this is an accessor property with a getter and setter. it is initially false in a freshly created debug...
...to false inhibits the ahead-of-time asm.js compiler and forces asm.js code to run as normal javascript. this is an accessor property with a getter and setter. it is initially false in a freshly created debugger instance. setting this flag to true is intended for uses of subsystems of the debugger api (e.g, debugger.source) for purposes other than step debugging a target javascript program. allowwasmbinarysource a boolean value indicating whether webassembly sources will be available in binary form. the webassembly text generation will be disabled. collectcoverageinfo a boolean value indicating whether code coverage should be enabled inside each debuggee of this debugger instance. changing this flag value will recompile all jit code to add or remove code coverage instrumentation. cha...
...And 12 more matches
Applying styles and colors - Web APIs
to black (css color value #000000). note: when you set the strokestyle and/or fillstyle property, the new value becomes the default for all shapes being drawn from then on. for every shape you want in a different color, you will need to reassign the fillstyle or strokestyle property. the valid strings you can enter should, according to the specification, be css <color> values. each of the following examples describe the same color. // these all set the fillstyle to 'orange' ctx.fillstyle = 'orange'; ctx.fillstyle = '#ffa500'; ctx.fillstyle = 'rgb(255, 165, 0)'; ctx.fillstyle = 'rgba(255, 165, 0, 1)'; a fillstyle example in this example, we once again use two for loops to draw a grid of rectangles, each in a different color. the resulting image should look something like the screensh...
...t) to 1.0 (fully opaque). this value is 1.0 (fully opaque) by default. the globalalpha property can be useful if you want to draw a lot of shapes on the canvas with similar transparency, but otherwise it's generally more useful to set the transparency on individual shapes when setting their colors. because the strokestyle and fillstyle properties accept css rgba color values, we can use the following notation to assign a transparent color to them. // assigning transparent colors to stroke and fill style ctx.strokestyle = 'rgba(255, 0, 0, 0.5)'; ctx.fillstyle = 'rgba(255, 0, 0, 0.5)'; the rgba() function is similar to the rgb() function but it has one extra parameter. the last parameter sets the transparency value of this particular color. the valid range is again between 0.0 (fully tra...
... linewidth = value sets the width of lines drawn in the future. linecap = type sets the appearance of the ends of lines. linejoin = type sets the appearance of the "corners" where lines meet. miterlimit = value establishes a limit on the miter when two lines join at a sharp angle, to let you control how thick the junction becomes. getlinedash() returns the current li...
...And 12 more matches
Using Service Workers - Web APIs
ll provide a terrible user experience if you can’t download it. there have been various attempts to create technologies to solve this problem, and some of the issues have been solved. but the overriding problem is that there still isn’t a good overall control mechanism for asset caching and custom network requests. the previous attempt — appcache — seemed to be a good idea because it allowed you to specify assets to cache really easily. however, it made many assumptions about what you were trying to do and then broke horribly when your app didn’t follow those assumptions exactly. read jake archibald's (unfortunately-titled but well-written) application cache is a douchebag for more details. note: as of firefox 44, when appcache is used to provide offline support for a page a wa...
...used to provide offline support for a page a warning message is now displayed in the console advising developers to use service workers instead (bug 1204581.) service workers should finally fix these issues. service worker syntax is more complex than that of appcache, but the trade off is that you can use javascript to control your appcache-implied behaviors with a fine degree of granularity, allowing you to handle this problem and many more. using a service worker you can easily set an app up to use cached assets first, thus providing a default experience even when offline, before then getting more data from the network (commonly known as offline first). this is already available with native apps, which is one of the main reasons native apps are often chosen over web apps. setting up to p...
...nable service workers; restart browser. you’ll also need to serve your code via https — service workers are restricted to running across https for security reasons. github is therefore a good place to host experiments, as it supports https. in order to facilitate local development, localhost is considered a secure origin by browsers as well. basic architecture with service workers, the following steps are generally observed for basic set up: the service worker url is fetched and registered via serviceworkercontainer.register(). if successful, the service worker is executed in a serviceworkerglobalscope; this is basically a special kind of worker context, running off the main script execution thread, with no dom access. the service worker is now ready to process events. installat...
...And 12 more matches
Signaling and video calling - Web APIs
a connection is established through a discovery and negotiation process called signaling. this tutorial will guide you through building a two-way video-call. webrtc is a fully peer-to-peer technology for the real-time exchange of audio, video, and data, with one central caveat. a form of discovery and media format negotiation must take place, as discussed elsewhere, in order for two devices on 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. ...
... channel the information back and forth. the contents don't matter at all to the signaling server. readying the chat server for signaling our chat server uses the websocket api to send information as json strings between each client and the server. the server supports several message types to handle tasks, such as registering new users, setting usernames, and sending public chat messages. to allow the server to support signaling and ice negotiation, we need to update the code. we'll have to allow directing messages to one specific user instead of broadcasting to all connected users, and ensure unrecognized message types are passed through and delivered, without the server needing to know what they are. this lets us send signaling messages using this same server, instead of needing a separa...
... } } } this code now looks at the pending message to see if it has a target property. if that property is present, it specifies the username of the client to which the message is to be sent, and we call sendtooneuser() to send the message to them. otherwise, the message is broadcast to all users by iterating over the connection list, sending the message to each user. as the existing code allows the sending of arbitrary message types, no additional changes are required. our clients can now send messages of unknown types to any specific user, letting them send signaling messages back and forth as desired. that's all we need to change on the server side of the equation. now let's consider the signaling protocol we will implement. designing the signaling protocol now that we've built a ...
...And 12 more matches
Inputs and input sources - Web APIs
nput sources for both targeting and selection. squeezable triggers or glove grip pads to provide squeeze actions. voice commands using speech recognition. spatially-tracked articulated hands, such as haptic gloves can provide both targeting and squeeze actions, as well as selection if outfitted with buttons or other sources of selection actions. single-button click devices. gaze tracking (following the movements of the eye to choose targets). input sources each source of webxr input data is represented by an xrinputsource object which describes the input source and its current state. the information for each input source includes which hand it's held in (if applicable), what targeting method it uses, xrspaces that can be used to draw the targeting ray and to find the targeted object o...
...direction. if the controller were instead positioned to the left of and closer to the user than the world space origin (or possibly behind the user, if the user is located at the origin, although that's an uncomfortable way to hold a controller), the coordinates would have a negative value for x, but a positive value for z. ...
... left of and closer to the user than the world space origin (or possibly behind the user, if the user is located at the origin, although that's an uncomfortable way to hold a controller), the coordinates would have a negative value for x, but a positive value for z. the value of y would still be positive unless the controller was moved below the world space origin. this is shown in the diagram below, in which the controller is located down and to the left of the world space's origin, with the controller also moved to be closer to us than the origin. as a result, the values of x and y are both negative, while z is positive. mapping a grip space to the world origin when the controller is positioned below and to the left of the world origin, and closer to us than the world origin is. ga...
...And 12 more matches
Web Audio API - Web APIs
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. ...
...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. ...
...iplying the samples by a value to make them louder or quieter (as is the case with gainnode). once the sound has been sufficiently processed for the intended effect, it can be linked to the input of a destination (audiocontext.destination), which sends the sound to the speakers or headphones. this last connection is only necessary if the user is supposed to hear the audio. 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 ...
...And 12 more matches
ARIA Test Cases - Accessibility
pass 2. fail - - voiceover (leopard) n/a n/a - fail window-eyes - - - - nv...
...an be directly checked. also, as a clever feature for at testing, the firing of events (like event_object_statechange) can be invoked from the examples. finally, a list of currently non-mapped aria roles is given. documenting and filing bugs review the information on how to file a bug on an aria implementation. when documenting an issue, please also list it in the relevant compatibility table below. when possible provide a link to the bug in the database so that its status can be reviewed. widget test cases alert simple alert complex alert real alert example with aria-required and aria-invalid -- type in a email address without an at sign to test the alert expected at behavior: a screen reader or screen magnifier must speak an alert when it becomes visible. a screen magnifier s...
...when pressing space, new state should be announced automatically. markup used: role="checkbox" aria-checked="true" or "false" notes: need testcase where aria-checked attribute is removed instead of set to false results: at firefox ie opera safari jaws 9 - - n/a n/a j...
...And 12 more matches
Web Accessibility: Understanding Colors and Luminance - Accessibility
iterion 1.4.3: contrast) a viewer's distance from the screen, the ambient background, 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. 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 per...
...s behind the evolution of digital technology set the standards, and these standards still retain a powerful presence today. this is evolving, and new methods for measuring color involve measurements using other color spaces, but color measurements in the rgb color space still predominates, and this includes video production. the rgb color model is extended to include “alpha” -- rgba -- to allow specification of the opacity of a color. there's movement towards adopting the use of hsl color values rather than rgb values is css color module 3 (see section 4.2.4), the rationale being that rgb is hardware-oriented, reflecting the use of crts, and that rgb is non-intuitive. that said, hsl colors incorporate lightness, not luminance, and this is a significant consideration. note that in tha...
... in addition, the "shape" of the text itself will matter. thin letters will be harder to read than thick ones; all type faces need space to "breathe" for human perception. in general, for accessibility purposes, the more contrast the better. that changes with animation. "safer" animation means images with less contrast, not more. for more on color contrast in animation, see three flashes or below threshold understanding sc 2.3.1 icons also need sufficient contrast for perception. see wcag 2.1 technique g207 luminance it is the difference in the luminance of a color that enables us to see contrast. here is the definition of relative luminance as defined by the w3c: "the relative brightness of any point in a colorspace, normalized to 0 for darkest black and 1 for lightest white" this...
...And 12 more matches
Visual formatting model - CSS: Cascading Style Sheets
such as a computer screen and paged media such as a book or document printed by browser print functions. most of the information applies equally to continuous and paged media. in the visual formatting model, each element in the document tree generates zero or more boxes according to the box model. the layout of these boxes is governed by: box dimensions and type. positioning scheme (normal flow, float, and absolute positioning). relationships between elements in the document tree. external information (e.g., viewport size, intrinsic dimensions of images, etc.). much of the information about the visual formatting model is defined in css2, however, various level 3 specifications have added to this information. when reading specifications you will often find references to the model as ...
... then, for each element, css generates zero or more boxes as specified by that element’s display property value. note: boxes are often referred to by their display type — e.g. a box generated by an element with display: block is called a "block box" or just a "block". note however that block boxes, block-level boxes and box containers are all subtly different; see the block boxes section below for more details. the principal box when an element generates one or more boxes, one of them is the principal box, which contains its descendant boxes and generated content in the box tree, and is also the box involved in any positioning scheme. some elements may generate additional boxes in addition to the principal box, for example display: list-item generates more than one box (e.g. a prin...
...lumns; these also cannot be styled or otherwise targetted. table layout will add anonymous boxes to create a proper table structure — for example adding an anonymous table row — if there was no box with display: table-row. line boxes line boxes are the boxes that wrap each line of text. ...
...And 12 more matches
position - CSS: Cascading Style Sheets
Web › CSS › position
and left properties determine the final location of positioned elements. 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. this is the default value. relative the element is positioned according to the normal flow of the document, and then offset relative to itself based on the values of top, right, bottom, and left. the offset does not affect the position ...
...t does not affect the position of any other elements; thus, the space given for the element in the page layout is the same as if position were static. this value creates a new stacking context when the value of z-index is not auto. 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 box...
...losest 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 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...
...And 12 more matches
Audio and Video Delivery - Developer guides
king them available through the browser's <audio> and <video> elements remains pretty much the same. currently, to support all browsers we need to specify two formats, although with the adoption of mp3 and mp4 formats in firefox and opera, this is changing fast. you can find compatibility information in the guide to media types and formats on the web. to deliver video and audio, the general workflow is usually something like this: check what format the browser supports via feature detection (usually a choice of two, as stated above). if the browser doesn't support playback of any of the provided formats natively, either present a still image or use a fallback technology to present the video. identify how you want to play/instantiate the media (e.g. a <video> element, or document.createe...
...udio.setattribute('src','audiofile.ogg'); } myaudio.currenttime = 5; myaudio.play(); we set the source of the audio depending on the type of audio file the browser supports, then set the play-head 5 seconds in and attempt to play it. note: play will be ignored by most browsers unless issued by a user-initiated event. it's also possible to feed an <audio> element a base64 encoded wav file, allowing to generate audio on the fly: <audio id="player" src="data:audio/x-wav;base64,uklgrvc..."></audio> speak.js employs this technique. try the demo. javascript video var myvideo = document.createelement('video'); if (myvideo.canplaytype('video/mp4')) { myvideo.setattribute('src','videofile.mp4'); } else if (myvideo.canplaytype('video/webm')) { myvideo.setattribute('src','videofile.webm')...
...you take the stream you receive from getusermedia, pass ...
...And 12 more matches
Block formatting context - Developer guides
floats (elements where float isn't none). absolutely positioned elements (elements where position is absolute or fixed). inline-blocks (elements with display: inline-block). ...
... captions (elements with display: table-caption, which is the default for html table captions). anonymous table cells implicitly created by the elements with display: table, table-row, table-row-group, table-header-group, table-footer-group (which is the default for html tables, table rows, table bodies, table headers, and table footers, respectively), or inline-table. block elements where overflow has a value other than visible. display: flow-root. elements with contain: layout, content, or paint. flex items (direct children of the element with display: flex or inline-flex) if they are neither flex nor grid nor table containers themselves. grid items (direct children of the element with display: grid or inline-grid) if they are neither flex nor grid nor table containers themselves. mu...
...ext, which is similar to block formatting context except layout. there's no floating children avaliable inside a flex/grid container, but exclude external floats and suppress margin collapsing still works. examples contain internal floats make float content and alongside content the same height. let's have a look at a couple of these in order to see the effect creating a new bfc. ...
...And 12 more matches
HTML5 - Developer guides
Web › Guide › HTML › HTML5
html5 is the latest evolution of the standard that defines html. the term represents two different concepts. it is a new version of the language html, with new elements, attributes, and behaviors, and a larger set of technologies that allows the building of more diverse and powerful web sites and applications. this set is sometimes called html5 & friends and often shortened to just html5. ...
...aviors, and a larger set of technologies that allows the building of more diverse and powerful web sites and applications. this set is sometimes called html5 & friends and often shortened to just html5. designed to be usable by all open web developers, this reference page links to numerous resources about html5 technologies, classified into several groups based on their function. semantics: allowing you to describe more precisely what your content is. connectivity: allowing you to communicate with the server in new and innovative ways. offline and storage: allowing webpages to store data on the client-side locally and operate offline more efficiently. multimedia: making video and audio first-class citizens in the open web. ...
... styling: letting authors write more sophisticated themes. ...
...And 12 more matches
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
Web › HTML › Element › iframe
topmost browsing context — the one with no parent — is usually the browser window, represented by the window object. because each browsing context is a complete document environment, every <iframe> in a page requires increased memory and other computing resources. while theoretically you can use as many <iframe>s as you like, check for performance problems. content categories flow content, phrasing content, embedded content, interactive content, palpable content. permitted content none. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts embedded content. implicit aria role no corresponding role permitted aria roles application, document, img, none, present...
.... tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts embedded content. implicit aria role no corresponding role permitted aria roles application, document, img, none, presentation dom interface htmliframeelement attributes this element includes the global attributes. ...
... permitted aria roles application, document, img, none, presentation dom interface htmliframeelement attributes this element includes the global attributes. allow specifies a feature policy for the <iframe>. see the article privacy, permissions, and information security for details on security issues and how <iframe> works with feature policy to keep systems safe. allowfullscreen set to true if the <iframe> can activate fullscreen mode by calling the requestfullscreen() method. this attribute is considered a legacy attribute and redefined as allow="fullscreen". ...
...And 12 more matches
Global attributes - HTML: Hypertext Markup Language
nts, even those not specified in the standard. that means that any non-standard elements must still permit these attributes, even though using those elements means that the document is no longer html5-compliant. for example, html5-compliant browsers hide content marked as <foo hidden>...</foo>, even though <foo> is not a valid html element. in addition to the basic html global attributes, the following global attributes also exist: xml:lang and xml:base — these are inherited from the xhtml specifications and deprecated, but kept for compatibility purposes. the multiple aria-* attributes, used for improving accessibility. the event handler attributes: onabort, onautocomplete, onautocompleteerror, onblur, oncancel, oncanplay, oncanplaythrough, onchange, onclick, onclose, oncontextmenu, ...
...ist of global attributes accesskey provides a hint for generating a keyboard shortcut for the current element. this attribute consists of a space-separated list of characters. the browser should use the first one that exists on the computer keyboard layout. autocapitalize controls whether and how text input is automatically capitalized as it is entered/edited by the user. ...
... for the current element. this attribute consists of a space-separated list of characters. the browser should use the first one that exists on the computer keyboard layout. autocapitalize controls whether and how text input is automatically capitalized as it is entered/edited by the user. ...
...And 12 more matches
Digital audio concepts - Web media technologies
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 black. at regular intervals, the a/d converter circuitry reads the voltage of the signal as a value between (in this case) -1.0 and +1.0. since the amplitude varies over the duration of that time slice, the a/d converter must choose a value to represent that slice, whether by simply taking the value ...
...e to audio codecs used on the web. audio channels and frames there are two types of audio channel. standard audio channels are used to present the majority of the audible sound. the sound for the left and right main channels, as well as all of your surround sound speakers (center, left and right rear, left and right sides, ceiling channels, and so forth) are all standard audio channels. special low frequency enhancement (lfe) channels provide the signal for special speakers designed to produce the low frequency sounds and vibration to create a visceral sensation when listening to the audio. the lfe channels typically drive subwoofers and similar devices. monophonic audio has one channel, stereo sound has two channels, 5.1 surround sound has 6 channels (five standard and one lfe), and so fo...
...minimum "high fidelity" sampling rate. the nyquist-shannon sampling theorem dictates that to reproduce a sound accurately, it must be sampled at twice the rate of the sound's frequency. since the range of human hearing is from around 20 hz to 20,000 hz, reproducing the highest-pitched sounds people can generally hear requires a sample rate of more than 40,000 hz. to provide additional room for a low-pass filter in order to avoid distortion caused by aliasing, an additional 2.05 khz transition band is added to the pre-sampling frequency (resulting in 22,050 hz). doubling that per the nyquist theorem results in a final minimum frequency of (you guessed it) 44.1 khz. high-resolution (96 khz) audio is used in some high-end audio systems, and it and ultra-high resolution (192 khz) audio are usef...
...And 12 more matches
platform/xpcom - Archive of obsolete content
om there. implementing xpcom interfaces this module exports a class called unknown which implements the fundamental xpcom interface nsisupports. by subclassing unknown, either using standard javascript inheritance or using the sdk's heritage module, you can provide your own implementations of xpcom interfaces. "unknown" is named after the "iunknown" interface in com. for example, the add-on below implements the nsiobserver interface to listen for and log all topic notifications: var { class } = require('sdk/core/heritage'); var { unknown } = require('sdk/platform/xpcom'); var { cc, ci } = require('chrome') var observerservice = cc['@mozilla.org/observer-service;1']. getservice(ci.nsiobserverservice); var starobserver = class({ extends: unknown, interfaces: [...
...{ console.log('star observer:', subject, topic, data); } }); var starobserver = starobserver(); starobserver.register(); implementing xpcom factories the xpcom module exports a class called factory which implements the nsifactory interface. you can use this class to register factories for xpcom components you have defined. ...
...er.register(); implementing xpcom factories the xpcom module exports a class called factory which implements the nsifactory interface. you can use this class to register factories for xpcom components you have defined. for example, this add-on defines a subclass of unknown called helloworld that implements a function called hello. by creating a factory and passing it the contract id for the helloworld component and the helloworld constructor, we enable xpcom clients to access the helloworld component, given its contract id. in this example the helloworld component is available to javascript only, so we use the technique documented under the "using wrappedjsobject" section of how to build an xpcom component in javascript. var { class } = require('sdk/core/heritage'); var { unknown, factor...
...And 11 more matches
Chapter 3: Introduction to XUL—How to build a more intuitive UI - 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 you learn how to develop extensions, let's learn about xul, the xml-based user-interface language, which is one of the building blocks for extensions. introduction an overview of xul xul is an xml-based language, and was developed to be the gui markup language for the mozilla browser. ...
...lues) as a size multiplier for elements. in listing 4, the second label will be displayed twice as big as the first (figure 3). <hbox> <label value="label1" flex="1" style="border: 1px solid;"/> <label value="label2" flex="2" style="border: 1px solid;"/> </hbox> listing 4: growing with flex figure 3: output of listing 4 ordinal within a xul box, elements will ordinarily be laid out following their order of appearance in the source code (laid out left to right or top to bottom). use the ordinal attribute to alter their order. the ordinal attribute takes positive integer values, which are used to order the box’s layout—in the example in listing 5, the buttons would be laid out in the order button3, button2, button1 (figure 4). if multiple elements have the same ordinal value, t...
...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. these all use pixels as the unit of size. <button label="button" width="200" height="100"/> listing 6: setting the size of a button also, as shown in listing 7, you can embed css inline into elements via the style attribute, which allows you to set sizes using units other than pixels. <button label="button" style="min-width: 10em;"/> listing 7: setting the size of a button using css markup hidden and collapsed the hidden and collapsed attributes act as switches to turn off the display of elements. setting hidden="true" disables display of that element. this has the same effect as setting display: none in css. you would use...
...And 11 more matches
The Essentials of an Extension - Archive of obsolete content
code, starting with the install.rdf file. you can open it with any text editor. the file is formatted in a special flavor of xml called rdf. rdf used to be the central storage mechanism for firefox, but it is now being replaced for a simpler database system. we'll discuss both of these storage systems further ahead in the tutorial. now let's look at the important parts of the file. <em:id>helloworld@xulschool.com</em:id> this is the unique identifier for the extension. firefox needs this to distinguish your extension from other extensions, so it is required that you have an id that is unique. there are two accepted standards for add-on ids. one is the email-like format in the hello world example, which should be something like <project-name>@<yourdomain>. the other standard practice ...
...s installed, that you can see in the add-ons manager. there are many other tags that can be added, for contributors and translators. the full specification of the install.rdf file has all the details. since extensions can be translated to multiple languages, it is often necessary to translate the extension's description, or even its name. a localized description and name can be added with the following code: <em:localized> <description> <em:locale>es-es</em:locale> <em:name>xul school hola mundo</em:name> <em:description>bienvenido a xul school!</em:description> </description> </em:localized> the es-es locale string indicates that this is the spanish (es) localization for spain (es). you can add as many <em:localized> sections as you need. for firefox 2, localizing this...
...nsion 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 with firefox 11, add-ons will default to compatible and firefox will mostly ignore the version range. testing your add-ons with every firefox version is always recommended, though. this is ...
...And 11 more matches
MMgc - Archive of obsolete content
jects more concisely: using namespace mmgc; ... gc* gc = gc::getgc(this); gcobject* gcobject; gc class the class mmgc::gc is the main class of the gc. it represents a full, self-contained instance of the garbage collector. it may be multiply instantiated; you may have multiple instances of the garbage collector running at once. each instance manages its own set of objects; objects are not allowed to reference objects in other gc instances. the gc typically is constructed early in your program's initialization, and then passed to operations like operator new for allocating gc objects. there are a few methods that you may need to call directly, such as alloc and free. gc::alloc, gc::free the alloc and free methods are garbage-collected analogs for malloc and free. memory allocated with al...
...delete operator. only do this if you know for certain that there are no other references, and you want to help the gc along: // optimization: get rid of myobject now, because we know there are no other // references, so no need to wait for gc to clean it up. delete myobject; the destructor for a gcobject will never be called (unless the object is also a descendant of gcfinalizedobject... see below.) class myobject : public mmgc::gcobject { ~myobject() { assert(!"this will never be hit (unless we also descend from gcfinalizedobject)"); } }; gcobject::getweakref gcweakref *getweakref() const; the getweakref method returns a weak reference to the object. normally, a pointer to the object is considered a hard reference -- any such reference will prevent the object from being destroyed. som...
...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. ...
...And 11 more matches
What is RSS - Archive of obsolete content
stood for rich site summary. in july of 1999 netscape's rss 0.91 was released. like rss 0.90, netscape's rss 0.91 was also a format for providing a summary of a website, and not really a syndication format (as it is today). netscape's rss 0.91 was created to simplify things. rss 0.90 was rdf-based, which many found to be overly complex. netscape's rss 0.91 was only xml-based and added a dtd to allow several entities (commonly found in html). so at this point netscape deprecated the rdf-based rss 0.90 and told everyone to use netscape's rss 0.91, which was xml-based. in june of 2000 userland's rss 0.91 was released. (and yes, that means that there are 2 different version of rss 0.91.) the difference between the two different versions of rss 0.91 -- netscape's rss 0.91 and userland's rss 0.9...
...<guid ispermalink="false">c1795324-d5ea-44fa-95b1-b5ce2090d4f1</guid> <pubdate>sun, 15 may 2005 13:02:08 -0700</pubdate> <link>http://news.example.com/artcle/552</link> </item> </channel> </rss> bloggers use rss to provide everyone with a list of their newest blog posts. ...
...d> <pubdate>sun, 15 may 2005 13:02:08 -0700</pubdate> <link>http://news.example.com/artcle/552</link> </item> </channel> </rss> bloggers use rss to provide everyone with a list of their newest blog posts. ...
...And 11 more matches
Introduction to SSL - Archive of obsolete content
sport and routing of data over the internet. other protocols, such as the hypertext transport protocol (http), lightweight directory access protocol (ldap), or internet messaging access protocol (imap), run "on top of" tcp/ip in the sense that they all use tcp/ip to support typical application tasks such as displaying web pages or running email servers. the ssl protocol runs above tcp/ip and below higher-level protocols such as http or imap. it uses tcp/ip on behalf of the higher-level protocols, and in the process allows an ssl-enabled server to authenticate itself to an ssl-enabled client, allows the client to authenticate itself to the server, and allows both machines to establish an encrypted connection. these capabilities address fundamental concerns about communication over the inte...
...ssl-enabled client software can use standard techniques of public-key cryptography to check that a server's certificate and public id are valid and have been issued by a certificate authority (ca) listed in the client's list of trusted cas. ...
...e standard techniques of public-key cryptography to check that a server's certificate and public id are valid and have been issued by a certificate authority (ca) listed in the client's list of trusted cas. this confirmation might be important if the user, for example, is sending a credit card number over the network and wants to check the receiving server's identity. ssl client authentication allows a server to confirm a user's identity. using the same techniques as those used for server authentication, ssl-enabled server software can check that a client's certificate and public id are valid and have been issued by a certificate authority (ca) listed in the server's list of trusted cas. this confirmation might be important if the server, for example, is a bank sending confidential financial...
...And 11 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
have a look to the more current article writing forward-compatible websites to find modern 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. ...
...embers of an entire family of user agents based upon the gecko layout engine which includes the commercial browser compuserve 7, and open source browsers such as epiphany, galeon, camino, kmeleon, and seamonkey. gecko was designed from the ground up to be compliant with the w3c html, w3c css, w3c xml, w3c dom, and ecmascript (javascript) standards. ...
...unfortunately, no other browser supports web standards as completely as gecko. this means web developers and authors are forced to continue to support other browsers which do not comply with the standards as fully. fortunately, other browsers such as opera (versions 7 & later) and to a lesser extent, internet explorer (versions 5.5 & later) also support the standards to a degree. ...
...And 11 more matches
RDF in Mozilla FAQ - Archive of obsolete content
f 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 datasource, refer to the rdf datasource how-to. how does mozilla manage datasources? the rdf service manages a table of all loaded datasources. the table is keyed by the datasource's "uri", which is either the url of an rdf/xml file, or a "special" uri starting with rdf: that refers to a built-in datasou...
...ces.nsirdfservice); // ...and from it, get the datasource. make sure that your web server // dishes it up as text/xml (recommended) or text/rdf! var ds = rdf.getdatasource("http://www.mozilla.org/some-rdf-file.rdf"); // note that ds will load asynchronously, so assertions will not // be immediately available alternatively, you can create one directly using the xpcom component manager, as the following code fragment illustrates: // create an rdf/xml datasource using the xpcom component manager var ds = components .classes["@mozilla.org/rdf/datasource;1?name=xml-datasource"] .createinstance(components.interfaces.nsirdfdatasource); // the nsirdfremotedatasource interface has the interfaces // that we need to setup the datasource. var remote = ds.queryinterface(components.interfaces.n...
...n't loaded, but it's loading now!"); } say the datasource wasn't loaded, and is loading asynchronously. using this api and javascript's settimeout(), one could set up a polling loop that would continually check the loaded property. ...
...And 11 more matches
Accessible multimedia - Learn web development
="a red tyrannosaurus rex: a two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth."> accessible audio and video controls implementing controls for web-based audio/video shouldn't be a problem, right? let's investigate. the problem with native html5 controls html5 video and audio instances even come with a set of inbuilt controls that allow you to control the media straight out of the box. for example (see native-controls.html source code and live): <audio controls> <source src="viper.mp3" type="audio/mp3"> <source src="viper.ogg" type="audio/ogg"> <p>your browser doesn't support html5 audio. here is a <a href="viper.mp3">link to the audio</a> instead.</p> </audio> <br> <video controls> <source src="rabbit320.mp4" type="v...
... however, there are problems with these controls: they are not keyboard accessible in most browsers, i.e. you can't tab between the controls inside the native player. opera and chrome provide this to some degree, but it still isn't ideal. different browsers give the native controls differing styling and functionality, and they aren't stylable, meaning that they can't be easily made to follow a site style guide. to remedy this, we can create our own custom controls. let's look at how. creating custom audio and video controls html5 video and audio share an api — html media element — which allows you to map custom functionality to buttons and other controls — both of which you define yourself. let's take the video example from above and add custom controls to them. basic set...
...html5 video. ...
...And 11 more matches
WAI-ARIA basics - Learn web development
wai-aria is a technology that can help with such problems by adding in further semantics that browsers and assistive technologies can recognize and use to let users know what is going on. here we'll show how to use it at a basic level to improve accessiblity. prerequisites: basic computer literacy, a basic understanding of html, css, and javascript, an understanding of the previous articles in the course. ...
...others that describe different pages structures, such as role="banner", role="search", role="tabgroup", role="tab", etc., which are commonly found in uis. properties — these define properties of elements, which can be used to give them extra meaning or semantics. as an example, aria-required="true" specifies that a form input needs to be filled in to be valid, whereas aria-labelledby="label" allows you to put an id on an element, then reference it as being the label for anything else on the page, including multiple elements, which is not possible using <label for="input">. as an example, you could use aria-labelledby to specify that a key description contained in a <div> is the label for multiple table cells, or you could use it as an alternative to image alt text — specify existing info...
...rs when an area of content is updated, e.g. via xmlhttprequest, or dom apis. enhancing keyboard accessibility: there are built-in html elements that have native keyboard accessibility; when other elements are used along with javascript to simulate similar interactions, keyboard accessibility and screenreader reporting suffers as a result. where this is unavoidable, wai-aria provides a means to allow other elements to receive focus (using tabindex). accessibility of non-semantic controls: when a series of nested <div>s along with css/javascript is used to create a complex ui-feature, or a native control is greatly enhanced/changed via javascript, accessibility can suffer — screenreader users will find it difficult to work out what the feature does if there are no semantics or other clues. ...
...And 11 more matches
Cascade and inheritance - Learn web development
d your css. this can seem like a set of tricky concepts to understand. as you get more practice writing css, however, the way it works will become more obvious to you. the cascade stylesheets cascade — at a very simple level this means that the order of css rules matter; when two rules apply that have equal specificity the one that comes last in the css is the one that will be used. in the below example, we have two rules that could apply to the h1. the h1 ends up being colored blue — these rules have an identical selector and therefore carry the same specificity, so the last one in the source order wins. specificity specificity is how the browser decides which rule applies if multiple rules have different selectors, but could still apply to the same element. it is basically a mea...
...the last one in the source order wins. specificity specificity is how the browser decides which rule applies if multiple rules have different selectors, but could still apply to the same element. ...
...ame element. it is basically a measure of how specific a selector's selection will be: an element selector is less specific — it will select all elements of that type that appear on a page — so will get a lower score. a class selector is more specific — it will select only the elements on a page that have a specific class attribute value — so will get a higher score. example time! below we again have two rules that could apply to the h1. the below h1 ends up being colored red — the class selector gives its rule a higher specificity, and so it will be applied even though the rule with the element selector appears further down in the source order. we'll explain specificity scoring and other such things later on. inheritance inheritance also needs to be understood in this c...
...And 11 more matches
HTML basics - Learn web development
ge; 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. ...
...this states where the element begins or starts to take effect — in this case where the paragraph begins. ...
...re the element ends — in this case where the paragraph ends. failing to add a closing tag is one of the standard beginner errors and can lead to strange results. the content: this is the content of the element, which in this case, is just text. the element: the opening tag, the closing tag and the content together comprise the element. elements can also have attributes that look like the following: attributes contain extra information about the element that you don't want to appear in the actual content. here, class is the attribute name and editor-note is the attribute value. the class attribute allows you to give the element a non-unique identifier that can be used to target it (and any other elements with the same class value) with style information and other things. an attribute...
...And 11 more matches
Introduction to events - Learn web development
the handler is the code that is run in response to it happening. note: web events are not part of the core javascript language — they are defined as part of the apis built into the browser. a simple example let's look at a simple example of what we mean here. you've already seen events and event handlers used in many of the examples, but let's recap just to cement our knowledge. ...
... therefore, event handlers available. we are listening for the click event firing, by setting the onclick event handler property to equal an 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.
...ler property being used in this situation. it is essentially a property like any other available on the button (e.g. btn.textcontent, or btn.style), but it is a special type — when you set it to be equal to some code, that code is run when the event fires on the button. you could also set the handler property to be equal to a named function name (like we saw in build your own function). the following works just the same: const btn = document.queryselector('button'); function bgchange() { const rndcol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundcolor = rndcol; } btn.onclick = bgchange; there are many different event handler properties available. let's experiment. first, make a local copy of random-color-eventhandlerproperty.ht...
...And 11 more matches
Introduction to web APIs - Learn web development
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 simply plug it into a plug socket and it works. you don't try to wire it directly into t...
... to do so would be really inefficient and, if you are not an electrician, difficult and dangerous to attempt. image source: overloaded plug socket by the clear communication people, on flickr. in the same way, if you want to say, program some 3d graphics, it is a lot easier to do it using an api written in a higher-level language such as javascript or python, rather than try to directly write low level code (say c or c++) that directly controls the computer's gpu or other graphics functions. note: see also the api glossary entry for further description. apis in client-side javascript client-side javascript, in particular, has many apis available to it — these are not part of the javascript language itself, rather they are built on top of the core javascript language, providing you ...
...ser apis are built into your web browser and are able to expose data from the browser and surrounding computer environment and do useful complex things with it. for example, the web audio api provides javascript constructs for manipulating audio in the browser — taking an audio track, altering its volume, applying effects to it, etc. in the background, the browser is actually using some complex lower-level code (e.g. c++ or rust) to do the actual audio processing. but again, this complexity is abstracted away from you by the api. third-party apis are not built into the browser by default, and you generally have to retrieve their code and information from somewhere on the web. for example, the twitter api allows you to do things like displaying your latest tweets on your website. it provide...
...And 11 more matches
Arrays - Learn web development
ady be annoying, but what about 100 items, or 1000? we'll return to this example later on in the article. as in previous articles, let's learn about the real basics of arrays by entering some examples into browser developer console. creating arrays arrays consist of square brackets and elements that are separated by commas. suppose we want to store a shopping list in an array. paste the following code into the console: let shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles']; shopping; in the above example, each element is a string, but in an array we can store various data types — strings, numbers, objects, and even other arrays. we can also mix data types in a single array — we do not have to limit ourselves to storing only numbers in one array, and in another only st...
... to storing only numbers in one array, and in another only strings. for example: let sequence = [1, 1, 2, 3, 5, 8, 13]; let random = ['tree', 795, [0, 1, 2]]; before proceeding, create a few example arrays. accessing and modifying array items you can then access individual items in the array using bracket notation, in the same way that you accessed the letters in a string. 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 a...
...do something like this: random[2][2]; try making some more modifications to your array examples before moving on. play around a bit, and see what works and what doesn't. finding the length of an array you can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string — by using the length property. try the following: shopping.length; // should return 5 this has other uses, but it is most commonly used to tell a loop to keep going until it has looped through all the items in an array. so for example: let sequence = [1, 1, 2, 3, 5, 8, 13]; for (let i = 0; i < sequence.length; i++) { console.log(sequence[i]); } you'll learn about loops properly later on (in our looping code article), but briefly, this ...
...And 11 more matches
Working with JSON - Learn web development
ng json. 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 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 ja...
...ile, which is basically just a text file with an extension of .json, and a mime type of application/json. json structure as described above, a json is a string whose format very much resembles javascript object literal format. you can include the same basic data types inside json as you can in a standard javascript object — strings, numbers, arrays, booleans, and other object literals. ...
...selector('section'); we have made our json data available on our github, at https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json. we are going to load it into our page, and use some nifty dom manipulation to display it, like this: obtaining the json to obtain the json, we use an api called xmlhttprequest (often called xhr). this is a very useful javascript object that allows us to make network requests to retrieve resources from a server via javascript (e.g. images, text, json, even html snippets), meaning that we can update small sections of content without having to reload the entire page. this has led to more responsive web pages, and sounds exciting, but it is beyond the scope of this article to teach it in much more detail. to start with, we store the url of...
...And 11 more matches
Aprender y obtener ayuda - Learn web development
ation about each sub-topic should you wish.. effective learning let's move straight on and think about effective learning. different learning methods it is interesting to consider that there 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 neu...
...effective for you to learn with. textual articles you'll find a lot of written articles on the web to teach you about web design. like most of this course, for example. some of the articles will be tutorials, to teach you a certain technique or important concept (such as "learn how to create a video player" or "learn the css box model"), and some of the articles will be reference material, to allow you to look up details you may have forgotten (such as "what is the syntax of the css background property"?) mdn web docs is very good for both types — the area you are currently in is great for learning techniques and concepts, and we also have several giant reference sections allowing you to look up any syntax you can't remember. there are also several other great resources on the web, some...
...u may have forgotten (such as "what is the syntax of the css background property"?) mdn web docs is very good for both types — the area you are currently in is great for learning techniques and concepts, and we also have several giant reference sections allowing you to look up any syntax you can't remember. there are also several other great resources on the web, some of which we'll mention below. note: the above text should have given you an important fact — you aren't expected to remember everything! professional web developers use tools like mdn web docs to look up things they have forgotten all the time. as you'll discover, learning web development is more about problem-solving and learning patterns than it is about learning lots of syntaxes. videos there are also a number of s...
...And 11 more matches
Client-Server Overview - Learn web development
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 on the server, or a tool to run). a method that defines the required action (for example, to get a file or to save or update some data). the different methods/verbs and their associated actions are listed below: get: get a specific resource (e.g. an html file containing information about a product, or a list of products). post: create a new resource (e.g. add a new article to a wiki, add a new contact to a database). head: get the metadata information about a specific resource without getting the body like get would. you might for example use a head request to find out the last time a reso...
...of a successful response to a get request would contain the requested resource. when an html page is returned it is rendered by the web browser. as part of processing the browser may discover links to other resources (e.g. an html page usually references javascript and css pages), and will send separate http requests to download these files. ...
... the format of http messages is defined in a "web standard" (rfc7230). you don't need to know this level of detail, but at least now you know where this all came from! the request each line of the request contains information about it. ...
...And 11 more matches
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
tanding 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 conditional rendering, and wire up some of our footer functionality. ...
...r functionality. 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. ...
...r. 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. ...
...And 11 more matches
Vue conditional rendering: editing existing todos - Learn web development
we'll also look at adding functionality to delete todo items. ...
...ures of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn how to do conditional rendering in vue. creating an editing component we can start by creating a separate component to handle the editing functionality. in your components directory, create a new file called todoitemeditform.vue. ...
...this is a useful way to help reinforce everything you've learned so far. this code sets up the core of the edit functionality. we create a form with an <input> field for editing the name of our to-do. there is a "save" button and a "cancel" button: when the "save" button is clicked, the component emi...
...And 11 more matches
Implementing feature detection - Learn web development
p and look at the example we touched on in our handling common javascript problems — the geolocation api (which exposes available location data for the device the web browser is running on) has the main entry point for its use, a geolocation property available on the global navigator object. therefore, you can detect whether the browser supports geolocation or not by using something like the following: if ("geolocation" in navigator) { navigator.geolocation.getcurrentposition(function(position) { // show the location on a map, perhaps using the google maps api }); } else { // give the user a choice of static maps instead perhaps } it is probably better to use an established feature detection library however, rather than writing your own all the time. modernizr is the industry st...
...nd 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. download the latest version (see manual installation), unzip the zip file, copy the html5shiv-printshiv.min.js and html5shiv.min.js files into your example directory, and link to one of the files by putting the following under your <title> element: <script src="html5shiv.min.js"></script> have a look at your example css files — you'll see that basic-styling.css handles all the styling that we want to give to every browser, whereas the other two css files contain the css we want to selectively apply to browser depending on their support levels. you can look at the different effects these two files have b...
...ve by manually changing the css file referred to by the second <link> element, but let's instead implement some javascript to automatically swap them as needed. first, remove the contents of the second <link> element's href attribute. we will fill this in dynamically later on. next, add a <script></script> element at the bottom of your body (just before the closing </body> tag). ...
...And 11 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. ...
...trates 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. ...
...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 11 more matches
sslerr.html
has been requested." the application has attempted to configure ssl to use an unknown cipher suite. ssl_error_no_ciphers_supported -12265 "no cipher suites are present and enabled in this program." possible causes: (a) all cipher suites have been configured to be disabled, (b) the only cipher suites that are configured to be enabled are those that are disallowed by cipher export policy, (c) the socket is configured to handshake as a server, but the certificate associated with that socket is inappropriate for the key exchange algorithm selected. ssl_error_bad_block_padding -12264 "ssl received a record with bad block padding." ssl was using a block cipher, and the last block in an ssl record had incorrect padding information...
...this probably indicates a flaw in the remote peer's implementation. ...
...this probably indicates a flaw in the remote peer's implementation. ssl_error_rx_malformed_hello_request -...
...And 11 more matches
Hacking Tips
pan 9 getting the bytecode of a function (from gdb) in jsopcode.cpp, a function named js::disassembleatpc can print the bytecode of a script. some variants of this function such as js::dumpscript etc are convenient for debugging. printing the js stack (from gdb) in jsobj.cpp, a function named js::dumpbacktrace prints a backtrace à la gdb for the js stack. the backtrace contains in the following order, the stack depth, the interpreter frame pointer (see js/src/vm/stack.h, stackframe class) or (nil) if compiled with ionmonkey, the file and line number of the call location and under parentheses, the jsscript pointer and the jsbytecode pointer (pc) executed. $ gdb --args js […] (gdb) b js::reportoverrecursed (gdb) r js> function f(i) { if (i % 2) f(i + 1); else f(i + 3); } js> f(0...
... since spidermonkey 48, we have a gdb unwinder. this unwinder is able to read the frames created by the jit, and to display the frames which are after these jit frames. $ gdb --args out/dist/bin/js ./foo.js […] spidermonkey unwinder is disabled by default, to enable it type: enable unwinder .* spidermonkey (gdb) b js::math_cos (gdb) run […] #0 js::math_cos (...
...erjitdata&) (cx=0x14f2640, data=...) at js/src/jit/baselinejit.cpp:150 note, when you enable the unwinder, the current version of gdb (7.10.1) does not flush the backtrace. therefore, the jit frames do not appear until you settle on the next breakpoint. ...
...And 11 more matches
Component Internals
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 of the module, the shared library in which a component is defined. a component in the xpcom framework when you build a component or module and compile it into a library, it must export a single method named n...
...the application startup itself. a web browser that embeds gecko, for example, may initialize xpcom at startup through the embedding apis. another application may delay this startup until xpcom is needed for the first time. in either case, the initialization sequence within xpcom is the same. xpcom starts when the application makes a call to initialize it. ...
... if there are new components, xpcom registers them: xpcom calls autoregistration start. xpcom registers new components. ...
...And 11 more matches
Creating the Component Code
. this object provides basic abstraction of the xpcom object itself. as you can see in onion peel view of xpcom component creation, the main accessor for the xpcom object is createinstance, which is expected to return the object that matches a given cid and iid pair. moving another layer outward is the nsimodule. this interface provides yet another abstraction of the nsifactory object, and may allow for multiple nsifactory objects. the key to this interface is that the return type of getclassobject does not have to be an nsifactory. instead, the nsimodule can ask for implementation details about the xpcom object. this is very useful if the caller is required to know information about the component like its threading module, whether or not it's a singleton, its implementation language, and so...
...s instances of your component to clients. these three interface implementations - for the component functionality, nsimodule interface, and for the nsifactory interface - are the basic pieces of code you need to write to create an xpcom component. basic structure of the weblock component source weblock1.cpp that defines these classes and the code you need to create a basic component has the following structure: * required includes and constants * weblock: public iweblock * weblockfactory: public nsifactory * weblockmodule: public nsimodule in xpcom, all of these classes also derive from the nsisupports base interface. 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 i...
...an 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 specify themselves as mozilla_strict_api. includes and constants in weblock1.cpp #include <stdio.h> // may be defined at the project level // in the makefile #define mozilla_strict_api #include "nsimodule.h" #include "n...
...And 11 more matches
Introduction to XPCOM for the DOM
set of methods that manipulate an object (often represented by a class), without worrying about the details of the implementation. if you know a class implements an interface, just use the methods in the interface, and you don't have to care if the implementation of the interface (the concrete class) changes. xpcom pushes this concept to the extreme. pure virtual methods are declared with the following syntax: virtual nsresult functionfoo() = 0; an interface is thus simply a c++ class where all the member functions are declared as pure virtual functions. an interface can also be defined using xpidl. this is described in section 1.e, "how to add an interface". since an interface doesn't have any implementation, it has to be implemented by a non-abstract class -- a concrete class. if the i...
...ons. an interface can also be defined using xpidl. this is described in section 1.e, "how to add an interface". since an interface doesn't have any implementation, it has to be implemented by a non-abstract class -- a concrete class. if the interface is called nsifoo and the class is called nsfoo, we say that "nsfoo implements nsifoo", or that "nsfoo inherits from nsifoo". the c++ code is the following: class nsfoo : public nsifoo for those unfamiliar with object-oriented c++, this means that nsfoo is declared as "derived from" nsifoo, and that nsifoo is a "base class" of nsfoo. for this introduction you don't need to know more about object-oriented c++. however the section 1.f provides a more detailed discussion about it, and is necessary to understand most of the dom code. an instance ...
...l never change anymore. the good thing is that your code will (in the best condition) last forever. the bad thing is that we have to find a way to improve those interfaces, and freezing them obliges implementers to create new interfaces. in summary, manipulate an interface rather than its implementation whenever possible! a pointer to an interface nsifoo implemented by nsfoo can be declared as follows nsifoo *fooptr = new nsfoo; a pointer such as fooptr is then called a "pointer to an interface nsifoo implemented by an instance of the nsfoo class", or "pointer to nsifoo" in short. from now on, when i speak of a "pointer to an interface", i really mean a "pointer to an interface implemented by an instance of a concrete c++ class". the important thing to note is that a pointer to nsifoo can ...
...And 11 more matches
Plug-in Basics - Plugins
gives you an overview of the way that plug-ins operate in the browser. when gecko starts, it looks for plugin modules in particular places on the system. for more information about where gecko looks for plugin modules on different systems, see how gecko finds plug-ins. when the user opens a page that contains embedded data of a media type that invokes a plug-in, the browser responds with the following sequence of actions: check for a plug-in with a matching mime type load the plug-in code into memory initialize the plug-in create a new instance of the plug-in gecko can load multiple instances of the same plug-in on a single page, or in several open windows at the same time. if you are browsing a page that has several embedded realaudio clips, for example, the browser will create as ...
...s 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 instance of the plug-in. gecko calls the plug-in api function np_initialize when the plug-in code ...
...n to generate additional threads to handle processing at any stage in its lifespan, you should be careful to isolate these from plug-in api calls. see initialization and destruction for more information about using these methods. plug-in detection gecko looks for plug-ins in various places and in a particular order. the next section, how gecko finds plug-ins, describes these rules, and the following section, checking plug-ins by mime type, describes how you can use javascript to locate plug-ins yourself and establish which ones are to be registered for which mime types. how gecko finds plug-ins when a gecko-based browser starts up, it checks certain directories for plug-ins, in this order: windows directory pointed to by moz_plugin_path environment variable. %appdata%\mozilla\plugi...
...And 11 more matches
Using the CSS Painting API - Web APIs
ive the worklet — this is the name we will use in our css as the parameter of the paint() function when we want to apply this styling to an element. the second parameter is the class that does all the magic, defining the context options and what to paint to the two-dimensional canvas that will be our image. registerpaint('headerhighlight', class { /* define if alphatransparency is allowed alpha is set to true by default. if set to false, all colours used on the canvas will be fully opaque */ static get contextoptions() { return { alpha: true }; } /* ctx is the 2d drawing context a subset of the html5 canvas api. */ paint(ctx) { ctx.fillstyle = 'hsla(55, 90%, 60%, 1.0)'; ctx.fillrect(0, 15, 200, 20); ...
... } /* ctx is the 2d drawing context a subset of the html5 canvas api. */ paint(ctx) { ctx.fillstyle = 'hsla(55, 90%, 60%, 1.0)'; ctx.fillrect(0, 15, 200, 20); /* order: x, y, w, h */ } }); in this class example we have defined a single context option with the contextoptions() function: we returned a simple object stating alpha transparency is allowed. we have then used the paint() function to paint to our canvas. a paint() function can take three arguments. here we have provided one argument: the rendering context (we'll look at more in due course), often refered to by the variable name ctx. the 2d rendering context is a subset of the html5 canvas api; the version available to houdini (called the paintrenderingcontext2d) is a further subs...
...ndering context is a subset of the html5 canvas api; the version available to houdini (called the paintrenderingcontext2d) is a further subset containing most of the features available in the full canvas api with the exception of the canvasimagedata, canvasuserinterface, canvastext, and canvastextdrawingstyles apis. we define the fillstyle as being hsla(55, 90%, 60%, 1.0), which is a shade of yellow, and then call fillrect() to create a rectangle of that color. the fillrect() parameters are, in order, x-axis origin, y-axis origin, width, and height. fillrect(0, 15, 200, 20) results in the creation of a rectangle that is 200 units wide by 20 units tall, positioned 0 units from the left and 15 units from the top of the content box. we can use the css background-size and background-position pr...
...And 11 more matches
Using Fetch - Web APIs
oss-site cookies; you can’t can establish a cross site session using fetch. set-cookie headers from other sites are silently ignored. fetch won’t send cookies, unless you set the credentials init option. (since aug 25, 2017. the spec changed the default credentials policy to same-origin. firefox changed since 61.0b13.) a basic fetch request is really simple to set up. have a look at the following code: fetch('http://example.com/movies.json') .then(response => response.json()) .then(data => console.log(data)); here we are fetching a json file across the network and printing it to the console. the simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response (a response object). this is just an http res...
...nd response objects.) note: the body mixin also has similar methods to extract other types of body content; see the body section for more. fetch requests are controlled by the connect-src directive of content security policy rather than the directive of the resources it's retrieving. supplying request options the fetch() method can optionally accept a second parameter, an init object that allows you to control a number of different settings: see fetch() for the full options available, and more details. // example post method implementation: async function postdata(url = '', data = {}) { // default options are marked with * const response = await fetch(url, { method: 'post', // *get, post, put, delete, etc. mode: 'cors', // no-cors, *cors, same-origin cache: 'no-cache',...
...ch(url, { method: 'post', // *get, post, put, delete, etc. ...
...And 11 more matches
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
in this guide we will be exploring the three properties that are applied to flex items, which enable us to control the size and flexibility of the items along the main axis — flex-grow, flex-shrink, and flex-basis. fully understanding how these properties work with growing and shrinking items is the real key to mastering flexbox. ...
... .item { flex: 2 1 auto; } if you have read the article basic concepts of flexbox, then you will have already had an introduction to the properties. ...
... 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 of the soft wrapping opportunities available to it, becoming as small as it can be without overflowing. this then, is the min-content size of that string. essentially, the longest wor...
...And 11 more matches
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
#d9480f; } .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 10px; } <div class="wrapper"> <div>one</div> <div>two</div> <div>three</div> <div>four</div> <div>five</div> </div> default rules for auto-placement as you can see with the above example, if you create a grid all child items will lay themselves out one into each grid cell. the default flow is to arrange items by row. grid will lay an item out into each cell of row 1. if you have created additional rows using the grid-template-rows property then grid will continue placing items in these rows. if the grid does not have enough rows in the explicit grid to place all of the items new implicit rows will be created. sizing rows in the implicit grid the default for automatically created ...
...rows property then grid will continue placing items in these rows. if the grid does not have enough rows in the explicit grid to place all of the items new implicit rows will be created. sizing rows in the implicit grid the default for automatically created rows in the implicit grid is for them to be auto-sized. this means that they will contain the content added to them without causing an overflow. you can however control the size of these rows with the property grid-auto-rows. to cause all created rows to be 100 pixels tall for example you would use: * {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; pa...
... <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; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ff...
...And 11 more matches
Using CSS gradients - CSS: Cascading Style Sheets
n in a clockwise direction. negative angles run in the counterclockwise direction. declaring colors & creating effects all css gradient types are a range of position-dependent colors. the colors produced by css gradients can vary continuously with position, producing smooth color transitions. it is also possible to create bands of solid colors, and hard transitions between two colors. ...
...to fine-tune their locations, you can give each one zero, one, or two percentage or, for radial and linear gradients, absolute length values. ...
...nsition to the adjacent color stop's color through the adjacent color stop's first position. ...
...And 11 more matches
text-transform - CSS: Cascading Style Sheets
the text-transform css property specifies how to capitalize an element's text. it can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. it also can help improve legibility for ruby. 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 text-transform property takes into account language-specific case mapping rules such as the following: in turkic languages, like turkish (tr), azerbaijani (az), crimean tatar (crh), volga tatar (tt), and bashkir (ba), there are two kinds of i, with and without the dot, and two case pairings: i/İ and ı/i. in german (de), the ß b...
... the ij digraph becomes ij, even with text-transform: capitalize, which only puts 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), 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 some cases, a hyphen is also removed upon upperca...
...And 11 more matches
HTML attribute reference - HTML: Hypertext Markup Language
accesskey global attribute keyboard shortcut to activate or add focus to the element. action <form> the uri of a program that processes the information submitted via the form. align <applet>, <caption>, <col>, <colgroup>, <hr>, <iframe>, <img>, <table>, <tbody>, <td>, <tfoot> , <th>, <thead>, <tr> specifies the horizontal alignment of the element. allow <iframe> specifies a feature-policy for the iframe. alt <applet>, <area>, <img>, <input> alternative text in case an image can't be displayed. async <script> executes the script asynchronously. autocapitalize global attribute sets whether input is automatically capitalized when entered by user autocomplete <form>, <input>, <select>, <...
...e element. decoding <img> indicates the preferred method to decode the image. default <track> indicates that the track should be enabled unless the user's preferences indicate something different. defer <script> indicates that the script should be executed after the page has been parsed. dir global attribute defines the text direction. allowed values are ltr (left-to-right) or rtl (right-to-left) dirname <input>, <textarea> disabled <button>, <command>, <fieldset>, <input>, <keygen>, <optgroup>, <option>, <select>, <textarea> indicates whether the user can interact with the element. download <a>, <area> indicates that the hyperlink is to be used for downloading a resource. dragga...
...ements listed here. for all other elements, use the css height property. note: in some instances, such as <div>, this is a legacy attribute, in which case the css height property should be used instead. hidden global attribute prevents rendering of given element, while keeping child elements, e.g. script elements, active. high <meter> indicates the lower bound of the upper range. href <a>, <area>, <base>, <link> the url of a linked resource. hreflang <a>, <area>, <link> specifies the language of the linked resource. http-equiv <meta> defines a pragma directive. icon <command> specifies a picture which represents the command. id global attribute often used with css to sty...
...And 11 more matches
Date and time formats used in HTML - HTML: Hypertext Markup Language
601, so there can be subtle differences in how date and time strings are expected to look. character set dates and times in html are always strings which use the ascii character set. year numbers in order to simplify the basic format used for date strings in html, the specification requires that all years be given using the modern (or proleptic) gregorian calendar. while user interfaces may allow entry of dates using other calendars, the underlying value always uses the gregorian calendar. while the gregorian calendar wasn't created until the year 1582 (replacing the similar julian calendar), for html's purposes, the gregorian calendar is extended back to the year 1 c.e. make sure any older dates account for this. for the purposes of html dates, years are always at least four digits lon...
...s to the algorithm (taking a leap year when the year can be divided by 400, and skipping leap years when the year is divisible by 100) help to bring the average even closer to the correct number of days (365.2425 days). scientists occasionally add leap seconds to the calendar (seriously) to handle the remaining three ten-thousandths of a day and to compensate for the gradual, naturally occurring slowing of earth's rotation. while month 02, february, normally has 28 days, it has 29 days in leap years. months of the year there are 12 months in the year, numbered 1 through 12. they are always represented by a two-digit ascii string whose value ranges from 01 through 12. see the table in the section days of the month for the month numbers and their corresponding names (and lengths in days). d...
...cii string whose value ranges from 01 through 12. see the table in the section days of the month for the month numbers and their corresponding names (and lengths in days). days of the month month numbers 1, 3, 5, 7, 8, 10, and 12 are 31 days long. months 4, 6, 9, and 11 are 30 days long. month 2, february, is 28 days long most years, but is 29 days long in leap years. this is detailed in the following table. the months of the year and their lengths in days month number name (english) length in days 01 january 31 02 february 28 (29 in leap years) 03 march 31 04 april 30 05 may 31 06 june 30 07 july 31 o8 august 31 09 september 30 ...
...And 11 more matches
<img>: The Image Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › img
s so they know what the image means. alt text is also displayed on the page if the image can't be loaded for some reason: for example, network errors, content blocking, or linkrot. there are many other attributes to achieve various purposes: referrer/cors control for security and privacy: see crossorigin and referrerpolicy. use both width and height to set the intrinsic size of the image, allowing it to take up space before it loads, to mitigate content layout shifts. responsive image hints with sizes and srcset (see also the <picture> element and our responsive images tutorial). supported image formats the html standard doesn't list what image formats to support, so each user agent supports different formats. a complete guide to image formats supported by web browsers is available.
... it to take up space before it loads, to mitigate content layout shifts. responsive image hints with sizes and srcset (see also the <picture> element and our responsive images tutorial). supported image formats the html standard doesn't list what image formats to support, so each user agent supports different formats. a complete guide to image formats supported by web browsers is available. below is a list of the image formats that are most commonly used on the web, as well as some older formats that should no longer be used, despite existing content possibly still using them. abbreviation file format mime type file extension(s) browser compatibility apng animated portable network graphics image/apng .apng chrome, edge, firefox, opera, safari...
..."tainted". if the crossorigin attribute is not specified, then a non-cors request is sent (without the origin request header), and the browser marks the image as tainted and restricts access to its image data, preventing its usage in <canvas> elements. ...
...And 11 more matches
<link>: The External Resource Link element - HTML: Hypertext Markup Language
Web › HTML › Element › link
favicon.ico"> there are a number of other icon rel values, mainly used to indicate special icon types for use on various mobile platforms, e.g.: <link rel="apple-touch-icon-precomposed" sizes="114x114" href="apple-icon-114.png" type="image/png"> the sizes attribute indicates the icon size, while the type contains the mime type of the resource being linked. these provide useful hints to allow the browser to choose the most appropriate icon available. you can also provide a media type or query inside a media attribute; this resource will then only be loaded if the media condition is true. for example: <link href="print.css" rel="stylesheet" media="print"> <link href="mobile.css" rel="stylesheet" media="screen and (max-width: 600px)"> some interesting new performance and security fea...
... the crossorigin attribute indicates whether the resource should be fetched with a cors request. other usage notes: a <link> element can occur either in the <head> or <body> element, depending on whether it has a link type that is body-ok. for example, the stylesheet link type is body-ok, and therefore <link rel="stylesheet"> is permitted in the body. however, this isn't a good practice to follow; it makes more sense to separate your <link> elements from your body content, putting them in the <head>. when using <link> to establish a favicon for a site, and your site uses a content security policy (csp) to enhance its security, the policy applies to the favicon. if you encounter problems with the favicon not loading, verify that the content-security-policy header's img-src directive is no...
...butes. as this attribute is only used when rel="preload" or rel="prefetch" has been set on the <link> element. it specifies the type of content being loaded by the <link>, which is necessary for request matching, application of correct content security policy, and setting of correct accept request header. furthermore, rel="preload" uses this as a signal for request prioritization. the table below lists the valid values for this attribute and the elements or resources they apply to. value applies to audio <audio> elements document <iframe> and <frame> elements embed <embed> elements fetch fetch, xhr this value also requires <link> to contain the crossorigin attribute. ...
...And 11 more matches
Evolution of HTTP - HTTP
the http protocol used in those early phases was very simple, later dubbed http/0.9, and sometimes as the one-line protocol. http/0.9 – the one-line protocol the initial version of http had no version number; it has been later called 0.9 to differentiate it from the later versions. http/0.9 is extremely simple: requests consist of a single line and start with the only possible method get followed by the path to the resource (not the url as both the protocol, server, and port are unnecessary once connected to the server). get /mypage.html the response is extremely simple too: it only consisted of the file itself. <html> a very simple html page </html> unlike subsequent evolutions, there were no http headers, meaning that only html files could be transmitted, but no other type of docu...
...ml file was send back with the description of the problem contained in it, for human consumption. http/1.0 – building extensibility http/0.9 was very limited and both browsers and servers quickly extended it to be more versatile: versioning information is now sent within each request (http/1.0 is appended to the get line) a status code line is also sent at the beginning of the response, allowing the browser itself to understand the success or failure of the request and to adapt its behavior in consequence (like in updating or using its local cache in a specific way) the notion of http headers has been introduced, both for the requests and the responses, allowing metadata to be transmitted and making the protocol extremely flexible and extensible. with the help of the new http header...
...o transmit other documents than plain html files has been added (thanks to the content-type header). ...
...And 11 more matches
An overview of HTTP - HTTP
Web › HTTP › Overview
it is the foundation of any data exchange on the web and it is a client-server protocol, which means requests are initiated by the recipient, usually the web browser. a complete document is reconstructed from the different sub-documents fetched, for instance text, layout description, images, videos, scripts, and more. clients and servers communicate by exchanging individual messages (as opposed to a stream of data). the messages sent by the client, usually a web browser, are called requests and the messages sent by the server as an answer are called responses. designed in the early 1990s, http is an extensible protocol which has evolved over time. ...
...os). the web browser then mixes these resources to present to the user a complete document, the web page. scripts executed by the browser can fetch more resources in later phases and the browser updates the web page accordingly. a web page is a hypertext document. this means some parts of displayed text are links which can be activated (usually by a click of the mouse) to fetch a new web page, allowing the user to direct their user-agent and navigate through the web. the browser translates these directions in http requests, and further interprets the http responses to present the user with a clear response. the web server on the opposite side of the communication channel, is the server, which serves the document as requested by the client. a server appears as only a single machine virtuall...
... 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 numerous functions: caching (the cache can be public or private, like the browser cache) filtering (like an antivirus scan or parental controls) load balancing (to allow multiple servers to serve the different requests) authentication (to control access to different resources) logging (allowing the storage of historical information) basic aspects of http http is simple http is generally designed to be simple and human readable, even with the added complexity introduced in http/2 by encapsulating http messages into frames. http messages can be read and under...
...And 11 more matches
Modules - Archive of obsolete content
host application to provide us with this functionality. applications such as firefox and thunderbird are based on xulrunner. xulrunner adds a built-in object, known as components, to the global scope. this object forms the central access point for all functionality provided by the host application. a complete explanation of how to use components is out of scope for this document. ...
...unction loadscript(url) { loader.loadsubscript(url); } when a script is loaded, it is evaluated in the scope of the global object of the script that loaded it. any property defined on the global object will be accessible from both scripts: // index.js: loadscript("www.foo.com/a.js"); foo; // => 3 // a.js: foo = 3; exporting names the script loader we obtained from the components object allows us load scripts from other locations, but its api is rather limited. for instance, it does not know how to handle relative urls, which is cumbersome if you want to organize your project hierarchically. a more serious problem with the loadscript function, however, is that it evaluates all scripts in the scope of the same global object. this becomes a problem when two scripts try to define the sam...
...s", since it is overwritten by "b.js". to prevent scripts from interfering with each other, loadscript should evaluate each script to be loaded in the scope of their own global object, and then return the global object as its result. in effect, any properties defined by the script being loaded on its global object are exported to the loading script. ...
...And 10 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...
...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 it to false. note: before firefox 1.5 the preference app.extensions.version could be used t...
...cation. 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 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 compatibili...
...And 10 more matches
Tabbed browser - Archive of obsolete content
in the onload handler will be a 'tab' xul element). see tabbrowser for getbrowserfortab(). note that the code above does not work inside of the electrolysis (e10s) enabled tabs. opening a url in the correct window/tab there are methods available in chrome://browser/content/utilityoverlay.js that make it easy to open url in tabs such as openuilinkin and openuilink. ...
...the code given is for a menuitem, but will work equally well for other xul elements. this will only work in an overlay of browser.xul. xul: <menuitem oncommand="myextension.foo(even...
...the code given is for a menuitem, but will work equally well for other xul elements. this will only work in an overlay of browser.xul. xul: <menuitem oncommand="myextension.foo(event)" onclick="checkformiddleclick(this, event)" label="...
...And 10 more matches
Creating a Help Content Pack - Archive of obsolete content
original doc: http://www.mozilla.org/projects/help.../content_packs i hesitate to call it "original", tho, because i've basically rewritten the entire thing so that it's easier and faster to use to create help content. the previous document had a lot of places where ideas were simply introduced without explanation, and i've tried to go through things a bit more slowly with better descriptions. this is still very much a work in progress, tho, and i need to complete the rest of it soon (where "complete" means "use what's there that's good, build on the stuff that's not as good, and add other useful information as necessary". this document describes how to integrate html help documentation into your application using the mozilla help viewer. documentation contained in the help viewer ca...
... actually an advantage - if you make an error you'll know immediately, and you should be able to easily figure out what the problem is by directly loading the file in firefox. later, when we get to actually writing content, you'll need to know xhtml, but for now knowledge of the syntax should be enough. open up your favorite text editor and create the file content-pack.rdf. insert into it the following text: <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:nc="http://home.netscape.com/nc-rdf#"> </rdf:rdf> if you're familiar with html or xml, you might recognize this as the container element for the whole document. it serves as a wrapper around the entire contents of the file, marking it as rdf. next, you'll need to insert a rdf:descri...
...nt. it serves as a wrapper around the entire contents of the file, marking it as rdf. next, you'll need to insert a rdf:description element into the file, inside the rdf:rdf element just created: <rdf:description rdf:about="urn:root" nc:title="" nc:defaulttopic="" nc:base=""> </rdf:description> fill in the attributes as follows: rdf:about must be urn:root or your pack won't work. this attribute marks the start point in the rdf graph described by the file, and the help viewer searches for this element in order to query for further information (stored in child elements) about the content pack being parsed. nc:title is where you specify the title (e.g., "mozilla firefox help") for the help window. this attribute is re...
...And 10 more matches
splitter - Archive of obsolete content
state, substate 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 i...
... 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. 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 rig...
...imum 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 below the splitter resizes. grow the elements to the right or below the splitter do not change size (unless they are flexible) when the splitter is dragged, but instead the entire container changes size. flex the closest flexible element resizes. ...
...And 10 more matches
Common Firefox theme issues and solutions - Archive of obsolete content
ent 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 mode from a normal window properly. the resolution to this issue is to add the follo...
...s issue: http://forums.mozillazine.org/viewtopic.php?f=18&t=2131121 http://forums.mozillazine.org/viewtopic.php?f=18&t=1953371&start=60 windows 7 aero not going into full screen mode properly on win7 with aero glass support firefox doesn't always go to full screen mode from a normal window properly. the resolution to this issue is to add the following code to your browser.css file somewhere below where the main-window is made transparent to support aero glass. @media all and (-moz-windows-compositor) { /* make transition to fullscreen mode seamlessly in firefox 10+ */ #main-window[infullscreen="true"] { -moz-appearance: none; background-color: -moz-dialog!important; } } for more information about this issue please see bug 732757 and bug 732757 and this mozillazine thread. ...
...olor: -moz-dialog!important; } } for more information about this issue please see bug 732757 and bug 732757 and this mozillazine thread. mac os x os x lion missing toolbar button icons due to firefox bug 679708 and bug 702558, some toolbar buttons icons may be missing on firefox 8 and later running on mac os x lion. ...
...And 10 more matches
Windows Media in Netscape - Archive of obsolete content
. an advantage of the client-side approach is that it is also possible to detect if windows media player is installed. 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: netsc...
...at browser you are running, and what kind of windows media player technology you may have. example 1: client-side detection scripts browser architecture supports: netscapeplugin windows media player installed: true windows media scriptable: false windows media version: pluginversion a complete source code listing showing how that detection was done can be found here (devedge-temp). ...
...mplayer.ocx.7 as an argument to both these apis creates a fully usable reference to the windows media player 7 or 9 control, with all the methods and properties exposed to javascript. furthermore, you know for certain that you are working with the windows media 7 or 9 control -- there is no comparable instantiation for the windows media player 6 control. ...
...And 10 more matches
Grids - Learn web development
cally have columns, rows, and then gaps between each row and column — commonly referred to as gutters. creating your grid in css having decided on the grid that your design needs, you can use css grid layout to create that grid in css and place items onto it. we will look at the basic features of grid layout first and then explore how to create a simple grid system for your project. the following video provides a nice visual explanation of using css grid: defining a grid as a starting point, download and open the starting point file in your text editor and browser (you can also see it live here). you will see an example with a container, which has some child items. by default these display in normal flow so the boxes display one below the other. we will be working with this file fo...
...we use the grid value of the display property. as with flexbox, this switches on grid layout, and all of the direct children of the container become grid items. add this to the css inside your file: .container { display: grid; } unlike flexbox, the items will not immediately look any different. declaring display: grid gives you a one column grid, so your items will continue to display one below the other as they do in normal flow. to see something that looks more grid-like, we will need to add some columns to the grid. let's add three 200-pixel columns here. you can use any length unit, or percentages to create these column tracks. .container { display: grid; grid-template-columns: 200px 200px 200px; } add the 2nd declaration to your css rule, then reload the page, and you sh...
... <div>six</div> <div>seven</div> </div> .container { display: grid; grid-template-columns: 200px 200px 200px; } flexible grids with the fr unit in addition to creating grids using lengths and percentages, we can use the fr unit to flexibly size grid rows and columns. this unit represents one fraction of the available space in the grid container. change your track listing to the following definition, creating three 1fr tracks. .container { display: grid; grid-template-columns: 1fr 1fr 1fr; } you should now see that you have flexible tracks. the fr unit distributes space in proportion, therefore you can give different positive values to your tracks, for example if you change the definition like so: .container { display: grid; grid-template-columns: 2fr 1fr 1fr...
...And 10 more matches
Choosing the right approach - Learn web development
passed to a third-party library. browser compatibility really good general support, although the exact support for callbacks in apis depends on the particular api. refer to the reference documentation for the api you're using for more specific support info. further information introducing asynchronous javascript, in particular async callbacks settimeout() settimeout() is a method that allows you to run a function after an arbitrary amount of time has passed. useful for... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations yes yes (recursive timeouts) yes (nested timeouts) no code example here the browser will wait two seconds before executing the anonymous function, then will disp...
...rt full support compatibility unknown compatibility unknownsee implementation notes.see implementation notes. further information cooperative asynchronous javascript: timeouts and intervals, in particular settimeout() settimeout() reference setinterval() setinterval() is a method that allows you to run a function repeatedly with a set interval of time between each execution. not as efficient as requestanimationframe(), but allows you to choose a running rate/frame rate. useful for... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no yes no (unless it is the same one) no code ex...
... function repeatedly with a set interval of time between each execution. not as efficient as requestanimationframe(), but allows you to choose a running rate/frame rate. useful for... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no yes no (unless it is the same one) no code example the following function creates a new date() object, extracts a time string out of it using tolocaletimestring(), and then displays it in the ui. we then run it once per second using setinterval(), creating the effect of a digital clock that updates once per second (see this live, and also see the source): function displaytime() { let date = new date(); let time = date.tolocaletimestring(); documen...
...And 10 more matches
Basic math in JavaScript — numbers and operators - Learn web development
d decimal places, for example 12.5, and 56.7786543. doubles are a specific type of floating point number that have greater precision than standard floating point numbers (meaning that they are accurate to a greater number of decimal places). we even have different types of number systems! decimal is base 10 (meaning it uses 0–9 in each column), but we also have things like: binary — the lowest level language of computers; 0s and 1s. octal — base 8, uses 0–7 in each column. hexadecimal — base 16, uses 0–9 and then 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 ...
...rs 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 values. it's all numbers to me let's quickly play with some numbers to reacquaint ourselves with the basic syntax we need. enter the commands listed below into your developer tools javascript console. first of all, let's declare a couple of variables and initialize them with an integer and a float, respectively, then type the variable names back in to check that everything is in order: let myint = 5; let myfloat = 6.667; myint; myfloat; number values are typed in without quote marks — try declaring and initializing a couple more variables...
...ack in to check that everything is in order: let myint = 5; let myfloat = 6.667; myint; myfloat; number values are typed in without quote marks — try declaring and initializing a couple more variables containing numbers before you move on. now let's check that both our original variables are of the same datatype. there is an operator called typeof in javascript that does this. enter the below two lines as shown: typeof myint; typeof myfloat; you should get "number" returned in both cases — this makes things a lot easier for us than if different numbers had different data types, and we had to deal with them in different ways. phew! useful number methods the number object, an instance of which represents all standard numbers you'll use in your javascript, has a number of useful...
...And 10 more matches
Ember app structure and componentization - Learn web development
planning out the layout of the todomvc app in the last article we set up a new ember project, then added and configured our css styles. at this point we add some html, planning out the structure and semantics of our todomvc app. the landing page html of our application is defined in app/templates/application.hbs. this already exists, and its contents currently look like so: {{!-- the following component displays ember's default welcome message. --}} <welcomepage /> {{!-- feel free to remove this! --}} {{outlet}} <welcomepage /> is a component provided by an ember addon that renders the default welcome page we saw in the previous article, when we first navigated to our server at localhost:4200. however, we don't want this. instead, we want it to contain the todomvc app structure...
...el free to remove this! --}} {{outlet}} <welcomepage /> is a component provided by an ember addon that renders the default welcome page we saw in the previous article, when we first navigated to our server at localhost:4200. however, we don't want this. instead, we want it to contain the todomvc app structure. to start with, delete the contents of application.hbs and replace them with the following: <section class="todoapp"> <h1>todos</h1> <input class="new-todo" aria-label="what needs to be done?" placeholder="what needs to be done?" autofocus > </section> note: aria-label provides a label for assistive technology to make use of — for example, for a screenreader to read out. this is useful in such cases where we have an <input> being used with no corresponding...
...r class="footer"> <span class="todo-count"> <strong>0</strong> todos left </span> <ul class="filters"> <li> <a href="#">all</a> <a href="#">active</a> <a href="#">completed</a> </li> </ul> <button type="button" class="clear-completed"> clear completed </button> </footer> </section> the rendered output should now be as follows: this looks pretty complete, but remember that this is only a static prototype. now we need to break up our html code into dynamic components; later we'll turn it into a fully interactive app. looking at the code next to the rendered todo app, there are a number of ways we could decide how to break up the ui, but let's plan on splitting the html out into the following components: the comp...
...And 10 more matches
React interactivity: Editing, filtering, conditional rendering - Learn web development
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. ...
...<todo /> components as a prop in the same way we did with deletetask: const tasklist = tasks.map(task => ( <todo id={task.id} name={task.name} completed={task.completed} key={task.id} toggletaskcompleted={toggletaskcompleted} deletetask={deletetask} edittask={edittask} /> )); now open todo.js. we’re going to do some refactoring. ...
...ng. a ui for editing in order to allow users to edit a task, we have to provide a user interface for them to do so. first, import usestate into the todo component like we did before with the app component, by updating the first import statement to this: import react, { usestate } from "react"; we'll now use this to set an isediting state, the default state of which should be false. ...
...And 10 more matches
Deploying our app - Learn web development
nd colleagues. deploying to hosting tends to be at the tail-end of the project life cycle, but with services such as netlify bringing down the cost of deployments (both in financial terms and also the time required to actually deploy) it's possible to deploy during development to either share work in progress or to have a pre-release for some other purpose. netlify, amongst other things, also allows you to run pre-deployment tasks, which in our case means that all the production code build processes can be performed inside of netlify and if the build is successful, the website changes will be deployed. although netlify offers a drag and drop deployment service, we are intending to trigger a new deployment to netlify each time we push to a github repo. it's exactly these kinds of connected...
...ice to get into the habit of setting up — across all our projects, we can then rely on npm run build to always do the complete build step, without needing to remember the specific build command arguments for each project. open the package.json file in your project's root directory, and find the scripts property. we'll add a build command that we can run to build our code. ...
... project's root directory, and find the scripts property. we'll add a build command that we can run to build our code. add the following line to your project now: "scripts": { ... "build": "parcel build src/index.html" } note: if the scripts property already has a command inside it, put a comma at the end of it. keep the json valid. ...
...And 10 more matches
Mozilla’s UAAG evaluation report
not rated na: not applicable document under construction guideline 1. support input and output device-independence. checkpoint title status notes/plans 1.1 full keyboard access. (p1) vg we have some remaining bugs, and some keyboard usability issues, but in general mozilla now has keyboard equivalents for almost everything. most browsers do not allow the user to select text with the keyboard alone. we intend to do this with a caret browsing feature. 1.2 activate event handlers. (p1) p onmouseover, onmousedown, onmouseup, onmousemove, onclick, ondbclick: no keyboard support onfocus and onblur: cannot be activated with pointer 1.3 provide text messages. (p1) c status line and alert boxes used to convey messages...
...t: supported abbr element: supported abbr attribute for td/th: not supported summary for table: supported title for frame: ? longdesc for frame: not supported, see bug 3658 noframe for frame: must use user style sheets to render this. a ui for this would be good. noscript for script: must use user style sheets to render this. a ui for this would be good. 2.4 allow time-independent interaction. (p1) nr need to look into this 2.5 make captions, transcripts available. (p1) na this relates to multimedia 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 presen...
... title for frame: ? longdesc for frame: not supported, see bug 3658 noframe for frame: must use user style sheets to render this. a ui for this would be good. noscript for script: must use user style sheets to render this. a ui for this would be good. 2.10 toggle placeholders. (p3) ni 2.11 alert unsupported language. (p3) nr ? guideline 3. allow configuration not to render some content that may reduce accessibility. checkpoint title status notes/plans 3.1 toggle background images. (p1) c preferences, appearance, colors - "use my chosen colors, ignoring the colors and background image specified" 3.2 toggle audio, video, animated images. (p1) p animated images can be made still with the escap...
...And 10 more matches
Configuring Build Options
note: do not make substantive changes to this document without consulting benjamin smedberg <benjamin@smedbergs.us> or one of the build-config peersthis document details how to configure firefox builds. 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. using a mozconfig configuration file the choice of which mozilla application to build and other configuration options can be configured in ...
...zconfig file: echo "# my first mozilla config" > mozconfig if your mozconfig isn't in your source directory, you can also use the mozconfig environment variable to specify the path to your mozconfig. the path you specify must be an absolute path or else client.mk will not find it. this is useful if you choose to have multiple mozconfig files for different applications or configurations (see below for a full example). note that in the export example below the filename was not mozconfig. regardless of the name of the actual file you use, we refer to this file as the mozconfig file in the examples below. setting the mozconfig path: export mozconfig=$home/mozilla/mozconfig-firefox calling the file .mozconfig (with a leading dot) is also supported, but this is not recommended because it m...
...s 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 your mozconfig allows you to change the objdir: mk_add_options moz_objdir=@topsrcdir@/obj-@config_guess@ it is a good idea to have your objdir name start with obj so that mercurial ignores it. sometimes it can be useful to build multiple versions of the source (such as with and without diagnostic asserts). to avoid the time it takes to do a full rebuild, you can create multiple moz...
...And 10 more matches
Multiple Firefox profiles
mizations, add-ons, and other personalizations 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. reasons to have multiple profiles the casual user may want to have different profiles for work and personal use, or different family members. having different profiles would help separate work and personal life, or allow each family member to have his or her own set of bookmarks, settings, and add-ons. web developers might want a secondary profile for testing websites, apps, or other projects on different firefox channels. for example, you might want to have some extensions installed for web development, but not for general-purpose web browsing. while using the nightly channel, you may encounter some add-ons tha...
...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 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 co...
...ou 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 use. press the “launch profile in new browser” button next to it. windows wind...
...And 10 more matches
DMD
active while running it, you just need to set the environment variable dmd=1 when running. for instance, on osx, you can run something like: dmd=1 /applications/firefox\ nightly.app/contents/macos/firefox you can tell it is working by going to about:memory and looking for "save dmd output". if dmd has been properly enabled, the "save" button won't be grayed out. look at the "trigger" section below to see the full list of ways to get a dmd report once you have it activated. note that stack information you get will likely be less detailed, due to being unable to symbolicate. you will be able to get function names, but not line numbers. desktop firefox (linux) build build firefox with these options: ac_add_options --enable-dmd if building via try server, modify browser/config/mozconfigs...
...md button (depending on how old your build is, it might be labelled "save" or "analyze reports" or "dmd"). the button won't be present in non-dmd builds, and will be grayed out in dmd builds if dmd isn't enabled 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 emp...
...utput 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 signal 34 to the firefox process, e.g. with the following command. $ killall -34 firefox each one of these steps triggers all the memory reporters and then dmd analyzes the reports, printing commentary like this: dmd[5222] opened /tmp/dmd-1414556492-5222.json.gz for writing dmd[5222] dump 1 { dmd[5222] constructing the heap block list... dmd[5222] constructing the stack trace table... dmd[5222] constructing the stack frame table... dmd[5...
...And 10 more matches
Scripting Java
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). ...
...packages and classes external packages and classes can also be used as in rhino. make sure your .jar or .class file is on you classpath then you may import them into your javascript application. these packages are likely not in the java package, so you'll need to prefix the package name with "packages." for example, to import the org.mozilla.javascript package you could use importpackage() as follows: $ java org.mozilla.javascript.tools.shell.main js> importpackage(packages.org.mozilla.javascript); js> context.currentcontext; org.mozilla.javascript.context@bb6ab6 occasionally, you will see examples that use the fully qualified name of the package instead of importing using the importpackage() method. this is also acceptable, it just takes more typing. using a fully qualified name, the abo...
...cript.tools.shell.main js> importpackage(packages.org.mozilla.javascript); js> context.currentcontext; org.mozilla.javascript.context@bb6ab6 occasionally, you will see examples that use the fully qualified name of the package instead of importing using the importpackage() method. this is also acceptable, it just takes more typing. ...
...And 10 more matches
How to build an XPCOM component in JavaScript
ersion of xpcomviewer that works with firefox 1.5 from mozdev mirrors. if an interface exists that meets your needs, then you do not need to write an idl, or compile a typelib, and may skip to the next section. if you don't find a suitable pre-existing interface, then you must define your own. xpcom uses a dialect of idl to define interfaces, called xpidl. here's the xpidl definition for our helloworld component: helloworld.idl #include "nsisupports.idl" [scriptable, uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)] interface nsihelloworld : nsisupports { string hello(); }; note that you must generate a new uuid for each xpcom component that you create. see generating guids for more information. compiling the typelib your interface definition must be compiled into a binary format (xpt) i...
...6 within the zip into the bin directory of the gecko sdk. note: the mac version of the sdk provided for download is powerpc-only. if you need an intel version, you'll need to compile it yourself as described on that page. execute this command to compile the typelib. here, {sdk_dir} is the directory in which you unpacked the gecko sdk. {sdk_dir}/bin/xpidl -m typelib -w -v -i {sdk_dir}/idl -e helloworld.xpt helloworld.idl note: on windows you must use forward slashes for the include path. note: (the -i flag is an uppercase i, not a lowercase l.) this will create the typelib file helloworld.xpt in the current working directory. for a new component in firefox/thunderbird/b2g if you are adding a new feature to applications in the mozilla-central repository, you can create a makefile listi...
...the imported library contains functions for gen...
...And 10 more matches
Index - Firefox Developer Tools
singly "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 inspector, devtools, guide, tools the accessibility inspector provides a means to access important information exposed to assistive technologies on the current page via the accessibility tree, allowing you to check what's missing or otherwise needs attention. this article takes you through the main features of the accessibility inspector and how to use it. 4 color vision simulation accessibility, accessibility inspector, color blindness, devtools, guide, simulation, tools the simulator in the accessibility inspector in firefox developer tools lets you see what a web page...
...inspector dom, dom:tools, dom_inspector, extensions, extensions:tools, themes, themes:tools, tools, web development, web development:tools, xul, xul:tools the dom inspector (also known as domi) is a developer tool used to inspect, browse, and edit the document object model of documents - usually web pages or xul windows. the dom hierarchy can be navigated using a two-paned window that allows a variety of different views on the document and all nodes within. 7 dom inspector faq dom_inspector the file menu contains approaches which will allow you to inspect a document. 8 dom inspector internals code, tools, internals, organisation, source there are three main facets to dom inspector. the one you are likely to be most familiar with is its inspe...
... tree map view the tree map view provides a visual representation of the snapshot, that helps you quickly get an idea of which objects are using the most memory. 45 migrating from firebug firebug, migration when migrating from firebug to the firefox developer tools, you may wonder where the features you loved in firebug are available in the developer tools. the following list aims to help firebug users to find their way into the developer tools. 46 network monitor debugging, dev tools, firefox, guide, networking, tools, l10n:priority the network monitor shows you all the network requests firefox makes (for example, when it loads a page, or due to xmlhttprequests), how long each request takes, and details of each request. 47 insp...
...And 10 more matches
BiquadFilterNode() - Web APIs
the biquadfilternode() constructor of the web audio api creates a new biquadfilternode object, which represents a simple low-order filter, and is created using the audiocontext.createbiquadfilter() method. syntax var biquadfilternode = new biquadfilternode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options optional options are as follows: type: one of "lowpass", "highpass", "bandpass", "lowshelf", "highshelf", "peaking", "notch", "allpass". the meaning of the other options depends on the value of this one. ...
... biquadfilternode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options optional options are as follows: type: one of "lowpass", "highpass", "bandpass", "lowshelf", "highshelf", "peaking", "notch", "allpass". the meaning of the other options depends on the value of this one. the defaults for all are as follows: q: 1 detune: 0 frequency: 350 gain: 0 lowpass: (default) allows frequencies below a cutoff frequency to pass through, and attenuates frequencies above the cutoff. this is a standard second-order resonant lowpass filter with 12db/octave rolloff. q: controls how peaked the response will be at the cutoff frequency. a large value makes the response more peaked. p...
...it implements a standard second-order resonant highpass filter with 12db/octave rolloff. q: controls how peaked the response will be at the cutoff frequency. a large value makes the response more peaked. ...
...And 10 more matches
WebGL model view projection - Web APIs
o make them useful for rendering complicated 3d scenes. these composed matrices ultimately move the original model data around into a special coordinate space called clip space. this is a 2 unit wide cube, centered at (0,0,0), and with corners that range range from (-1,-1,-1) to (1,1,1). this clip space is compressed down into a 2d space and rasterized into an image. the first matrix discussed below is the model matrix, which defines how you take your original model data and move it around in 3d world space. the projection matrix is used to convert world space coordinates into clip space coordinates. a commonly used projection matrix, the perspective projection matrix, is used to mimic the effects of a typical camera serving as the stand-in for the viewer in the 3d virtual world. the view ma...
...into clip space coordinates. a commonly used projection matrix, the perspective projection matrix, is used to mimic the effects of a typical camera serving as the stand-in for the viewer in the 3d virtual world. the view matrix is responsible for moving the objects in the scene to simulate the position of the camera being changed, altering what the viewer is currently able to see. the sections below offer an in-depth look into the ideas behind and implementation of the model, view, and projection matrices. these matrices are core to moving data around on the screen, and are concepts that transcend individual frameworks and engines. clip space in a webgl program, data is typically uploaded to the gpu with its own coordinate system and then the vertex shader transforms those points into a sp...
... put our data into the clip space coordinate system directly. normally model data is used that is in some arbitrary coordinate system, and is then transformed using a matrix, converting the model coordinates into the clip space coordinate system. for this example, it's easiest to illustrate how clip space works by simply using model coordinate values ranging from (-1,-1,-1) to (1,1,1). 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...
...And 10 more matches
Basic concepts behind Web Audio API - Web APIs
d how the features of the web audio api work, to help you make informed decisions while designing how audio is routed through your app. it won't turn you into a master sound engineer, but it will give you enough background to understand why the web audio api works like it does. audio graphs the web audio api involves handling audio operations inside an audio context, and has been designed to allow 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...
.... 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. create effects nodes, such as reverb, biquad filter, panner, or compressor. choose the final destination for the audio, such as the user's computer speakers. establish connections from the audio sources through zero or more effects, eventual...
...eventually ending at the chosen destination. channel notation the number of audio channels available on a signal is frequently presented in a numeric format, such as 2.0 or 5.1. this is called channel notation. the first number is the number of full frequency range audio channels that the signal includes. the number after the period indicates the number of those channels which are reserved for low-frequency effect (lfe) outputs; these are often referred to as subwoofers. each input or output is composed of one or more audio channels, which together represent a specific audio layout. any discrete channel structure is supported, including mono, stereo, quad, 5.1, and so on. audio sources can be obtained in a number of ways: sound can be generated directly in javascript by an audio ...
...And 10 more matches
Using XMLHttpRequest - Web APIs
s data exchange were xml handling responses there are several types of response attributes defined by the living standard specification for the xmlhttprequest() constructor. these tell the client making the xmlhttprequest important information about the status of the response. some cases where dealing with non-text response types may involve some manipulation and analysis are outlined in the following sections. analyzing and manipulating the responsexml property if you use xmlhttprequest to get the content of a remote xml document, the responsexml property will be a dom object containing a parsed xml document. this could prove difficult to manipulate and analyze. there are four primary ways of analyzing this xml document: using xpath to address (or point to) parts of it. manually pars...
...pe = "arraybuffer"; oreq.send(); for more examples check out the sending and receiving binary data page monitoring progress xmlhttprequest 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); o...
...f bytes transferred so far in the event's total and loaded fields. however, if the lengthcomputable field is false, the total length is not known and will be zero. progress events exist for both download and upload transfers. the download events are fired on the xmlhttprequest object itself, as shown in the above sample. the upload events are fired on the xmlhttprequest.upload object, as shown below: var oreq = new xmlhttprequest(); oreq.upload.addeventlistener("progress", updateprogress); oreq.upload.addeventlistener("load", transfercomplete); oreq.upload.addeventlistener("error", transferfailed); oreq.upload.addeventlistener("abort", transfercanceled); oreq.open(); note: progress events are not available for the file: protocol. note: starting in gecko 9.0, progress events can now be...
...And 10 more matches
Web accessibility for seizures and physical reactions - Accessibility
f venetian blinds. certain visual patterns, especially stripes of contrasting colors. that same article continues that many factors must combine to trigger the photosensitive reaction. of note is that it includes the wavelength of light as a possible factor; wavelengths in the red part of the spectrum seem to be especially problematic. in the article, "understanding wcag 2.0 three flashes or below threshold" notes generally that: “individuals who have photosensitive 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 ...
...sical response possible from flashing, flickering, blnking, and other such stimuli. in 1997, a japanese cartoon featured an animated "virus bomb". some of the children watching the cartoon reacted by having seizures, others by suffering nausea, shaking, and vomitting blood. the reactions from the children were so severe, they had to be rushed to the emergency room. the physical disorders listed below are all possible consequences: each of these physical reactions may be so severe as to be incapacitating. seizures vestibuler disordera migraines nausea vomiting flashing, blinking, & flickering although "flashing" and "blinking" are sometimes used interchangably, they are not the same. according to the w3c, blinking is a distraction problem, whereas flashing refers to content that occu...
... flashing, blinking, & flickering although "flashing" and "blinking" are sometimes used interchangably, they are not the same. according to the w3c, blinking is a distraction problem, whereas flashing refers to content that occurs more than 3 times per second, is large enough, and bright enough. section 508 prohibits flickering effects with a frequency greater than 3 hz (flickers per second) and lower than 55 hz. the epilepsy foundation's article "take advantage of media queries with <style> in setting up media queries, you are enabling controls by the user; these controls are made available in the browser or in the os. see the mdn document, "accessibility: what users can to to browse more safely" to see more details of how a user accesses the controls. prefers-reduced-motion support for ...
...And 10 more matches
Constraint validation - Developer guides
what is done on the client side. intrinsic and basic constraints in html5, basic constraints are declared in two ways: by choosing the most semantically appropriate value for the type attribute of the <input> element, e.g., choosing the email type automatically creates a constraint that checks whether the value is a valid e-mail address. by setting values on validation-related attributes, allowing basic constraints to be described in a simple way, without the need for javascript. semantic input types the intrinsic constraints for the type attribute are: input type constraint description associated violation <input type="url"> the value must be an absolute url, as defined in the url living standard. typemismatch constraint violation <input t...
...ny 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. ...
... 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. ...
...And 10 more matches
<input type="datetime-local"> - HTML: Hypertext Markup Language
wser; at the moment support is patchy, with only chrome/opera 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 ...
...ore widely supported than datetime-local. some browsers may resort to a text-only input element that validates that the results are legitimate date/time values before letting them be delivered to the server, as well, but you shouldn't rely on this behavior since you can't easily predict it. for those of you not using a supporting browser, the chrome/opera datetime-local control looks like the below screenshot. clicking the down arrow on the right hand side brings up a date picker to allow you to choose a date; you have to enter the time manually. the edge datetime-local control looks like the below; clicking the date and the time parts of the value bring up two separate pickers for you, so you can easily set both the date and the time. this is somewhat like having date and time widgets b...
...ontrol.value = '2017-06-01t08:30'; there are several methods provided by javascript's date that can be used to convert numeric date information into a properly-formatted string, or you can do it manually. for example, the date.toisostring() method can be used for this purpose. additional attributes in addition to the attributes common to all <input> elements, datetime-local inputs offer the following attributes: attribute description max the latest date and time to accept min the earliest date and time to accept step the stepping interval to use for this input, such as when clicking arrows on spinner controls or performing validation max the latest date and time to accept. if the value entered into the element is later than this ...
...And 10 more matches
<input type="month"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › month
the value is a string whose value is in the format "yyyy-mm", where yyyy is the four-digit year and mm is the month 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. the control's ui varies in general from browser to browser; at the moment support is patchy, with only chrome/opera and edge on desktop — and most modern mobile browser versions — having usable implementations. ...
...rome/opera and edge on desktop — and most modern mobile browser versions — having usable implementations. in browsers that don't support month inputs, the control degrades gracefully to a simple <input type="text">, although there may be automatic validation of the entered text to ensure it's formatted as expected. for those of you using a browser that doesn't support month, the screenshot below shows what it looks like in chrome and opera. clicking the down arrow on the right hand side brings up a date picker that lets you select the month and year. the microsoft edge month control looks like this: value a domstring representing a month and year, or empty. events change and input supported common attributes autocomplete, list, readonly, and step...
...nting a month and year, or empty. events change and input supported common attributes autocomplete, list, readonly, and step. idl attributes value methods select(), stepdown(), stepup(). value a domstring representing the value of the month and year entered into the input, in the form yyyy-mm (four or more digit year, then a hyphen ("-"), followed by the two-digit month). the format of the month string used by this input type is described in format of a valid local month string in date and time formats used in html. you can set a default value for the input control by including a month and year inside the value attribute, like so: <label for="bday-month">what month were you born in?</label> <input id="bday-month" type="month" name="bd...
...And 10 more matches
<input type="text"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › text
ntered into the text field. you can retrieve this using the value property in javascript. let thetext = mytextinput.value; if no validation constraints are in place for the input (see validation for more details), the value may be an empty string (""). ...
...a global attribute which is used to indicate whether or not to enable spell checking for an element. it can be used on any editable content, but here we consider specifics related to the use of spellcheck on <input> elements. the permitted values for spellcheck are: false disable spell checking for this element. true enable spell checking for this element. "" (empty string) or no value follow the element's default behavior for spell checking. this may be based upon a parent's spellcheck setting or other factors. an input field can have spell checking enabled if it doesn't have the readonly attribute set and is not disabled. the value returned by reading spellcheck may not reflect the actual state of spell checking within a control, if the user agent's preferences override the setti...
...pell checking. this may be based upon a parent's spellcheck setting or other factors. an input field can have spell checking enabled if it doesn't have the readonly attribute set and is not disabled. the value returned by reading spellcheck may not reflect the actual state of spell checking within a control, if the user agent's preferences override the setting. non-standard attributes the following non-standard attributes are also available on some browsers. as a general rule, you should avoid using them unless it can't be helped. attribute description autocorrect a string indicating whether or not autocorrect is on or off. safari only. mozactionhint a string indicating the type of action that will be taken when the user presses the enter or retur...
...And 10 more matches
CSP: script-src - HTTP
urls loaded directly into <script> elements, but also things like inline script event handlers (onclick) and xslt stylesheets which can trigger script execution. csp version 1 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the script-src policy: content-security-policy: script-src <source>; content-security-policy: script-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a...
...: url scheme. mail.example.com:443: matches all attempts to access port 443 on mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a scheme such as http: or https:. the colon is required. unlike other values below, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. f...
...es shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' ...
...And 10 more matches
CSP: style-src - HTTP
the http content-security-policy (csp) style-src directive specifies valid sources for stylesheets. csp version 1 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the style-src policy: content-security-policy: style-src <source>; content-security-policy: style-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as the port number, indicating that all leg...
...: url scheme. mail.example.com:443: matches all attempts to access port 443 on mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a scheme such as http: or https:. the colon is required. unlike other values below, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. f...
...es shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' ...
...And 10 more matches
Introduction to using XPath in JavaScript - XPath
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 its child nodes. the doc...
...section in the appendix for details. resulttype: a constant that specifies the desired result type to be returned as a result of the evaluation. the most commonly passed constant is xpathresult.any_type which will return the results of the xpath expression as the most natural type. there is a section in the appendix which contains a full list of the available constants. they are explained below in the section "specifying the return type." result: if an existing xpathresult object is specified, it will be reused to return the results. specifying null will create a new xpathresult object. return value returns xpathresult, which is an xpathresult object of the type specified in the resulttype parameter. the xpathresult interface is defined here. implementing a default namespace resolv...
... return type the returned variable xpathresult from document.evaluate can either be composed of individual nodes (simple types), or a collection of nodes (node-set types). ...
...And 10 more matches
Enhanced Extension Installation - Archive of obsolete content
the state of the world install locations in firefox 1.0 extensions can be installed into only two locations: the firefox user's profile directory directory, e.g. ~/.mozilla/firefox/abcdefgh.default/extensions/ the firefox application directory, e.g. c:\program files\mozilla firefox\extensions extension metadata the extension system stores metadata in both of the two locations, in the following files: <location>/extensions/extensions.rdf - an xml/rdf datasource listing all the extensions installed at that location. <location>/extensions.ini - an ini manifest listing the directories for all the extensions and themes at the location (used by the component manager, preferences system, chrome registry etc to locate files during the startup process). in the profile directory, the fi...
... fully, rather than awaiting the next restart, since themes do not supply xpcom components, preferences defaults etc. for extensions, on the next startup, the startup system notices the presence of the .autoreg file and starts the extension manager with a "dirty" flag, telling it to finish any install operations that may be pending. the extension manager loads the xml/rdf datasources (this is allowable and necessary because a major change has happened) and gets a list of all items that need to be installed (tracked using a tobeinstalled flag on the item in the datasource). it locates the staged copy of the xpi file, extracts its contents (logging file additions as it goes into {guid}/uninstall/uninstall), loads the install manifest file and copies all metadata into the appropriate datasourc...
...ds and the needs of other applications may vary in the future, since we've already effectively generalized the concept of an install location, we can make this set configurable by applications and extensions. to this end, we scan the category extension-install-locations as the extension system is started (after profile initialization) and add these to our internal set. extension metadata the following files are now used to hold metadata: <profile>/extensions.ini -active items this file contains a list of active extension directories (i.e. directories to extensions that are enabled only), to be used by the xredirprovider during startup to locate components, preferences and chrome manifests. the format here is similar to firefox 1.0 except there is no longer a count value that needs to b...
...And 9 more matches
JavaScript crypto - Archive of obsolete content
. be aware that this feature may cease to work at any time. warning: the features mentioned in this article are deleted proprietary mozilla extensions, and are not supported in any other browser. they won't work in firefox 34 or later. use <keygen> or the future web crypto api instead. using the mozilla crypto object from javascript mozilla defines a special javascript object to allow web pages access to certain cryptographic-related services. these services are a balance between the functionality web pages need and the requirement to protect users from malicious web sites. most of these services are available via the dom window object as window.crypto. services are provided to enable: smart card events, generating certificate requests, importing user certs, generating random...
... tell the crypto system you are interested by setting window.crypto.enablesmartcardevents to true. you can then register event handlers for these events with the document.addeventlistener() method. two smart card related events are generated: smartcard-insert when smartcards are inserted, and smartcard-remove when smartcards are removed. web sites which use ssl clientauth login could use the following code to refresh the page on token insertions and removals: <!doctype html> <p>... <script> function onsmartcardchange() { window.location.reload(); } function register() { window.crypto.enablesmartcardevents = true; document.addeventlistener("smartcard-insert", onsmartcardchange, false); document.addeventlistener("smartcard-remove", onsmartcardchange, false); } function deregister() {...
...rdchange, false); } function deregister() { document.removeeventlistener("smartcard-insert", onsmartcardchange, false); document.removeeventlistener("smartcard-remove", onsmartcardchange, false); } document.body.onload = register; document.body.onunload = deregister; </script> with the above example, your web site will automatically reload anytime a smartcard is inserted or removed. this allows the page to automatically login and logout based on the presence of the smartcard. generating keys and issuing user certificates there are several crypto object methods used in generating keys for certificates: generatecrmfrequest(), importusercertificates(). the generatecrmfrequest() function generates a key and creates a crmf request object. this object can be passed to a ca using a webform...
...And 9 more matches
Tamarin build documentation - Archive of obsolete content
tamarin source versions the following instructions are for obtaining and building the tamarin central source code. for instructions on tamarin tracing, please see tamarin tracing build documentation. supported platforms tamarin currently supports the following operating systems and/or architectures. windows 32 and 64 bit mac osx 10.4, 10.5 on ppc mac osx 10.5, 10.6 on intel linux 32 and 64 bit solaris 10 on sparc android 2.2 on arm windows mobile 6.5 mips (linux) sh4 (linux) getting the tamarin source the tamarin source resides in mercurial at tamarin central. active development source resides at tamarin redux. in this document replace instances of tamarin-central with tamarin-redux to operate in the redux repository. ...
...c osx 10.5, 10.6 on intel linux 32 and 64 bit solaris 10 on sparc android 2.2 on arm windows mobile 6.5 mips (linux) sh4 (linux) getting the tamarin source the tamarin source resides in mercurial at tamarin central. active development source resides at tamarin redux. in this document replace instances of tamarin-central with tamarin-redux to operate in the redux repository. use the following command to create a copy of the tamarin repository: $ hg clone http://hg.mozilla.org/tamarin-central tamarin-central tips for working with mercurial can be found here. building tamarin building tamarin will create all the libraries for the avmplus and garbage collector (mmgc), and create a standalone executable (shell) for executing files in the abc file format. running the shell without ...
... $ ../configure.py --mac-sdk=105 --target=x86_64-darwin if asc is not set, you will need to add asc.jar to the utils directory in tamarin-redux (bug 631641). download ftp://ftp.mozilla.org/pub/js/tamarin/builds/asc/latest/asc.jar put it in utils/ building tamarin for android 2.3.3 on mac public sdk/ndk setup to build tamarin for android you will need an sdk/ndk. the setup procedure below creates an android sdk/ndk entirely from publicly available sources. this sdk/ndk *must* be used if you've cloned tamarin at changeset 5844:92ad3ca84a0b or later and will be using the cross-compile build method. steps to create a public sdk/ndk tree on a mac: - create an sdk/ndk top folder under your main volume named /android-public. - download the android 2.3.3 mac sdk zip file from http://d...
...And 9 more matches
Document Object Model - Archive of obsolete content
in a browser context, the window is the global object, and the same is also true for xul. naturally, this global object will be different for each window. each frame will also have a separate window object. the window is often referred to using the window property, although this is optional. sometimes, this is done just to clarify the scope of the method you are referring to. ...
... function gettext(){ return "message"; } alert(gettext()); alert(window.gettext()); thus, if you want to access variables or call a function declared in a script used by another window, you just need to access it using the other window's window object. ...
...(window.gettext()); thus, if you want to access variables or call a function declared in a script used by another window, you just need to access it using the other window's window object. for example, if we combined the last two examples into a single file, we might want to call the gettext() function from within the other window (for example, the test.xul window). to do this, we can do the following: alert(window.opener.gettext()); each window has an opener property which holds the window object that opened this one. in this example, we retrieve the opener window and call the gettext() function declared in a script used there. note that we qualified the property with the 'window' identifier just to be clearer. the window's open() method also returns a reference to the new window so yo...
...And 9 more matches
Templates - Archive of obsolete content
th mozilla such as bookmarks, history and mail messages. more details on these will be provided in the later section. usually, elements such as treeitems and menuitems will be populated with data. however, you can use other elements if you want although they are more useful for specialized cases. nevertheless, we'll start with these other elements because trees and menus require more code. to allow the creation of elements based on rdf data, you need to provide a simple template which will be duplicated for each element that is created. essentially, you provide only the first element and the remaining elements are constructed based on the first one. the template is created using the template element. inside it, you can place the elements that you want to use for each constructed element. t...
...can be used to get the data. this example will only get the top-level bookmarks (or bookmark folders) as we're going to create buttons. for child bookmarks, we would need to use an element that displays a hierarchy such as a tree or menu. this example and any others that reference internal rdf datasources will only work if you load them from a chrome url. for security reasons, mozilla doesn't allow access to them from other sources. to view this example, you will need to create a chrome package and load the file from there (you can do this easily, see manifest files). you can then enter the chrome url into the browser url field. example 1 : source <vbox datasources="rdf:bookmarks" ref="nc:bookmarksroot" flex="1"> <template> <button uri="rdf:*" label="rdf:http://home.netscape.com/n...
...n the image that the set of buttons has been created, one for each bookmark. try adding a bookmark in the browser while you have the example window open. you'll notice that the buttons in the example get updated instantly. (you may have to focus the window for it to change.) container and datasources the template itself is placed inside a vertical box. the box has two special attributes that allow it to be used for templates, which are used to specify where the data comes from. the first attribute on the box is the datasources attribute. this is used to declare what rdf datasource will be providing the data to create the elements. in this case, rdf:bookmarks is used. you can probably guess that this means to use the bookmarks datasource. this datasource is provided by mozilla. to use your ...
...And 9 more matches
XUL element attributes - Archive of obsolete content
for boxes that have horizontal orientation, it specifies how its children will be aligned vertically. for boxes that have vertical orientation, it specifies how its children will be aligned horizontally. start child elements are aligned starting from the left or top edge of the box. if the box is larger than the total size of the children, the extra space is placed on the right or bottom side. ...
...on their left edges. center the elements are centered horizontally. right the elements are aligned on their right edges. the pack attribute is related to the alignment but is used to specify the position in the opposite direction. you can also specify the value of align using the style property -moz-box-align. ...
...ents are aligned on their right edges. the pack attribute is related to the alignment but is used to specify the position in the opposite direction. you can also specify the value of align using the style property -moz-box-align. allowevents type: boolean if true, events are passed to children of the element. otherwise, events are passed to the element only. allownegativeassertions type: boolean valid on any element that has a datasources attribute. when multiple datasources are used, one may override an assertion from another. this attribute, if true, which is the default, allows a datasource to negate an earlier assertion. class type: string the style class of the element. multiple classes may be specified by separating them with spaces. ...
...And 9 more matches
Building up a basic demo with Babylon.js - Game development
d one. there is one helper variable already included, which will store a reference to the <canvas> element. before reading on, copy this code to a new text file and save it in your working directory as index.html. initialising the babylon.js engine we have to create a babylon.js engine instance first (passing it the <canvas> element to render on) before we start developing our game. add the following code to the bottom of your second <script> element: var engine = new babylon.engine(canvas); the babylon global object contains all the babylon.js functions available in the engine. creating a scene a scene is the place where all the game content is displayed. while creating new objects in the demo, we will be adding them all to the scene to make them visible on the screen. let's create a...
...f your second <script> element: var engine = new babylon.engine(canvas); the babylon global object contains all the babylon.js functions available in the engine. creating a scene a scene is the place where all the game content is displayed. while creating new objects in the demo, we will be adding them all to the scene to make them visible on the screen. let's create a scene by adding the following lines just below our previous code: var scene = new babylon.scene(engine); scene.clearcolor = new babylon.color3(0.8, 0.8, 0.8); thus, the scene is created and the second line sets the background color to light gray. creating a rendering loop to make the scene actually visible we have to render it. add these lines at the end of the <script> element, just before the closing </script>. var...
...nderloop); we're using the engine's runrenderloop() method to execute the renderloop() function repeatedly on every frame — the loop will continue to render indefinitely until told to stop. creating a camera now the setup code is in place we need to think about implementing the standard scene components: camera, light and objects. let's start with the camera — add this line to your code below the scene creation and the line where we defined the clearcolor. var camera = new babylon.freecamera("camera", new babylon.vector3(0, 0, -10), scene); there are many cameras available in babylon.js; freecamera is the most basic and universal one. to initialize it you need to pass it three parameters: any name you want to use for it, the coordinates where you want it to be positioned in the 3d ...
...And 9 more matches
Advanced styling effects - Learn web development
s, providing an introduction to some interesting advanced styling features such as box shadows, blend modes, and filters. prerequisites: html basics (study introduction to html) and an idea of how css works (study css first steps.) objective: to get an idea about how to use some of the advanced styling effects available in modern browsers. box shadows box-shadow allows you to apply one or more drop shadows to an element's box. like text shadows, box shadows are supported pretty well across browsers, including ie9+ and edge. users of older ie versions might just have to cope with no shadows, so just test your designs to make sure your content is legible without them. you can find the examples in this section at box-shadow.html (see the source code too). a sim...
... the second length value is the vertical offset — the distance downwards that the shadow is offset from the original box (or upwards, if the value is n...
...the button has a simple black box shadow set on it by default, plus a couple of inset shadows, one light and one dark, placed on opposite corners of the button to give it a nice shading effect. when the button is pressed in, the active state causes the first box shadow to be swapped for a very dark inset sh...
...And 9 more matches
Beginner's guide to media queries - Learn web development
previous overview: css layout next the css media query gives you a way to apply css only when the browser and device environment matches a rule that you specify, for example "viewport is wider than 480 pixels". media queries are a key part of responsive web design, as they allow you to create different layouts depending on the size of the viewport, but they can also be used to detect other things about the environment your site is running on, for example whether the user is using a touchscreen rather than a mouse. in this lesson you will first learn about the syntax used in media queries, and then move on to use them in a worked example showing how a simple design might be made responsive. prerequisites: html basics (study introduction to html), and an idea of ho...
... a media type, which tells the browser what kind of media this code is for (e.g. print, or screen). a media expression, which is a rule, or test that must be passed for the contained css to be applied. a set of css rules that will be applied if the test passes and the media type is correct. media types the possible types of media you can specify are: all print screen speech the following media query will only set the body to 12pt if the page is printed. it will not apply when the page is loaded in a browser. @media print { body { font-size: 12pt; } } note: the media type here is different from the so-called mime type. note: there were a number of other media types defined in the level 3 media queries specification; these have been deprecated and should be...
...a type in your media query then the media query will default 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 ...
...And 9 more matches
Getting started with CSS - Learn web development
prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, and html basics (study introduction to html.) objective: to understand the basics of linking a css document to an html file, and be able to do simple text formatting with css. starting with some html our starting point is an html document. you can copy the code from below if you want to work on your own computer. save the code below as index.html in a folder on your machine. <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>getting started with css</title> </head> <body> <h1>i am a level one heading</h1> <p>this is a paragraph of text. in the text is a <span>span element</span> and also a <a href="http://example.com">link</a...
...ttp://example.com">link</a>.</p> <p>this is the second paragraph. it contains an <em>emphasized</em> element.</p> <ul> <li>item one</li> <li>item two</li> <li>item <em>three</em></li> </ul> </body> </html> note: if you are reading this on a device or an environment where you can't easily create files, then don't worry — live code editors are provided below to allow you to write example code right here in the page. adding css to our document the very first thing we need to do is to tell the html document that we have some css rules we want it to use. there are three different ways to apply css to an html document that you'll commonly come across, however, for now, we will look at the most usual and useful way of doing so — linking css from the ...
...there are three different ways to apply css to an html document that you'll commonly come across, however, for now, we will look at the most usual and useful way of doing so — linking css from the head of your document. create a file in the same folder as your html document and save it as styles.css. the .css extension shows that this is a css file. ...
...And 9 more matches
Web fonts - Learn web development
prerequisites: basic computer literacy, html basics (study introduction to html), css basics (study introduction to css), css text and font fundamentals. ...
... prerequisites: basic computer literacy, html basics (study introduction to html), css basics (study introduction to css), css text and font fundamentals. ...
...nt it has available on the system it is running on: p { font-family: helvetica, "trebuchet ms", verdana, sans-serif; } this system works well, but traditionally web developers' font choices were limited. there are only a handful of fonts that you can guarantee to be available across all common systems — the so-called web-safe fonts. ...
...And 9 more matches
What are browser developer tools? - Learn web development
every modern web browser includes a powerful suite of developer tools. these tools do a range of things, from inspecting currently-loaded html, css and javascript to showing which assets the page has requested and how long they took to load. this article explains how to use the basic functions of your browser's devtools. note: before you run through the examples below, open the beginner's example site that we built during the getting started with the web article series. you should have this open as you follow the steps below. how to open the devtools in your browser the devtools live inside your browser in a subwindow that looks roughly like this, depending on what browser you are using: how do you pull it up? three ways: keyboard: ctrl + shift + i, except internet explor...
...s context menu: press-and-hold/right-click an item on a webpage (ctrl-click on the mac), and choose inspect element from the context menu that appears. (an added bonus: this method straight-away highlights the code of the element you right-clicked.) the inspector: dom explorer and css editor the developer tools usually open by default to the inspector, which looks something like the following screenshot. this tool shows what the html on your page looks like at runtime, as well as what css is applied to each element on the page. it also allows you to instantly modify the html and css and see the results of your changes reflected live in the browser viewport. if you don't see the inspector, tap/click the inspector tab. in internet explorer, tap/click dom explorer, or press ctr...
...rent element. edit as html (sometimes add attribute/edit text). lets you change the html and see the results on the fly. very useful for debugging and testing. :hover/:active/:focus. forces element states to be toggled on, so you can see what their styling would look like. copy/copy as html. copy the currently selected html. some browsers also have copy css path and copy xpath available, to allow you to copy the css selector or xpath expression that would select the current html element. try editing some of your dom now. double-click an element, or right-click it and choose edit as html from the context menu. you can make any changes you'd like, but you cannot save your changes. exploring the css editor by default, the css editor displays the css rules applied to the currently selecte...
...And 9 more matches
Advanced form styling - Learn web development
tter for compatibility. if you look at the reference page you'll see a lot of different possible values listed for -webkit-appearance, however by far the most helpful value, and probably the only one you'll use, is none. this stops any control you apply it to from using system-level styling, as much as possible, and lets you build up the styles yourself using css. ...
... input { -webkit-appearance: none; appearance: none; } note: it is a good idea to always include both declarations — prefixed and unprefixed — when using a prefixed property. prefixed usually means "work in progress", so in the future browser vendors may come to a consensus to drop the prefix. the above code is good for future-proofing agains...
...evel styling. input { -webkit-appearance: none; appearance: none; } note: it is a good idea to always include both declarations — prefixed and unprefixed — when using a prefixed property. prefixed usually means "work in progress", so in the future browser vendors may come to a consensus to drop the prefix. the above code is good for future-proofing against such an eventuality. the following live example shows you what they look like in your system — default on the left, and with the above css applied on the right (find it here also if you want to test it on other systems). 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 mo...
...And 9 more matches
How to build custom form controls - Learn web development
to spend time in the design stage; if you define a behavior poorly, or forget to define one, it will be very hard to redefine it once the users have gotten used to it. if you have doubts, ask for the opinions of others, and if you have the budget for it, do not hesitate to perform user tests. this process is called ux design. if you want to learn more about this topic, you should check out the following helpful resources: uxmatters.com uxdesign.com the ux design section of smashingmagazine note: also, in most systems there is a way to open the <select> element with the keyboard to look at all the available choices (this is the same as clicking the <select> element with a mouse). this is achieved with alt + down on windows. we didn't implement this in our example, but it would be easy...
...nted for the click event. defining the html structure and (some) semantics now that the control's basic functionality has been decided upon, it's time to start building it. the first step is to define its html structure and to give it some basic semantics. here is what we need to rebuild a <select> element: <!-- this is our main container for our control. the tabindex attribute is what allows the user to focus the control. we'll see later that it's better to set it through javascript. --> <div class="select" tabindex="0"> <!-- this container will be used to display the current value of the control --> <span class="value">cherry</span> <!-- this container will contain all the options available for our control. because it's a list, it makes sense to use the ul eleme...
...cy styles used to make it look the way we want. required styles the required styles are those necessary to handle the three states of our control. .select { /* this will create a positioning context for the list of options; adding this to .select:focus-within will be a better option when fully supported */ position: relative; /* this will make our control become part of the text flow and sizable at the same time */ display : inline-block; } we need an extra class active to define the look and feel of our control when it is in its active state. because our control is focusable, we double this custom style with the :focus pseudo-class in order to be sure they will behave the same. .select .active, .select:focus { outline: none; /* this box-shadow property is not exactl...
...And 9 more matches
Responsive images - Learn web development
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 on github.) we won't discuss the css much in this lesson, except to say that: the body conte...
...xample: 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 on github.) we won't discuss the css much in this lesson, except to say that: the body content has been set to a maximum width of 1200 pixels — in viewports above that width, the body remains at 1200px and centers itself in the available space. in viewports below that width, the body will stay at 100% of the width of the viewport. the header image has been set so that its center always stays in the center of the header, no matter what width the heading is set at. if the site is being viewed on a narrower screen, the important detail in the center of the image (the people) can still be seen, and the excess is lost off either side. it is 200px high. the c...
...at width the heading is set at. if the site is being viewed on a narrower screen, the important detail in the center of the image (the people) can still be seen, and the excess is lost off either side. it is 200px high. the content images have been set so that if the body element becomes smaller than the image, the images start to shrink so that they always stay inside the body, rather than overflowing it. however, issues arise when you start to view the site on a narrow screen device. the header below looks ok, but it's starting to take up a lot of the screen height for a mobile device. and at this size, it is difficult to see the people within the first content image. an improvement would be to display a cropped version of the image which displays the important details of the image wh...
...And 9 more matches
Introduction to the server side - Learn web development
r-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 stored on a server and sent to the client to be displayed via some code (e.g. html and javascript). ...
...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. ...
...arrive, and reply to the web browser with an http response message. the response contains a status line indicating whether or not the request succeeded (e.g. "http/1.1 200 ok" for success). the body of a successful response to a request would contain the requested resource (e.g. a new html page, or an image, etc...), which could then be displayed by the web browser. static sites the diagram below shows a basic web server architecture for a static site (a static site is one that returns the same hard-coded content from the server whenever a particular resource is requested). when a user wants to navigate to a page, the browser sends an http "get" request specifying its url. the server retrieves the requested document from its file system and returns an http response containing the documen...
...And 9 more matches
Getting started with React - Learn web development
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 covered in this module, react does not enforce strict rules around code conventions or file organization. this allows teams to set conventions that work best for them, and to adopt react in any way they would like to. react can handle a single button, a few pieces of an interface, or an app's entire user interface. while react can be used for small pieces of an interface, it's not as easy to "drop into" an application as a library like jquery, or even a framework like vue — it is more approachable when you b...
...s of an interface, it's not as easy to "drop into" an application as a library like jquery, or even a framework like vue — it is more approachable when you build your entire app with react. in addition, many of the developer-experience benefits of a react app, such as writing interfaces with jsx, require a compilation process. adding a compiler like babel to a website makes the code on it run slowly, so developers often set up such tooling with a build step. react arguably has a heavy tooling requirement, but it can be learned. this article is going to focus on the use case of using react to render the entire user interface of an application, using tooling provided by facebook’s own create-react-app tool. how does react use javascript? react utilizes features of modern javascript for ...
... from javascript comes with the use of jsx syntax. jsx extends javascript's syntax so that html-like code can live alongside it. for example: const heading = <h1>mozilla developer network</h1>; this heading constant is known as a jsx expression. react can use it to render that <h1> tag in our app. suppose we wanted to wrap our heading in a <header> tag, for semantic reasons? the jsx approach allows us to nest our elements within each other, just like we do with html: const header = ( <header> <h1>mozilla developer network</h1> </header> ); note: the parentheses in the previous snippet aren't unique to jsx, and don’t have any effect on your application. they're a signal to you (and your computer) that the multiple lines of code inside are part of the same expression. you could ...
...And 9 more matches
Software accessibility: Where are we today?
these operating systems were not designed with the needs of people with disabilities in mind. ...
...eact to sounds played. this tends to be somewhat less of a limitation in that most software doesn't rely exclusively on audio to relay feedback. if a person was unable to do one of the above-listed tasks, they found themselves unable to use many popular computer applications. here are some of the groups of people that have problems doing some of those tasks: print disabled: blind, deaf-blind, low vision, obstructed vision, dyslexic, cognitively disabled and illiterate individuals. physically disabled: users have amputations, paralysis, repetitive stress, cerebral palsy, muscular dystrophy, parkinson's or other problems limiting mobility. hearing impaired we must also consider the increasing numbers of aging baby boomers that are beginning to experience problems with their sight, visi...
...er to this problem, many small accessibility hardware and software vendors created products and software which helped people who could not perform one of the four basic tasks to use common computer applications. ...
...And 9 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. ...
...curses into all referenced files and directories. as the moz.build files are read, data structures describing the overall build system definition are emitted. these data structures are then read by a build backend generator, which then converts them into files, function calls, and so on. in the case of a make backend, the generator writes out makefiles. when config.status runs, you'll see the following output: reticulating splines... finished reading 1096 moz.build files into 1276 descriptors in 2.40s backend executed in 2.39s 2188 total backend files. 0 created; 1 updated; 2187 unchanged total wall time: 5.03s; cpu time: 3.79s; efficiency: 75% what this is saying is that a total of 1,096 moz.build files were read. altogether, 1,276 data structures describing the build configuration were d...
...ols is used to install tests and other support tools. when make is invoked, it starts at the export sub-tier of the first tier, and traverses all the directories in that tier. then, it does the same thing for the libs sub-tier and, subsequently, the tools sub-tier. it then moves on to the next tier and continues until no tiers remain. to view information about the tiers, you can execute the following special make targets: command effect make echo-tiers show the final list of tiers. make echo-dirs show the list of non-static source directories to iterate over, as determined by the tier list. make echo-variable-static_dirs show the list of static source directories to iterate over, as determined by the tier list. moz.build files moz.bu...
...And 9 more matches
Error codes returned by Mozilla APIs
ns_error_not_initialized (0xc1f30001) an attempt was made to use a component or object which has not yet been initialized. these components usually provide an initialization method, often called init, which must be called before other methods are used. ...
...es list errors that can occur when calling various mozilla apis. each error is listed by its name and an error code in parentheses. an error will typically be displayed on the error console, but can be captured using a try-catch block in javascript. these constants can be accessed through components.results. for example, by using components.results.ns_error_not_initialized general errors the following errors are general and can occur when using any component. ns_error_not_initialized (0xc1f30001) an attempt was made to use a component or object which has not yet been initialized. these components usually provide an initialization method, often called init, which must be called before other methods are used. ns_error_already_initialized (0xc1f30002) an attempt is made to initialize a c...
...n which was not expected. this error occurred rather than continuing. ns_error_out_of_memory (0x8007000e) this error occurs when there is not enough memory available to carry out an operation, or an error occurred trying to allocate memory. ns_error_illegal_value (0x80070057) an argument supplied to a method was not valid, for instance a null value was supplied as an argument which does not allow null values, or a value was out of range. ns_error_no_aggregation (0x80040110) ns_error_not_available (0x80040111) an operation could not be completed because some other necessary component or resource was not available. ns_error_factory_not_registered (0x80040154) returned when a service could not be found. ns_error_factory_register_again (0x80040155) this error is returned when regist...
...And 9 more matches
How to implement a custom autocomplete search component
utocomplete sources, including: history: search the browser's url history (firefox: 1.0+; seamonkey: 1.1+) form-history: search the values that the user has entered into form fields. (firefox: 1.0+; seamonkey: 2.0+) file: search file names (firefox: 2.0+; thunderbird: 2.0+; seamonkey: 1.1+; gtk builds only). the component uses the autocompletesearchparam attribute or searchparam property to allow the developer to define the default directory otherwise only paths beginning with / or ~/ will be autocompleted. building your custom autocomplete search components sometimes, you may want to build your own autocomplete source. to do so you need the following: create an xpcom component that implements the nsiautocompletesearch interface. make sure the contract id of your xpcom component follo...
...oper to define the default directory otherwise only paths beginning with / or ~/ will be autocompleted. building your custom autocomplete search components sometimes, you may want to build your own autocomplete source. to do so you need the following: create an xpcom component that implements the nsiautocompletesearch interface. make sure the contract id of your xpcom component follows the following form: "@mozilla.org/autocomplete/search;1?name=xxx", where "xxx" is the name of your autocomplete source. implement the list of matched strings using the nsiautocompleteresult interface. the simplest way to make an xpcom component is to build an xpcom javascript component (this cannot be done with a javascript module). how to build an xpcom component in javascript will step you through the p...
...ed strings using the nsiautocompleteresult interface. the simplest way to make an xpcom component is to build an xpcom javascript component (this cannot be done with a javascript module). how to build an xpcom component in javascript will step you through the process. because creating an xpcom component in order to build a custom autocomplete source can be enough to discourage some developers, below is an example javascript xpcom component called "simple-autocomplete" that implements the necessary interfaces. note: when copying the examples below, change the uuid that uniquely identifies the component, otherwise you might have problems if your component gets installed along another component derived from those same examples. that can happen! so, get a uuid from http://www.famkruithof.net/u...
...And 9 more matches
Bootstrapping a new locale
lease 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. install the compare-locales utility the next step is to install compare-locales. $ sudo eas...
...tep 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. ...
... create a bare-bones localization next, create a base localization. this is done by cloning the en-us (united states english) files into your localization. ...
...And 9 more matches
Localizing without a specialized tool
from the create a new localization document, an interested localizer can follow a technical step-by-step process that starts the localization process by focusing on how to localize two of the primary types of localization files (dtd and properties) used in the mozilla source code. with that document, users can see immediately two localized files in their user interface by following closely and carefully the steps to create a language pack or a binary file that is ready for installation. repeating the process allows a localizer to create a testable package to see his or her work as they progress to a final version. if you choose to localize mozilla with nothing more than a text editing application and not a specialized tool, this document (along with create a new localization) will ena...
...fault points to the google search. if you click on the highlighted arrow pointing down while reading this tutorial on mdc, you will see two string that need to be translated: add "mdc search" manage search engines... there is also a tooltip that appears when you hover over the magnifying glass icon on the right side of the bar. ...
... document, we will be using the following folder structure in all examples: your working directory (root) mozilla-1.9.2 (en-us source, pulled from http://hg.mozilla.org/releases/mozilla-1.9.2) l10n-mozilla-1.9.2 (a directory containing localization directories, one dir per localization; often referred to as "l10n base") x-testing (a directory with your localization files) please either follow this structure closely or adjust all 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. ...
...And 9 more matches
Mozilla DOM Hacking Guide
own property on the object (window, in our case). in getproperty(), we check if the property being set is "location". if that is the case, we call nsidomlocation::sethref(). in fact, when setting window.location, we really set window.location.href. this is all possible thanks to the magic of the interaction between xpconnect and the dom. the second example is the history object. other browsers allow the history object to be used like an array, e.g. history[1]. the behavior "act as an array" cannot be reflected in the idl itself. fortunately, xpconnect provides us with a way to make our class available as an array in javascript. i'm talking about the "scriptable flags". the nsixpcscriptable interface, implemented by the nsdomclassinfo class (see section) defines several flags, one of which is...
...y, e.g. history[1]. the behavior "act as an array" cannot be reflected in the idl itself. fortunately, xpconnect provides us with a way to make our class available as an array in javascript. i'm talking about the "scriptable flags". the nsixpcscriptable interface, implemented by the nsdomclassinfo class (see section) defines several flags, one of which is the want_getproperty flag. when set, it allows us to define a getproperty() function on nshistorysh (the helper class for the history object), which will handle the array behavior. indeed, it will forward the call history[1] to history.item(1), which is defined in the idl and easily coded. the relevant code is at nsdomclassinfo.cpp, around line 4520. these two examples demonstrate the power of the dom combined with xpconnect and the javascr...
... can easily see the interfaces available from js through interface flattening by looking at the code. the interesting part is in nsdomclassinfo::init(). there we have a long list of macros. there is one set of macros per dom class. there you can see, for each object, what interfaces are part of the "flattened" set. as an example, on the window object, we can call all the methods defined on the following interfaces: nsidomwindow, nsidomjswindow, nsidomeventreciever, nsidomeventtarget, nsidomviewcss, and nsidomabstractview. again, without caring on what interface the method is defined. see section 1.5 for more information about the init() method. for the w3c dom (level 1, 2, 3) objects, for each object there is one "standards-compliant" interface, which is exactly the same as the w3c one, name...
...And 9 more matches
NSS Tools certutil
cate and key database management. for information security module database management, see using the security module database tool. availability see the release notes for the platforms this tool is available on. ...
...til option [arguments ] where options and arguments are combinations of the options and arguments listed in the following section. each command takes one option. each option may take zero or more arguments. to see a usage string, issue the command without options, or with the -h option. options and arguments options specify an action and are uppercase. option arguments modify an action and are lowercase. certificate database tool command options and their arguments are defined as follows: options -n create new certificate and key databases. -s create an individual certificate and add it to a certificate database. -r create a certificate-request file that can be submitted to a certificate a...
...g the values of the -t argument. -h display a list of the options and arguments used by the certificate database tool. -w change the password to a key database. -u list all available modules or print a single named module. arguments -a use ascii format or allow the use of ascii format for input or output. this formatting follows rfc 1113. for certificate requests, ascii output defaults to standard output unless redirected. -b validity-time specify a time at which a certificate is required to be valid. use when checking certificate validity with the -v option. the format of thevalidity-time argument is "yymmddhhmmss[+hhmm|-h...
...And 9 more matches
Rhino Debugger
note that this debugger will not work with javascript scripts run in the mozilla browser since rhino is not the engine used in such environments. current limitations: no breakpoint menu using the rhino javascript debugger the mozilla rhino javascript engine includes a source-level debugger for debugging javascript scripts. the debugger is itself a java program which you may run as java org.mozilla.javascript.tools.debugger.main [options] [filename.js] [script-arguments] where the options are the same as the shell. ...
... running scripts you may select the file->run menu item on the menu bar to execute javascript scripts contained in files. this action will display a file-selection dialog box prompting you for the location of a script to execute. the loaded script will be run in a new thread and control will be given to the debugger on its first instruction. controlling execution the debugger provides the following facilities for you to control the execution of scripts you are debugging: step into to single step entering any function calls, you may do any of the following: select the debug->step into menu item on the menu bar press the step into button on the toolbar press the f11 key on the keyboard execution will resume. if the current line in the script contains a function call contro...
...into button on the toolbar press the f11 key on the keyboard execution will resume. if the current line in the script contains a function call control will return to the debugger upon entry into the function. otherwise control will return to the debugger at the next line in the current function. ...
...And 9 more matches
SpiderMonkey Build Documentation
28, you'll additionally need nspr. and of course, you'll need to get the spidermonkey source code. non-developer (optimized) build use these steps if you want to install spidermonkey for production use or run performance benchmarks. (if you want to use spidermonkey as a library in your c++ application, or work on improving spidermonkey itself, do a developer/debug build instead, as described below.) cd js/src # this name should end with "_opt.obj" to make the version control system ignore it. mkdir build_opt.obj cd build_opt.obj /bin/sh ../configure.in # use "mozmake" on windows make a few notes about this: the most common build problems are dependency problems. see the build prerequisites page for your platform. spidermonkey does not support building in your source directo...
...h' file not found, err: true this is because, starting from mohave, headers are no longer installed in /usr/include. refer the release notes under command line tools -> new features the release notes also states that this compatibility package will no longer be provided in the near future, so the build system on macos will have to be adapted to look for headers in the sdk until then, the following should help, open /library/developer/commandlinetools/packages/macos_sdk_headers_for_macos_10.14.pk this builds an executable named js in the directory build-release/dist/bin. you can test it with dist/bin/js --help, which displays a help page. at this point, you're ready to run and try out the shell. on mac, linux, or unix, you can install spidermonkey on your system with the additional ...
...command make install. this installs the shared library to /usr/local/lib, the c header files to /usr/local/include, and the js executable to/usr/local/bin. developer (debug) build for developing and debugging spidermonkey itself, it is best to have both a debug build (for everyday debugging) and an optimized build (for performance testing), in separate build directories. thus, in addition to following the steps above, you should also create a debug build using these steps: cd js/src # this name should end with "_dbg.obj" to make the version control system ignore it. mkdir build_dbg.obj cd build_dbg.obj /bin/sh ../configure.in --enable-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 buil...
...And 9 more matches
JSAPI reference
_newcompartmentandglobalobject added in spidermonkey 1.8.1 obsolete since jsapi 16 js_entercrosscompartmentcall added in spidermonkey 1.8.1 obsolete since jsapi 18 js_leavecrosscompartmentcall added in spidermonkey 1.8.1 obsolete since jsapi 18 locale callbacks: struct jslocalecallbacks js_getlocalecallbacks js_setlocalecallbacks locale callback types: jslocaletouppercase jslocaletolowercase jslocalecompare jslocaletounicode scripts just running some javascript code is straightforward: class js::compileoptions added in spidermonkey 17 class js::owningcompileoptions added in spidermonkey 31 class js::readonlycompileoptions added in spidermonkey 31 class js::sourcebufferholder added in spidermonkey 31 js::evaluate added in spidermonkey 17 js_evaluatescript obsolet...
...rmatstring added in spidermonkey 17 class jserrorreport class js::autosaveexceptionstate added in spidermonkey 31 enum jsexntype added in spidermonkey 17 js_reporterror js_reportwarning js_reporterrornumber js_reporterrornumberuc js_reporterrorflagsandnumber js_reporterrorflagsandnumberuc js_reporterrornumberucarray added in spidermonkey 24 js_reportoutofmemory js_reportallocationoverflow added in spidermonkey 1.8 js_geterrorreporter js_seterrorreporterobsolete since jsapi 52 js_errorfromexception js_geterrorprototype jsreport_is_exception jsreport_is_strict jsreport_is_warning jsreport_is_strict_mode_error the following functions allow c/c++ functions to throw and catch javascript exceptions: js::createerror added in spidermonkey 38 js_isexceptionpending js_getpend...
...see js::value for their modern replacements. jsval_is_null obsolete since jsapi 32 jsval_is_void obsolete since jsapi 32 jsval_is_boolean obsolete since jsapi 32 jsval_is_number obsolete since jsapi 32 jsval_is_int obsolete since jsapi 32 jsval_is_double obsolete since jsapi 32 jsval_is_string obsolete since jsapi 32 jsval_is_object obsolete since jsapi 15 jsval_is_p...
...And 9 more matches
Setting up the Gecko SDK
« previousnext » this chapter provides basic setup information for the gecko software development kit (sdk) used to build the weblock component in this tutorial. the following four sections tell the developer how to download and organize the gecko sdk and create a new project in which components like weblock can be created. downloading and setting the sdk the gecko sdk provides all of the tools, headers, and libraries that you need to build xpcom components. the sdk is available for windows, linux, and mac operating systems, and versions for other operating systems are being developed, and can be retrieved from as a single archive from the following platform-specific locations (need correction for last version (now 1.9.2.8). there is now separate archive with gecko-sdk, ju...
...la.org/pub/mozi...illa/releases/ gecko versions after 1.8: http://ftp.mozilla.org/pub/mozi...nner/releases/ once you download the sdk, you can expand it into any convenient location. in this appendix, we set up the windows gecko sdk in c:\gecko-sdk\. if you choose some other location, remember to adjust the settings described here (e.g., in the building a microsoft visual cpp project section below) to point to this new location. when you extract the sdk, it should have the layout seen below: layout of the extracted sdk the directories represent different modules in the sdk. for example, the headers for networking are all located in the necko directory, and the headers that xpcom requires are in the xpcom directory. this directory structure makes build scripts slightly more complicated...
...e subdirectories: module subdirectories the bin directory contains static libraries, dynamic libraries, and in some cases tools that may be useful in development. the idl directory contains the public idl files exported by the module. the includes directory contains c++ header files used by your component. xpcom exports a number of binaries that should be mentioned at this point. the table below refers to the windows file names for the executables. application name description of functionality regxpcom.exe registers or unregisters components with xpcom xpidl.exe generates typelib and c++ headers from xpidl xpt_dump.exe prints out information about a given typelib xpt_link.exe combines multiple typelibs into a single typelib ...
...And 9 more matches
Using XPCOM Utilities to Make Things Easier
s that can replace a lot of the code in weblock1.cpp. much of the code created to get the software recognized and registered as a component can be reduced to a small data structure and a single macro. xpcom macros the xpcom framework includes a number of macros for making c++ development easier. though they overlap somewhat (e.g., high-level macros expand to other macros), they fall into the following general categories. generic xpcom module macros the work in the previous chapter was useful in setting up the generic component code. but there are only a few places in that code that are unique to the weblock component, and it was a lot of typing. to write a different component library, you could copy the listing at the end of the chapter, change very little, and paste it into a new project...
...to a new project. to avoid these kinds of redundancies, to regulate the way generic code is written, and to save typing, xpcom providesgeneric module macros that expand into the module code you've already seen. since these macros expand into "generic" implementations, they may not offer as much flexibility as you have when you are writing your own implementation. but they have the advantage of allowing much more rapid development. to get an idea about how much can be handled with the macros described in this section, compare the code listing in weblock2.cpp at the end of the chapter with weblock1.cpp in the previous chapter. the module macros include one set of macros that define the exported nsgetmodule entry point, the required nsimodule implementation code and another that creates a gene...
...when the module is created and/or destroyed. xpcom module macros lists the macros discussed in this section. xpcom module macros macro description ns_impl_nsgetmodule(name, components) implements the nsimodule interface with the module name of name and the component list in components. ns_impl_nsgetmodule_with_ctor(name, components, ctor) same as above but allows for a special function to be called when the module is created. ns_impl_nsgetmodule_with_dtor(name, components, dtor) same as the first macro but allows for a special function to be called when the module is destroyed. ns_impl_nsgetmodule_with_ctor_dtor(name, components, ctor, dtor) this combines the last two macros so that you can define functions to be called at the con...
...And 9 more matches
nsIAccessibleRole
upported automatically by ms windows. role_menubar 2 represents the menu bar (positioned beneath the title bar of a window) from which menus are selected by the user. the role is used by xul:menubar or role="menubar". role_scrollbar 3 represents a vertical or horizontal scroll bar, which is part of the client area or used in a control. role_grip 4 represents a special mouse pointer, which allows a user to manipulate user interface elements such as windows. for example, a user clicks and drags a sizing grip in the lower-right corner of a window to resize it. role_sound 5 represents a system sound, which is associated with various system events. role_cursor 6 represents the system mouse pointer. role_caret 7 represents the system caret. the role is supported for caret. role_alert ...
...pp_root. role_document 15 represents a document window. a document window is always contained within an application window. it is used for role="document". role_pane 16 represents a pane within a frame or document window. users can navigate between panes and within the contents of the current pane, but cannot navigate between items in different panes. thus, panes represent a level of grouping lower than frame windows or documents, but above individual controls. it is used for the first child of a or iframe. role_chart 17 represents a graphical image used to represent data. role_dialog 18 represents a dialog box or message box. it is used for xul:dialog, role="dialog". role_border 19 represents a window border. role_grouping 20 logically groups other objects. there is not always a ...
...w that displays information about the current operation, state of the application, or selected object. the status bar has multiple fields, which display different kinds of information. it is used for xul:statusbar. role_table 24 represents a table that contains rows and columns of cells, and optionally, row headers and column headers. it is used for html:table, role="grid". also refer to the following roles: role_columnheader, role_rowheader, role_column, role_row, role_cell. role_columnheader 25 represents a column header, providing a visual label for a column in a table. it is used for xul tree column headers, html:th, role="colheader". also refer to role_table. role_rowheader 26 represents a row header, which provides a visual label for a table row. it is used for role="rowheader". a...
...And 9 more matches
nsIDocShell
y); native code only! void preparefornewcontentmodel(); void resumerefreshuris(); void setchildoffset(in unsigned long offset); native code only! ...
...set); native code only! ...
...id 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. ...
...And 9 more matches
nsIFile
void append(in astring node); void appendnative(in acstring node); native code only! void appendrelativenativepath(in acstring relativefilepath); void appendrelativepath(in astring relativefilepath); nsifile clone(); boolean contains(in nsifile infile); void copyto(in nsifile newparentdir, in astring newname); void copytofollowinglinks(in nsifile newparentdir, in astring newname); void copytofollowinglinksnative(in nsifile newparentdir, in acstring newname); native code only! void copytonative(in nsifile newparentdir, in acstring newname); native code only! void create(in unsigned long type, in unsigned long permissions); void createunique(in unsigned long type, in unsigned long permi...
... the size of the symbolic link referenced 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...
...ile has undefined behavior. 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 intended to be used whenever a nsifile needs to be serialized to disk and later recovered. this string is not intended for display to users. note: the value of the followlinks attribute is not encoded in the persistent descriptor. target astring this attribute exposes the full target of the nsifile - the full path with any symbolic links dereferenced. accessor to the string path. the native version of these strings are not guaranteed to be a usable path to pass to nspr or the c stdlib. there are problems that affect platforms on which ...
...And 9 more matches
nsINavHistoryService
fox 22 / thunderbird 22 / seamonkey 2.19) implemented by: "@mozilla.org/browser/nav-history-service;1". ...
...: "@mozilla.org/browser/nav-history-service;1". ...
...oruri(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. ...
...And 9 more matches
XPIDL
efs, native types, or interfaces. interfaces may furthermore contain typedefs, natives, methods, constants, or attributes. most declarations can have properties applied to them. types there are three ways to make types: a typedef, a native, or an interface. in addition, there are a few built-in native types. the built-in native types are those listed under the type_spec production above. ...
...s type but astring. array<t> const nstarray<t>& nstarray<t>& array the c++-exposed type t will be an owned variant. (e.g. ns[c]string, refptr<t>, or uint32_t) string, wstring, [ptr] native and [ref] native are unsupported as element types. ...
... nsiidref const nsiid& nsiid* ? nscidref const nscid& nscid* ? nsidptr const nsid* nsid** ? nsiidptr const nsiid* nsiid** ? ns...
...And 9 more matches
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
make manipulation of the content tree difficult in unexpected ways, depending on where it is located. this article explores when difficulties can occur, and looks at what can be done to mitigate resulting problems. what is whitespace? whitespace is any string of text composed only of spaces, tabs or line breaks (to be precise, crlf sequences, carriage returns or line feeds). these characters allow you to format your code in a way that will make it easily readable by yourself and other people. in fact, much of 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 sin...
...uch of 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. ...
...ace? they don't just disappear, however. any whitespace characters that are outside of html elements in the original document are represented in the dom. this is needed internally so that the editor can preserve formatting of documents. this means that: there will be some text nodes that contain only whitespace, and some text nodes will have whitespace at the beginning or end. ...
...And 9 more matches
Element - Web APIs
Web › API › Element
svgelement interface is the basis for all svg elements. most functionality is specified further down the class hierarchy. languages outside the realm of the web platform, like xul through the xulelement interface, also implement element. ...
... the element. element.namespaceuri read only the namespace uri of the element, or null if it is no namespace. note: in firefox 3.5 and earlier, html elements are in no namespace. in later versions, html elements are in the http://www.w3.org/1999/xhtml namespace in both html and xml trees. nondocumenttypechildnode.nextelementsibling read only is an element, the element immediately following the given one in the tree, or null if there's no sibling node. element.outerhtml is a domstring representing the markup of the element including its content. when used as a setter, replaces the element with nodes parsed from the given string. element.part represents the part identifier(s) of the element (i.e. set using the part attribute), returned as a domtokenlist. element.prefix read o...
...ed with the element. element.undoscope is a boolean indicating if the element is an undo scope host, or not. note: dom level 3 defined namespaceuri, localname and prefix on the node interface. in dom4 they were moved to element. this change is implemented in chrome since version 46.0 and firefox since version 48.0. properties included from slotable the element interface includes the following property, defined on the slotable mixin. slotable.assignedslotread only returns a htmlslotelement representing the <slot> the node is inserted in. event handlers element.onfullscreenchange an event handler for the fullscreenchange event, which is sent when the element enters or exits full-screen mode. this can be used to watch both for successful expected transitions, but also to wa...
...And 9 more matches
IDBKeyRange - Web APIs
the idbkeyrange interface of the indexeddb api represents a continuous interval over some data type that is used for keys. records can be retrieved from idbobjectstore and idbindex objects using keys or a range of keys. you can limit the range using lower and upper bounds. for example, you can iterate over all values of a key in the value range a–z. a key range can be a single value or a range with upper and lower bounds or endpoints. if the key range has both upper and lower bounds, then it is bounded; if it has no bounds, it is unbounded. ...
... key in the value range a–z. a key range can be a single value or a range with upper and lower bounds or endpoints. if the key range has both upper and lower bounds, then it is bounded; if it has no bounds, it is unbounded. a bounded key range can either be open (the endpoints are excluded) or closed (the endpoints are included). ...
...r and lower bounds or endpoints. if the key range has both upper and lower bounds, then it is bounded; if it has no bounds, it is unbounded. a bounded key range can either be open (the endpoints are excluded) or closed (the endpoints are included). ...
...And 9 more matches
Node - Web APIs
Web › API › Node
to one of its child interfaces; in that case, the inheriting node may return null or throw an exception, depending on circumstances. for example, attempting to add children to a node type that cannot have children will throw an exception. ...
... node.baseuriread only returns a domstring representing the base url of the document containing the node. node.baseuriobject read only (not available to web content.) the nsiuri object representing the base uri for the element. node.childnodesread only returns a live nodelist containing all the children of this node. nodelist bei...
...nt returns / sets the textual content of an element and all its descendants. obsolete properties node.localname read only returns a domstring representing the local part of the qualified name of an element. note: in firefox 3.5 and earlier, the property upper-cases the local name for html elements (but not xhtml elements). in later versions, this does not happen, so the property is in lower case for both html and xhtml. node.namespaceuri read only the namespace uri of this node, or null if it is no namespace. note: in firefox 3.5 and earlier, html elements are in no namespace. in later versions, html elements are in the http://www.w3.org/1999/xhtml/ namespace in both html and xml trees. node.nodeprincipal obsolete since gecko 46 a nsiprincipal representing the no...
...And 9 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
pendencies while we will not rely upon any 3d graphics frameworks such as three.js or the like for this example, we do use the glmatrix library for matrix math, which we've used in other examples in the past. this example also imports the webxr polyfill maintained by the immersive web working group, which is the team responsible for the webxr api's specification. by importing this polyfill, we allow the example to work on many browsers that don't yet have webxr implementations in place, and we smooth out any transient deviations from the specification that occur during these still somewhat experimental days of the webxr specification. options this example has a number of options you can configure by adjusting the values of constants before you load it in the browser. the code looks like th...
...that occur during these still somewhat experimental days of the webxr specification. options this example has a number of options you can configure by adjusting the values of constants before you load it in the browser. the code looks like this: const xrotationdegreespersecond = 25; const yrotationdegreespersecond = 15; const zrotationdegreespersecond = 35; const enablerotation = true; const allowmouserotation = true; const allowkeyboardmotion = true; const enableforcepolyfill = false; //const session_type = "immersive-vr"; const session_type = "inline"; const mouse_speed = 0.003; xrotationdegreespersecond the number of degrees of rotation to apply around the x axis per second. yrotationdegreespersecond the number of degrees to rotate around the y axis each second. zrotationdegrees...
..._speed = 0.003; xrotationdegreespersecond the number of degrees of rotation to apply around the x axis per second. yrotationdegreespersecond the number of degrees to rotate around the y axis each second. zrotationdegreespersecond the number of degrees per second to rotate around the z axis. enablerotation a boolean indicating whether or not to enable the rotation of the cube at all. allowmouserotation if true, you can use the mouse to pitch and yaw the view angle. allowkeyboardmotion if true, the w, a, s, and d keys move the viewer forward, left, backward, and to the right, while the up and down arrow keys move up and down. if false, only xr device changes to the view are permitted. enableforcepolyfill if this boolean is true, the example will attempt to use the webxr polyfil...
...And 9 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
by the windoworworkerglobalscope mixin. syntax var intervalid = scope.setinterval(func, [delay, arg1, arg2, ...]); var intervalid = scope.setinterval(function[, delay]); var intervalid = scope.setinterval(code, [delay]); parameters func a function to be executed every delay milliseconds. the function is not passed any arguments, and no return value is expected. ...
... arg1, ..., argn optional additional arguments which are passed through to the function specified by func once the timer expires. note: passing additional arguments to setinterval() in the first syntax does not work in internet explorer 9 and earlier. ...
...nd that clearinterval() and cleartimeout() can technically be used interchangeably. for clarity, however, you should try to always match them to avoid confusion when maintaining your code. note: the delay argument is converted to a signed 32-bit integer. this effectively limits delay to 2147483647 ms, since it's specified as a signed integer in the idl. examples example 1: basic syntax the following example demonstrates setinterval()'s basic syntax. var intervalid = window.setinterval(mycallback, 500, 'parameter 1', 'parameter 2'); function mycallback(a, b) { // your code here // parameters are purely optional. console.log(a); console.log(b); } example 2: alternating two colors the following example calls the flashtext() function once a second until the stop button is pressed. <...
...And 9 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
w.settimeout()) sets a timer which executes a function or specified piece of code once the timer expires. syntax var timeoutid = scope.settimeout(function[, delay, arg1, arg2, ...]); var timeoutid = scope.settimeout(function[, delay]); var timeoutid = scope.settimeout(code[, delay]); parameters function a function to be executed after the timer expires. code an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. this syntax is not recommended for the same reasons that make using eval() a security risk. delay optional the time, in milliseconds (thousandths of a second), the timer should wait before the specified function or code is executed. if this parameter is omitted, a value of 0 is used, meaning e...
...curity risk. delay optional the time, in milliseconds (thousandths of a second), the timer should wait before the specified function or code is executed. if this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. note that in either case, the actual delay may be longer than intended; see reasons for delays longer than specified below. arg1, ..., argn optional additional arguments which are passed through to the function specified by function. note: passing additional parameters to the function in the first syntax does not work in internet explorer 9 and below. if you want to enable this functionality on that browser, you must use a polyfill (see the polyfill section). return value the returned timeoutid is a positive ...
...imeout() and clearinterval() can technically be used interchangeably. for clarity, however, you should try to always match them to avoid confusion when maintaining your code. it is guaranteed that a timeout id will never be reused by a subsequent call to settimeout() or setinterval() on the same object (a window or a worker). however, different objects use separate pools of ids. example the following example sets up two simple buttons in a web page and hooks them to the settimeout() and cleartimeout() routines. pressing the first button will set a timeout which calls an alert dialog after two seconds and stores the timeout id for use by cleartimeout(). you may optionally cancel this timeout by pressing on the second button. html <p>live example</p> <button onclick="delayedalert();">show ...
...And 9 more matches
Ordering Flex Items - CSS: Cascading Style Sheets
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. ...
...se 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 for linear models such as speech and sequential navigation.” - ordering and orientation if your items were links or some other element that the user could tab to, then the tabbing order would be the order that these items appear in the document source — not your visual order. if you are...
...order that these items appear in the document source — not your visual order. if you are using a reverse value, or otherwise reordering your items, you should consider whether you actually need to change the logical order in the source. the specification continues with a warning not to use reordering to fix issues in your source: “authors must not use order or the *-reverse values of flex-flow/flex-direction as a substitute for correct source ordering, as that can ruin the accessibility of the document.” note: for some years firefox had a bug whereby it would attempt to follow the visual order and not the source order, making it behave differently to other browsers. this has now been fixed. you should always take the source order as the logical order of the document as all up-to-d...
...And 9 more matches
OpenType font features guide - CSS: Cascading Style Sheets
hs or character styles contained within an opentype font. these include things like ligatures (special glyphs that combine characters like 'fi' or 'ffl'), kerning (adjustments to the spacing between specific letterform pairings), fractions, numeral styles, and a number of others. these are all referred to as opentype features, and are made available to use on the web via specific properties and a low-level control property — font-feature-settings. this article provides you with all you need to know about using opentype font features in css. some fonts will have one or more of these features enabled by default (kerning and default ligatures are common examples), while others are left to the designer or developer to choose to enable in specific scenarios. in addition to broad feature sets l...
...using opentype font features in css. some fonts will have one or more of these features enabled by default (kerning and default ligatures are common examples), while others are left to the designer or developer to choose to enable in specific scenarios. in addition to broad feature sets like ligatures or lining figures (numerals that line up evenly as opposed to 'oldstyle', which look more like lower-case letters), there are also very specific ones such as stylistic sets (which might include several specific variants of glyphs meant to be used together), alternates (which might be one or more variants of the letter 'a'), or even language-specific alterations for east asian languages. in the latter case, these alterations are actually necessary to properly express the language, so they go be...
... for east asian languages. in the latter case, these alterations are actually necessary to properly express the language, so they go beyond the more stylistic preference of most other opentype features. caution: there are many css attributes defined to leverage font features, but unfortunately many are not fully implemented. they are all defined and shown here, but many will only work using the lower-level font-feature-settings property. it's possible to write css to work both ways but this can become cumbersome. the issue with simply using font-feature-settings for everything is that every time you want to change one of the individual features, you have to redefine the entire string (similar to manipulating variable fonts with font-variation-settings). discovering availability of feature...
...And 9 more matches
Value definition syntax - CSS: Cascading Style Sheets
css value definition syntax, a formal grammar, is used for defining the set of valid values for a css property or function. in addition to this syntax, the set of valid values can be further restricted by semantic constraints (for example, for a number to be strictly positive). the definition syntax describes which values are allowed and the interactions between them. a component can be a keyword, some characters considered as a literal, or a value of a given css data type or of another css property. component value types keywords generic keywords a keyword with a predefined meaning appears literally, without quotation marks. for example: auto, smaller or ease-in. the specific case of inherit, initial and unset all css properties accept the keywords inherit, initial and unset, that ar...
...of their definition. in this case, the definition is usually physically very close to the definition of the property using them. component value combinators brackets brackets enclose several entities, combinators, and multipliers, then transform them as a single component. they are used to group components to bypass the precedence rules. bold [ thin && <length> ] this example matches the following values: bold thin 2vh bold 0 thin bold thin 3.5em but not: thin bold 3em, as bold is juxtaposed with the component defined by the brackets, it must appear before it. juxtaposition placing several keywords, literals or data types, next to one another, only separated by one or several spaces, is called juxtaposition. all juxtaposed components are mandatory and should appear in the e...
... not: thin bold 3em, as bold is juxtaposed with the component defined by the brackets, it must appear before it. juxtaposition placing several keywords, literals or data types, next to one another, only separated by one or several spaces, is called juxtaposition. all juxtaposed components are mandatory and should appear in the exact order. ...
...And 9 more matches
<color> - CSS: Cascading Style Sheets
the <color> css data type represents a color in the srgb color space. a <color> may also include an alpha-channel transparency value, indicating how the color should composite with its background. a <color> can be defined in any of the following ways: using a keyword (such as blue or transparent) using the rgb cubic-coordinate system (via the #-hexadecimal or the rgb() and rgba() functional notations) using the hsl cylindrical-coordinate system (via the hsl() and hsla() functional notations) note: this article describes the <color> data type in detail. to learn more about using color in html, see applying color to html elements using css. syntax the <color> data type is specified using one of the options listed below. note: although <color> values are precisely defined, their...
...word rgb hex value live keyword css level 1 black #000000 silver #c0c0c0 gray #808080 white #ffffff maroon #800000 red #ff0000 purple #800080 fuchsia #ff00ff green #008000 lime #00ff00 olive #808000 yellow #ffff00 navy #000080 blue #0000ff teal #008080 aqua #00ffff css level 2 (revision 1) orange #ffa500 css color module level 3 aliceblue #f0f8ff antiquewhite #faebd7 aquamarine #7fffd4 azure #f0ffff beige #f5f5dc bisque...
...uamarine #7fffd4 azure #f0ffff beige #f5f5dc bisque #ffe4c4 blanchedalmond #ffebcd blueviolet #8a2be2 brown #a52a2a burlywood #deb887 cadetblue #5f9ea0 chartreuse #7fff00 chocolate #d2691e coral #ff7f50 cornflowerblue #6495ed cornsilk #fff8dc crimson #dc143c cyan (synonym of aqua) #00ffff darkblue #00008b darkcyan #008b8b darkgoldenrod #b8860b darkgray #a9a9a9 darkgreen #006400 darkgrey #a9a9a9 darkkhaki #bdb76b darkmagenta ...
...And 9 more matches
Adding captions and subtitles to HTML5 video - Developer guides
s if you are not sure what they are. they are however implemented in the same way technically, so the material in this article will apply to both. for this article we will refer to the text tracks displayed as subtitles, as their content is aimed at hearing people who have difficulty understanding the language of the film, rather than deaf or hard-of-hearing people. ...
...l in this article will apply to both. for this article we will refer to the text tracks displayed as subtitles, as their content is aimed at hearing people who have difficulty understanding the language of the film, rather than deaf or hard-of-hearing people. the <track> element html5 allows us to specify subtitles for a video using the <track> element. the various attributes of this element allow us to specify such things as the type of content that we're adding, the language it's in, and of course a reference to the text file that contains the actual subtitle information. webvtt the files that contain the actual subtitle data are simple text files that follow a specified format, in this case the web video text tracks (webvtt) format. the webvtt specification is still being worked on, b...
... src is assigned a valid url pointing to the relevant ...
...And 9 more matches
Creating a cross-browser video player - Developer guides
<source src="video/tears-of-steel-battle-clip-medium.ogg" type="video/ogg"> <!-- flash fallback --> <object type="application/x-shockwave-flash" data="flash-player.swf?videourl=video/tears-of-steel-battle-clip-medium.mp4" width="1024" height="576"> <param name="movie" value="flash-player.swf?videourl=video/tears-of-steel-battle-clip-medium.mp4" /> <param name="allowfullscreen" value="true" /> <param name="wmode" value="transparent" /> <param name="flashvars" value="controlbar=over&amp;image=img/poster.jpg&amp;file=flash-player.swf?videourl=video/tears-of-steel-battle-clip-medium.mp4" /> <img alt="tears of steel poster image" src="img/poster.jpg" width="1024" height="428" title="no video playback possible, please download the video ...
...e="true" /> <param name="wmode" value="transparent" /> <param name="flashvars" value="controlbar=over&amp;image=img/poster.jpg&amp;file=flash-player.swf?videourl=video/tears-of-steel-battle-clip-medium.mp4" /> <img alt="tears of steel poster image" src="img/poster.jpg" width="1024" height="428" title="no video playback possible, please download the video from the link below" /> </object> <!-- offer download --> <a href="video/tears-of-steel-battle-clip-medium.mp4">download mp4</a> </video> <figcaption>&copy; blender foundation | <a href="http://mango.blender.org">mango.blender.org</a></figcaption> </figure> even though this player will define its own custom control set, the controls attribute is still added to the <video> element, and the pl...
...ip-medium.mp4">download mp4</a> </video> <figcaption>&copy; blender foundation | <a href="http://mango.blender.org">mango.blender.org</a></figcaption> </figure> even though this player will define its own custom control set, the controls attribute is still added to the <video> element, and the player's default control set is switched off later with javascript. doing things this way still allows users who have javascript turned off (for whatever reason) to still have access to the browser's native controls. a poster image is defined for the video, and the preload attribute is set to metadata, which informs the browser that it should initially only attempt to load the metadata from the video file rather than the entire video file. this provides the player with data such as video duratio...
...And 9 more matches
Challenge solutions - Developer guides
it also supports some more exotic color names like chartreuse, fuschia, or burlywood. see css color value for a complete list as well as other ways of specifying colors. ...
...it also supports some more exotic color names like chartreuse, fuschia, or burlywood. see css color value for a complete list as well as other ways of specifying colors. ...
...rial describe style rules and declarations in greater detail. selectors second paragraph blue challenge without changing your html file, add a single rule to your css file that keeps all the initial letters the same color as they are now, but makes all the other text in the second paragraph blue. solution add a rule with an id selector of #second and a declaration color: blue;, as shown below: #second { color: blue; } a more specific selector, p#second also works. both paragraphs blue challenge now change the rule you have just added (without changing anything else), to make the first paragraph blue too. solution change the selector of the new rule to be a tag selector using p: p { color: blue; } the rules for the other colors all have more specific selectors, so they...
...And 9 more matches
Indexed collections - 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 are specified, the array is initialized with them as the array's elements. the array's length property is ...
...pecified, the array is initialized with them as the array's elements. the array's length property is set to the number of arguments. the bracket syntax is called an "array literal" or "array initializer." it's shorter than other forms of array creation, and so is generally preferred. see array literals for details. to create an array with non-zero length, but without any items, either of the following can be used: // this... let arr = new array(arraylength) // ...results in the same array as this let arr = array(arraylength) // this has exactly the same effect let arr = [] arr.length = arraylength note: in the above code, arraylength must be a number. otherwise, an array with a single element (the provided value) will be created. calling arr.length will return arraylength, but the ar...
...tes an array with only one element: // the number 42. let arr = array(42) // creates an array with no elements // and arr.length set to 42. // // this is equivalent to: let arr = [] arr.length = 42 calling array(n) results in a rangeerror, if n is a non-whole number whose fractional portion is non-zero. the following example illustrates this behavior. let arr = array(9.3) // rangeerror: invalid array length if your code needs to create arrays with single elements of an arbitrary data type, it is safer to use array literals. alternatively, create an empty array first before adding the single element to it. in es2015, you can use the array.of static method to create arrays with single element. let wis...
...And 9 more matches
Inheritance and the prototype chain - JavaScript
re dynamic "bags" of properties (referred to as own properties). javascript objects have a link to a prototype object. when trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached. following the ecmascript standard, the notation someobject.[[prototype]] is used to designate the prototype of someobject. since ecmascript 2015, the [[prototype]] is accessed using the accessors object.getprototypeof() and object.setprototypeof(). this is equivalent to the javascript property __proto__ which is non-standard but de-facto implemented by many browsers. it should not be confused with the ...
...); // 5 // when p.m is called, 'this' refers to p. // so when p inherits the function m of o, // 'this.a' means p.a, the property 'a' of p using prototypes in javascript let's look at what happens behind the scenes in a bit more detail. in javascript, as mentioned above, functions are able to have properties. all functions have a special property named prototype. please note that the code below is free-standing (it is safe to assume there is no other javascript on the webpage other than the below code). for the best learning experience, it is highly recommended that you open a console, navigate to the "console" tab, copy-and-paste in the below javascript code, and run it by pressing the enter/return key. (the console is included in most web browser's developer tools. more information is...
... ƒ dosomething(), __proto__: { constructor: ƒ object(), hasownproperty: ƒ hasownproperty(), isprototypeof: ƒ isprototypeof(), propertyisenumerable: ƒ propertyisenumerable(), tolocalestring: ƒ tolocalestring(), tostring: ƒ tostring(), valueof: ƒ valueof() } } we can add properties to the prototype of dosomething(), as shown below. function dosomething(){} dosomething.prototype.foo = "bar"; console.log( dosomething.prototype ); this results in: { foo: "bar", constructor: ƒ dosomething(), __proto__: { constructor: ƒ object(), hasownproperty: ƒ hasownproperty(), isprototypeof: ƒ isprototypeof(), propertyisenumerable: ƒ propertyisenumerable(), tolocalestring: ƒ tolo...
...And 9 more matches
eval() - JavaScript
the eval() function evaluates javascript code represented as a string. 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 eval(string) parameters string a string representing a javascript expression, statement, or sequence of statements. ...
...ion as a string, you can use eval() to evaluate it at a later time. for example, suppose you have a variable x. you can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval() at a later point in your script. if the argument of eval() is not a string, eval() returns the argument unchanged. in the following example, the string constructor is specified and eval() returns a string object rather than evaluating the string. eval(new string('2 + 2')); // returns a string object containing "2 + 2" eval('2 + 2'); // returns 4 you can work around this limitation in a generic fashion by using tostring(). var expression = new string('2 + 2'); eval(expression.tostring()); // retur...
...ges of the caller. if you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. more importantly, a third-party code can see the scope in which 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 th...
...And 9 more matches
XUL Migration Guide - Archive of obsolete content
outline how to decide whether your add-on is a good candidate for migration via a comparison of the benefits and limitations of the sdk versus xul development. next, we'll look at some of the main tasks involved in migrating: working with content scripts using the sdk's supported apis how to go beyond the supported apis when necessary, by: using third party modules using the sdk's low-level apis getting direct access to xpcom finally, we'll walk through a simple example. should you migrate? see this comparison of the benefits and limitations of sdk development and xul development. whether you should migrate a particular add-on is largely a matter of how well the sdk's supported apis meet its needs. if your add-on can accomplish everything it needs using on...
...is comparison of the benefits and limitations of sdk development and xul development. whether you should migrate a particular add-on is largely a matter of how well the sdk's supported apis meet its needs. if your add-on can accomplish everything it needs using only the supported apis, it's a good candidate for migration. if your add-on needs a lot of help from third party packages, low-level apis, or xpcom, then the cost of migrating is high, and may not be worth it at this point. if your add-on only needs a little help from those techniques, and can accomplish most of what it needs using the supported apis, then it might still be worth migrating: we'll add more supported apis in future releases to meet important use cases. user interface components xul-based add-ons...
.... to add user interface components to the browser, there are a few different options. in order of complexity, the main options are: the sdk includes modules that implement some basic user interface components including buttons, dialogs, and context menu items. there is a collection of community-developed modules that includes various user interface components. by using the sdk's low-level apis you can directly modify the browser chrome. xul windows xul windows are used to define completely new windows to host user interface elements specific to the add-on. the sdk generally expects you to specify your user interface using html, not xul. however, you can include a chrome.manifest file in your add-on and it will be included in the generated xpi. my-addon/ chrome/ ...
...And 8 more matches
Preferences - Archive of obsolete content
this article provides examples for extension developers that wish to use the mozilla preferences system. information here applies to the mozilla suite, firefox, thunderbird, and possibly other mozilla-based applications. for more details on preferences in mozilla, see preferences system. if you haven't yet, read other documents about mozilla preferences on mdn (links below in resources section). note: this article doesn't cover all available methods for manipulating preferences; please refer to the xpcom reference pages listed in resources section for the complete list of methods. the interfaces dealing with preferences are fairly well documented, so using the methods not mentioned here should be straightforward. xpcom interfaces for preferences system mozilla exposes its preferences sys...
...ng preferences; please refer to the xpcom reference pages listed in resources section for the complete list of methods. the interfaces dealing with preferences are fairly well documented, so using the methods not mentioned here should be straightforward. xpcom interfaces for preferences system mozilla exposes its preferences system through a few xpcom interfaces. look in the resources section below for the link to a list of preferences-related interfaces. two used interfaces are nsiprefservice and nsiprefbranch. the preferences service is instantiated in the same way you instantiate any xpcom service. to get an nsiprefbranch, either queryinterface() the pref service (that will give you the root branch) or call nsiprefservice.getbranch() to get a sub-branch. here are two examples: // get...
...xvalue(). you can look up their implementations in nsprefbranch.cpp. here are the idl definitions: void getcomplexvalue(in string aprefname, in nsiidref atype, [iid_is(atype), retval] out nsqiresult avalue); void setcomplexvalue(in string aprefname, in nsiidref atype, in nsisupports avalue); as you can see, both of them take a parameter, atype, which can have one of the following values (to be precise, you should pass components.interfaces.nsiwhatever instead of just nsiwhatever, which is undefined). nsisupportsstring used to handle unicode strings in preferences. use this when the preference value may contain non-ascii characters (for example, a user's name). nsipreflocalizedstring almost the same as nsisupportsstring, but it is handled differently in getcomple...
...And 8 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
for parallel development! unlike many other application frameworks, you are not limited to the widget set we provide, nor limited to the "look and feel" of the native os. you can create applications using our framework that either have a native look and feel for each os, or one which is identical on macs, pc's or unix operating systems. you may also further enhance the user interface by allowing 3rd parties to develop "themes" for your application. themes are simply collections of images and css which can augment or replace your current ui elements. xul provides an excellent answer for organizations with heterogeneous computing environments. customized xul applications with significant business logic can be written once, and used on the range of platforms that exist within the ...
...pplications with significant business logic can be written once, and used on the range of platforms that exist within the organization. in addition, if the organization maintains sophisticated, interactive websites, it will already possess a wealth of technical expertise that will be relevant for creating xul applications. in addition to the technologies already mentioned, we go even further by allowing you to even create your own custom interface widgets. don't feel limited by the widgets that the framework already contains! xbl (extensible binding language) allows you to expand your library of interface elements, and even construct your own xml language for defining your ui. for instance imagine that you wanted to create a chess style game. you could easily create xml elements such as <ches...
...e. you could easily create xml elements such as <chessboard> or <chesspiece> and via xbl map these to images and application logic. this is very powerful since you could make improvements to the underlying application logic without having to rewrite the higher level code. our platform also can take advantage of other internet standards such as xslt and rdf. rdf, a core element to the framework, allows you to define dynamic elements in your ui (elements that may change after you have completed the application, such as a "history" menu item). xslt could be used to translate information from web services, rss, soap, or other xml-based languages and convert them into a form that you might display in your user interface. the gecko rendering engine gecko is the revolutionary rendering engine that ...
...And 8 more matches
New Security Model for Web Services - Archive of obsolete content
h they were loaded, any script loaded from one domain into another is prevented from accessing resources in the domain into which it has been loaded. this policy has generally been successful in sandboxing javascript and java applets across the web. if the sandbox is unable to distinguish the common uri substring of the domain to be trusted from similar uris of untrusted domains, then it could allow a script loaded from an indistinguishable domain to exploit firewall-protected resources. also, this technique prevents the script from accessing many legitimate external resources not provided in the same domain as the script. this prevents a script from accessing web services and data published from any domain besides its own. white-listing by creating a white list of trusted uris from which...
...ntly 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 either understand or pay the consequences 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 verifi...
...r 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 untrusted scripts will reject the requests. this is offered in the mozilla implementation of soap today. unfortunately, this does not prevent soap messages from being sent to non-soap addresses...
...And 8 more matches
URIs and URLs - Archive of obsolete content
warning: the content of this article may be out of date. it was last updated in 2002. overview handling network and locally retrievable resources is a central part of necko. ...
... in 2002. overview handling network and locally retrievable resources is a central part of necko. ...
... resource a resource can be anything that has identity. familiar examp...
...And 8 more matches
Positioning - Archive of obsolete content
horizontally, the left edge of the menu popup is aligned with the left edge of the menu or button. a submenu, however, is placed by default to the right of the parent menu item, such that the top edge of the menu is aligned with the top edge of the parent menu item. ...
...s placed by default to the right of the parent menu item, such that the top edge of the menu is aligned with the top edge of the parent menu item. however, the submenu will appear to the left instead for right to left locales. for both top level menus and submenus, they may appear above or to the left instead of their usual placement if there is not enough room to display the menu at full size below or to the right. if there is not enough room on either side, the menu will be shrunk down to fit. for popups attached using the popup or context attributes, the default position to appear is with the upper left corner (or upper right corner in right to left locales) at the position where the mouse was clicked. context menus will appear offset down and to the right a couple of pixels so that the ...
...set vertically by a small amount. the position attribute the position of all types of popups can be controlled in two ways. first, the position can be specified when using the popup's openpopup method. this is used when a popup is opened by a script. second, the position can be specified using several attributes placed on the menupopup, panel or tooltip element. these attributes are described below and function the same for all three elements. the position attribute specifies the alignment of the popup with respect to the element that the popup is attached to. for a menupopup placed inside a menu, button or toolbarbutton, the position attribute controls how the menupopup is anchored to the parent menu, button or toolbarbutton. for a menupopup or panel attached using the popup attribute...
...And 8 more matches
Skinning XUL Files by Hand - Archive of obsolete content
pplied to a whole application -- like the mozilla browser -- so that all the various windows and parts will look consistent. in the meantime, however, skinning a file requires some manual interaction. this article can help you get started understanding skins and creating skins for xul. it presumes you have at least basic understanding of xul and the application object model that xul describes. following the instructions here, you are going to create a skin for a xul file and apply it by specifying classes for all of the interested elements. the skin will reside in a single css file, appropriately named drxul.css. as you will see, css provides a lot of flexibility for defining styles to individual elements, to classes of elements, to pseudo-classes, and to anonymous classes. by the way, in co...
..., most of the behavior that buttons exhibit comes from styles and an event model based on javascript that dynamically switches between these styles. mozilla's current global skin defines this basic behavior for several classes of button. a button is styled by the global skin when its class attribute is set to a class which is defined in the global skin. for example, when a button is defined as follows: <button class="plain" label="push me" /> then the following very simple style definition applies to that button. button.plain { border: 0px !important; } the global skin, in which styles for these several button classes and dozens of other elements are defined, is described in the following section. if you want to use the classes already defined in mozilla's global skin to style your elem...
... be skinned, like mozilla, you probably want your xul file to pick up the global changes when the application is dynamically reskinned. to keep your xul looking consistent and to avoid breaking skins altogether (when your styles have some dependency on a part of the global skin that changes, such as an image), use the style rules in the global skin by importing it into your stylesheet with the following instruction: @import url("chrome://global/skin/"); refer to the document writing skinnable xul and css for guidelines on how to make your skins friendly to the global skin, to xul, and to mozilla. stylesheet syntax to familiarize yourself with the global skin, open up the text file called global.css in the chrome/classic.jar!/skin/classic/global directory of the mozilla application. in a ...
...And 8 more matches
textbox - Archive of obsolete content
disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. focused ...
...ute is true if the element is focused. emptytext deprecated since gecko 2 type: string a string that appears in the textbox when it has no value. this is superseded by the placeholder attribute in gecko 2.0. the old name is retained for compatibility, but you should update your code. hidespinbuttons type: boolean if true, the number box does not have arrow buttons next to it to allow the user to adjust the value. the value may still be adjusted with the keyboard. the default value is false. increment type: integer the amount by which the curpos (for scroll bars) or value (for number boxes and scale) attribute changes when the arrows are clicked(or scales are dragged). the default value is 1. label type: string if present and not empty, this w...
...agged). the default value is 1. 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. ...
...And 8 more matches
tree - Archive of obsolete content
Archive › Mozilla › XUL › tree
r 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 scrolled, simply set the width attributes for each column to make the tree wider than its containing object. tree type view interfaces has dom nodes? description content tre...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. disablek...
... more letters with select more specific items. this feature may be disabled by setting this attribute to true. editable type: boolean indicates that the cells of the tree may be edited. enablecolumndrag type: boolean when set to true, the user may drag the column headers around to change the order in which they are displayed. flags type: space-separated list of the values below a set of flags used for miscellaneous purposes. two flags are defined, which may be the value of this attribute. dont-test-empty: for template generated content, the builder will not check that a container is empty. dont-build-content: this flag may be used on a tree to indicate that content elements should not be generated. this results in a performance enhancement, but you will not be ab...
...And 8 more matches
treecol - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a column of a tree. it displays the column header and holds the size and other information about the column. you can also place splitter elements between the columns to allow column resizing. you should always place an id attribute on a treecol element to ensure that the column positioning is handled properly. more information is available in the xul tutorial. attributes crop, cycler, dragging, editable, fixed, hidden, hideheader, ignoreincolumnpicker, label, primary, sort, sortactive, sortdirection, src, type, width properties accessibletype style classes treecol-image examples this example shows a checkbox in the first column, requires the style below. <tree flex="1" edi...
...on firefox 2.x and 3.x, all operating systems other than mac os x already use these styles by default. if targeting firefox for mac os x, be sure to use these styles but include your own checkbox image. however, chrome://global/skin/checkbox/cbox-check.gif is available in seamonkey on mac os x.. treechildren::-moz-tree-checkbox { ...
...ecify a url to an image in your extension or elsewhere. */ list-style-image: url("chrome://global/skin/checkbox/cbox-check.gif"); } for example: create a css file. copy and paste the code above and link the css file to your xul file. reload the page to see the checkbox. if you want, you can also style the tree using css. 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. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...And 8 more matches
Adobe Flash - Archive of obsolete content
c 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. ...
...ra), 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 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 ...
...r where major can be a major revision such as "5" or "6" and minor is the subsidiary version number. example 1 also creates a constant flashversionosxscriptable that declares (arbitrarily) that macromedia will fix flash to be scriptable in mach-o browsers (on os x) by version 12. this is currently not the case, but 12 is a sufficiently high version number (current versions are version 6r.79) to allow for some leeway for fixing this down the road. when information about when this problem on mac os x will be addressed becomes available, the constant can be updated to reflect something less arbitrary. a complete code listing which expands on the above approach can be found in the flashversion.js file used in the samples. performance and flash as is the case with any plug-in content, flash cont...
...And 8 more matches
Move the ball - Game development
, 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(). ...
... 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. ...
... making it move you won't notice the ball being repainted constantly at the moment, as it's not moving. ...
...And 8 more matches
Player paddle and controls - Game development
with. rendering the paddle from the framework point of view the paddle is very similar to the ball — we need to add a variable to represent it, load the relevant image asset, and then do the magic. ...
...e following new load.image() call: function preload() { // ... game.load.image('ball', 'img/ball.png'); game.load.image('paddle', 'img/paddle.png'); } adding the paddle graphic just so we don't forget, at this point you should grab the paddle graphic from github, and save it in your /img folder. rendering the paddle, with physics next up, we will init our paddle by adding the following add.sprite() call inside the create() function — add it right at the bottom: paddle = game.add.sprite(game.world.width*0.5, game.world.height-5, 'paddle'); we can use the world.width and world.height values to position the paddle exactly where we want it: game.world.width*0.5 will be right in the middle of the screen. in our case the world is the same as the canvas, but for other types of...
...s you'll notice if you reload your index.html at this point, the paddle is currently not exactly in the middle. why? because the anchor from which the position is calculated always starts from the top left edge of the object. we can change that to have the anchor in the middle of the paddle's width and at the bottom of it's height, so it's easier to position it against the bottom edge. ...
...And 8 more matches
Handling different text directions - Learn web development
what are writing modes? a writing mode in css refers to whether the text is running horizontally or vertically. the writing-mode property lets us switch from one writing mode to another. you don't need to be working in a language which uses a vertical writing mode to want to do this — you could also change the writing mode of parts of your layout for creative purposes. ...
...sentences run vertically. ...
...e below we have a heading displayed using writing-mode: vertical-rl. the text now runs vertically. vertical text is common in graphic design, and can be a way to add a more interesting look and feel to your web design. the three possible values for the writing-mode property are: horizontal-tb: top-to-bottom block flow direction. sentences run horizontally. vertical-rl: right-to-left block flow direction. sentences run vertically. vertical-lr: left-to-right block flow direction. sentences run vertically. so the writing-mode property is in reality setting the direction in which block-level elements are displayed on the page — either from top-to-bottom, right-to-left, or left-to-right. this then dictates the direction text flows in sentences. writing modes and block and inline layou...
...And 8 more matches
Images, media, and form elements - Learn web development
er elements. as we will see however, there are various things that css can do with an image. certain replaced elements, such as images and video, are also described as having an aspect ratio. this means that it has a size in both the horizontal (x) and vertical (y) dimensions, and will be displayed using the intrinsic dimensions of the file by default. ...
...zontal (x) and vertical (y) dimensions, and will be displayed using the intrinsic dimensions of the file by default. sizing images as you already know from following these lessons, everything in css generates a box. if you place an image inside a box that is smaller or larger than the intrinsic dimensions of the image file in either direction, it will either appear smaller than the box, or overflow the box. you need to make a decision about what happens with the overflow. ...
...he file by default. sizing images as you already know from following these lessons, everything in css generates a box. if you place an image inside a box that is smaller or larger than the intrinsic dimensions of the image file in either direction, it will either appear smaller than the box, or overflow the box. you need to make a decision about what happens with the overflow. in the example below we have two boxes, both 200 pixels in size: one contains an image which is smaller than 200 pixels — it is smaller than the box and doesn't stretch to fill it. the other is larger than 200 pixels and overflows the box. so what can we do about the overflowing issue? as we learned in our previous lesson, a common technique is to make the max-width of an image 100%. this will enable the i...
...And 8 more matches
Responsive design - Learn web development
iew: css layout next in the early days of web design, pages were built to target a particular screen size. if the user had a larger or smaller screen than the designer expected, results ranged from unwanted scrollbars to overly long line lengths, and poor use of space. as more diverse screen sizes became available, the concept of responsive web design (rwd) appeared, a set of practices that allows web pages to alter their layout and appearance to suit different screen widths, resolutions, etc. it is an idea that changed the way we design for a multi-device web, and in this article, we'll help you understand the main techniques you need to know to master it. prerequisites: html basics (study introduction to html), and an idea of how css works (study css first steps and css bui...
...in history you had two options when designing a website: you could create a liquid site, which would stretch to fill the browser window or a fixed width site, which would be a fixed size in pixels. these two approaches tended to result in a website that looked its best on the screen of the person designing the site! the liquid site resulted in a squashed design on smaller screens (as seen below) and unreadably long line lengths on larger ones. note: see this simple liquid layout: example, source code. when viewing the example, drag your browser window in and out to see how this looks at different sizes. the fixed-width site risked a horizontal scrollbar on screens smaller than the site width (as seen below), and lots of white space at the edges of the design on larger screens. ...
...ticle, fluid grids (published in 2009 on a list apart). the second technique was the idea of fluid images. using a very simple technique of setting the max-width property to 100%, images would scale down smaller if their containing column became narrower than the image's intrinsic size, but never grow larger. this enables an image to scale down to fit in a flexibly-sized column, rather than overflow it, but not grow larger and become pixellated if the column becomes wider than the image. the third key component was the media query. media queries enable the type of layout switch that cameron adams had previously explored using javascript, using only css. rather than having one layout for all screen sizes, the layout could be changed. sidebars could be repositioned for the smaller screen, or ...
...And 8 more matches
How to structure a web form - Learn web development
u explicitly bind a control with a form even if it is not nested inside it. let's move forward and cover the structural elements you'll find nested in a form. the <fieldset> and <legend> elements the <fieldset> element is a convenient way to create groups of widgets that share the same purpose, for styling and semantic purposes. you can label a <fieldset> by including a <legend> element just below the opening <fieldset> tag. the text content of the <legend> formally describes the purpose of the <fieldset> it is included inside. many assistive technologies will use the <legend> element as if it is a part of the label of each control inside the corresponding <fieldset> element. for example, some screen readers such as jaws and nvda will speak the legend's content before speaking the label o...
...el to activate the corresponding widget. this is useful for controls like text inputs, where you can click the label as well as the input to focus it, but it is especially useful for radio buttons and checkboxes — the hit area of such a control can be very small, so it is useful to make it as easy to activate as possible. ...
...find this example in checkbox-label.html (see it live also). multiple labels strictly speaking, you can put multiple labels on a single widget, but this is not a good idea as some assistive technologies can have trouble handling them. in the case of multiple labels, you should nest a widget and its labels inside a single <label> element. ...
...And 8 more matches
Styling web forms - Learn web development
t we can now use css to style many form features, though we do need to take extra care to ensure we don't break usability. not all widgets are created equal when css is involved at present, some difficulties remain when using css with forms. these problems can be divided into three categories: the good some elements can be styled with few if any problems across platforms. these include the following elements: <form> <fieldset> and <legend> single-line text <input>s (e.g. type text, url, email...), except for <input type="search">. multi-line <textarea>s buttons (both <input> and <button>s) <label> <output> the bad some elements are more difficult to style, requiring more complex css or some more specific tricks: checkboxes and radio buttons <input type="search"> we descr...
...<select> that causes the options list to display) making up those widgets. if you want to thoroughly customize those widgets, you really have to create your own using html, css, and javascript. this is beyond the scope of the core form articles, but we do look at this in an advanced article how to build custom form controls. note: there are some proprietary css pseudo-elements available that allow you to style internal components of these form controls, such as ::-moz-range-track, but these are not consistent across browsers, so can't be relied upon. we will mention these later as well. the good to style form controls that are easy to style with css, you shouldn't face much if any difficulties, since they mostly behave like any other html element. we already looked at some simple form s...
... css font and text features can be used easily with any widget (and yes, you can use @font-face with form widgets). however, browser behavior is often inconsistent. by default, some widgets do not inherit font-family and font-size from their parents. many browsers use the system default appearance instead. to make your forms' appearance consistent with the rest of your content, you can add the following rules to your stylesheet: button, input, select, textarea { font-family: inherit; font-size: 100%; } the inherit property value causes the property value to match the computed value of the property of its parent element; inheriting the value of the parent. the screenshots below show the difference. on the left is the default rendering of an <input type="text">, <input type="date">, <sel...
...And 8 more matches
The web and web standards - Learn web development
eferred to as timbl) wrote a notebook program called enquire, which featured the concept of links between different nodes. sound familiar? fast forward to 1989, and timbl wrote information management: a proposal and hypertext at cern; these two publications together provided the background for how the web would work. ...
...ok, that's a very simple summary of what happened, but i did promise you a brief summary. ...
...ated. ok, that's a very simple summary of what happened, but i did promise you a brief summary. one last significant data point to share is that in 1994, timbl founded the world wide web consortium (w3c), an organization that brings together representatives from many different technology companies to work together on the creation of web technology specifications. after that other technologies followed such as css and javascript, and the web started to look more like the web we know today. web standards web standards are the technologies we use to build web sites. these standards exist as long technical documents called specifications, which detail exactly how the technology should work. these documents are not very useful for learning how to use the technologies they describe (this is why ...
...And 8 more matches
Build your own function - Learn web development
a custom function, and explain a few more useful associated details. active learning: let's build a function the custom function we are going to build will be called displaymessage(). it will display a custom message box on a web page and will act as a customized replacement for a browser's built-in alert() function. we've seen this before, but let's just refresh our memories. type the following in your browser's javascript console, on any page you like: alert('this is a message'); the alert function takes a single argument — the string that is displayed in the alert box. try varying the string to change the message. the alert function is limited: you can alter the message, but you can't easily vary anything else, such as the color, icon, or anything else. we'll build one that wi...
...e. 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 custom message box, and an empt...
...s 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 custom message box, and an empty <script> element to put our javascript in. next, add the following inside the <script> element: function displaymessage() { } we start off with the keyword function, which means we are defining a function. this is followed by the name we want to give to our function, a set of parentheses, and a set of curly braces. any parameters we want to give to our function go inside the parentheses, and the code that runs when we call the function goes inside the cu...
...And 8 more matches
Handling text — strings in JavaScript - Learn web development
gs 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. the power of words words are very important to humans — they are a large part of how we communicate. ...
...n familiarity with the basics of strings in javascript. the power of words words are very important to humans — they are a large part of how we communicate. since the web is a largely text-based medium designed to allow humans to communicate and share information, it is useful for us to have control over the words that appear on it. html provides structure and meaning to our text, css allows us to precisely style it, and javascript contains a number of features for manipulating strings, creating custom welcome messages and prompts, showing the right text labels when needed, sorting terms into the desired order, and much more. pretty much all of the programs we've shown you so far in the course have involved some string manipulation. strings — the basics strings are dealt with s...
...f the programs we've shown you so far in the course have involved some string manipulation. strings — the basics strings are dealt with similarly to numbers at first glance, but when you dig deeper you'll start to see some notable differences. let's start by entering some basic lines into the browser developer console to familiarize ourselves. ...
...And 8 more matches
Inheritance in JavaScript - Learn web development
person, but also includes: a new property, subject — this will contain the subject the teacher teaches. an updated greeting() method, which sounds a bit more formal than the standard greeting() method — more suitable for a teacher addressing some students at school. ...
...but also includes: a new property, subject — this will contain the subject the teacher teaches. an updated greeting() method, which sounds a bit more formal than the standard greeting() method — more suitable for a teacher addressing some students at school. ...
...the first parameter specifies the value of this that you want to use when running the function, and the other parameters are those that should be passed to the function when it is invoked. ...
...And 8 more matches
Starting our Svelte Todo list app - Learn web development
ctive tasks, or completed tasks. edit tasks. mark all tasks as active/completed. remove all completed tasks. building our first component let's create a todos.svelte component — this will contain our list of todos. create a new folder — src/components. ...
...asks, or completed tasks. edit tasks. mark all tasks as active/completed. remove all completed tasks. building our first component let's create a todos.svelte component — this will contain our list of todos. create a new folder — src/components. ...
...ing our first component let's create a todos.svelte component — this will contain our list of todos. create a new folder — src/components. note: you can put your components anywhere inside the src folder, but the components folder is a recognized convention to follow, allowing you to find your components easily. ...
...And 8 more matches
Creating our first Vue component - Learn web development
ing a todoitem component let's create our first component, which will display a single todo item. we'll use this to build our list of todos. in your moz-todo-vue/src/components directory, create a new file named todoitem.vue. open the file in your code editor. create the component's template section by adding <template></template> to the top of the file. ...
...we'll use a <div> for that root element. add an empty <div> inside your component template now. inside that <div>, let's add a checkbox and a corresponding label. ...
...a single root element — one element needs to wrap everything inside the template section (this will change when vue 3 comes out). we'll use a <div> for that root element. add an empty <div> inside your component template now. inside that <div>, let's add a checkbox and a corresponding label. add an id to the checkbox, and a for attribute mapping the checkbox to the label, as shown below. <template> <div> <input type="checkbox" id="todo-item" checked="false" /> <label for="todo-item">my todo item</label> </div> </template> using todoitem inside our app this is all fine, but we haven’t added the component to our app yet, so there’s no way to test it and see if everything is working. let’s add it now. open up app.vue again. at the top of your <...
...And 8 more matches
Command line options
mmand line interface by pressing shift + f2. syntax rules but first, let's describe the syntax rules that apply for all options. command parameters containing spaces must be enclosed in quotes, such as "joel user". command actions are case insensitive. command parameters, except profile names, are case insensitive. blank spaces ( ) separate commands and parameters. ...
...if the option contains arguments, enter the argument after the option. ...
...nd newer: body=c:\path\to\file.txt separate multiple message options by comma (,), for example: "to=foo@nowhere.net,subject=cool page" . comma separators must not follow or precede spaces ( ). to assign multiple values to a field, enclose the values in single quotes ('), for example: "to='foo@nowhere.net,foo@foo.de',subject=cool page" . using command line options command line options follow the command to start the application. if the option contains arguments, enter the argument after the option. some options have abbreviations, for example, "-editor" can be abbreviated as "-edit" (available abbreviations are described in the text below). in some cases, option arguments must be enclosed in quotation marks (this is noted in the option descriptions below). multiple command line optio...
...And 8 more matches
HTTP Cache
oon be completely obsoleted and removed (bug 913828). nsicachestorageservice the http cache entry-point. accessible as a service only, fully thread-safe, scriptable. //github.com/realityripple/uxp/blob/master/netwerk/cache2/nsicachestorageservice.idl "@mozilla.org/netwerk/cache-storage-service;1" provides methods accessing “storage” objects – see nsicachestorage below – giving further access to cache entries – see nsicacheentry more below – per specific url. currently we have 3 types of storages, all the access methods return an nsicachestorage object: memory-only (memorycachestorage): stores data only in a memory cache, data in this storage are never put to disk disk (diskcachestorage): stores data on disk, but for existing...
...urge any intermediate memory structures: clear – after it returns, all entries are no longer accessible through the cache apis; the method is fast to execute and non-blocking in any way; the actual erase happens in background purgefrommemory – removes (schedules to remove) any intermediate cache data held in memory for faster access (more about the intermediate cache below) nsiloadcontextinfo distinguishes the scope of the storage demanded to open. mandatory argument to *storage methods of nsicachestorageservice. //github.com/realityripple/uxp/blob/master/netwerk/base/public/nsiloadcontextinfo.idl it is a helper interface wrapping following four arguments into a single one: private-browsing boolean flag ano...
... immediately); there is currently no way to opt out of this feature (watch bug 938186). nsicacheentry //github.com/realityripple/uxp/blob/master/netwerk/cache2/nsicacheentry.idl obtained asynchronously or pseudo-asynchronously by a call to nsicachestorage.asyncopenuri. provides access to a cached entry data and meta data for reading or writing or in some cases both, see below. lifetime of a new entry such entry is initially empty (no data or meta data is stored in it). the anew argument in oncacheentryavailable is true for and only for new entries. only one consumer (the so called "writer") may have such an entry available (obtained via oncacheentryavailable). other parallel openers of the same cache entry are blocked (wait) for invocation ...
...And 8 more matches
Internationalized Domain Names (IDN) Support in Mozilla Browsers
introduction netscape 7.1 is the first commercial browser that has built-in support for internationalized domain name under the new ietf rfc's established in 2003. an internationalized domain name (idn) is a domain/host name which uses non-ascii characters. until recently domain names allowed only a subset of 7-bit ascii characters. as the internet has spread to non-english speaking people around the world, it has become increasingly clear that forcing them to use domain names written only in a subset of the latin alphabet is not ideal. many of the european languages use the basic latin alphabet with additional accented characters for writing but they were not able to use them in domain names. there are many languages whose writing scripts are not based on latin alphabet at all. sp...
... non-ascii characters in domain names. how idn works when a browser sees a host name such as http://developer.mozilla.org, it passes a request to the dns resolver service (usually built into an os), which in turn sends a request to a nearest domain name server to return an ip address that corresponds to the host name. this ip address is then used to connect to the web server in question. idn allows host/domain names with non-ascii characters for user input into a browser's location bar or url's embedded in web pages. at the network protocol level, there is no change in the restriction that only a subset of ascii characters be used in url/uri. if end users input non-ascii characters as part of a domain name or if a web page contains a link using a non-ascii domain name, the application must...
...existing host name character restrictions. how mozilla browsers handle non-ascii domain names unicode and nameprep when mozilla receives idn input from the user via the location 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. ...
...And 8 more matches
Index
internationalization, localization when creating a localization for mozilla products, it’s important to be aware of the encoding of the files that you generate. 5 index localization found 42 pages: 6 l10n checks internationalization, localization, localization:tools, tools l10n checks is a python script and library similar to compare-locales. it allows mozilla localizers to easily check their work. 7 l10n testing with xcode firefox for ios, localization once you have your l10n testing environment set up in xcode, testing your firefox on ios localization is a breeze. 8 localization and plurals internationalization, localization you're likely here because you're localizing a .properties file and it had a...
...l setup! as a reward for your efforts, you get to move on to the very reason you've come here: to localize mozilla projects. 17 localization sign-off reviews guide, localization, mozilla this article presents an overview of why we do sign-off reviews of localizations, the details on the criteria used for the sign-off reviews, and the process for requesting a review and for following its progress. 18 localization technical reviews guide, localization, mozilla this guide provides details on what a localization technical review is, what criteria are used for the technical reviews, and the process for requesting one and following its progress. 19 localization: frequently asked questions faq, guide, internationalization, localization, mozill...
... this tutorial will guide you through making a couple of changes to firefox's user interface using koala, an add-on for komodo edit created to help localizing mozilla. 24 localizing with mercurial build documentation, internationalization, localization in mozilla, we use the the mercurial version control system (hg) to manage our source code and localizations. mercurial allows localizers to work locally (on their machines) and then push (an hg term) changes to a remote repository, which usually is hosted on the mozilla servers (hg.mozilla.org). localizing current versions of firefox, thunderbird and seamonkey includes working with mercurial. if the documentation is incomplete or you have questions, please drop by the #l10n or #hg channels on irc.mozilla.org. the mercu...
...And 8 more matches
MathML Accessibility in Mozilla
we started exposing generic accessible objects for mathml in bug 920547 and so these can be retrieved by nvda starting with gecko 27.0 (firefox 27.0 / thunderbird 27.0 / seamonkey 2.24). mozilla and nvda developers essentially do not have control on how mathematical formulas are read, please contact design science for any inquiries. mac: mathml support is provided by voiceover. in bug 1175269 and bug 1001641, we relied on the webkit's nsaccessibility mathml tree to expose the main constructions. ...
..._____ a raised to the b __________ a, superscript b a. superscript b a base b superscript scripted abc __________ a sub b to the c __________ a, subscript b, superscript c a. ...
...see webkit's bug 146407 a. underscript b overscript c a base b underscript c overscript scripted a __________ the square root of a __________ square root of a, end of root square root of a. root end. ...
...And 8 more matches
Mozilla Web Services Security Model
used as a tool for web sites to obtain priveleges that belong to the browser's user (such as being behind a firewall or getting the benefits of the user's cookies), web browsers restrict what web pages can do when accessing things in other domains. these restrictions 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.exampl...
...eb 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 failures to follow the format, will cause the document to be ignored. the webscriptaccess element its root element must be a webscriptaccess element in the http://www.mozilla.org/2002/soap/security namespace. this element must have either one delegate element child or any number (0 or more) of allow element children. all of these children elements must be in the same namespace as the parent, and must be empty. t...
...e 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. ...
...And 8 more matches
Gecko Profiler FAQ
is it possible to locate hot spots occurring within a single function? the gecko profiler currently doesn’t have the ability to show you information about line numbers, neither for js code nor for native code. ...
... 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 samples / stacks will not be meaningful. profiler.firefox.com does not have a comparison view at the moment. i can help you add one, though. there is documentation for the gecko profile format. is it worth slowing down cpu to increase the profiler resolution? it depends on what you are trying to profile to some extent. usually you should be really careful when changing the characteristics of the environment that you are trying to measure to avoid measuring the wrong thing. if the issue you are trying to avoid is not profiling on fast machines that mozilla developers typically us...
...to profile to some extent. usually you should be really careful when changing the characteristics of the environment that you are trying to measure to avoid measuring the wrong thing. if the issue you are trying to avoid is not profiling on fast machines that mozilla developers typically use to build firefox on, a better solution may be using a less high-end machine that actually has lower spec’d hardware instead of artificially slowing down just the cpu. 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 fo...
...And 8 more matches
An overview of NSS Internals
rtability layer, called the netscape portable runtime (nspr), which provides cross platform application programming interfaces (apis) for os specific apis like file system access, memory management, network communication, and multithreaded programming. nss offers lots of functionality; we'll walk through the list of modules, design principles, and important relevant standards. ...
...rder to allow interoperability between software and devices that perform cryptographic operations, nss conforms to a standard called pkcs#11. (note that it's important to look at the number 11, as there are other pkcs standards with different numbers that define quite different topics.) a software or hardware module conforming to the pkcs#11 standard implements an interface of c calls, which allow querying the characteristics and offered services of the module. multiple elements of nss's own modules have been implemented with this interface, and nss makes use of this interface when talking to those modules. ...
...ifferent numbers that define quite different topics.) a software or hardware module conforming to the pkcs#11 standard implements an interface of c calls, which allow querying the characteristics and offered services of the module. multiple elements of nss's own modules have been implemented with this interface, and nss makes use of this interface when talking to those modules. this strategy allows nss to work with many hardware devices (e.g., to speed up the calculations required for cryptographic operations, or to access smartcards that securely protect a secret key) and software modules (e.g., to allow to load such modules as a plugin that provides additional algorithms or stores key or trust information) that implement the pkcs#11 interface. a core element of nss is freebl, a base l...
...And 8 more matches
NSS 3.12.6 release notes
nss 3.12.6 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1. distribution information the cvs tag for the nss 3.12.6 release is nss_3_12_6_rtm. nss 3.12.6 requires nspr 4.8.4. ...
...nd shared libraries, which nss 3.12.6 requires. nspr 4.8.4 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.8.4/. ...
...tiation indication extension (rfc 5746) by default, nss 3.12.6 uses the new tls renegotiation indication extension for tls renegotiation but allows simple ssl/tls connections (without renegotiation) with peers that don't support the tls renegotiation indication extension. the behavior of nss for renegotiation can be changed through api function calls, or with the following environment variables: nss_ssl_enable_renegotiation values: [0|n|n]: ssl_renegotiate_never never allow renegotiation - that was the default for 3.12.5 release. [1|u|u]: ssl_renegotiate_unrestricted ...
...And 8 more matches
How to embed the JavaScript engine
see also jsapi user guide. in particular, it has more and better code examples! a bare bones tutorial hello world sample embedding application the following code is a very simple application that shows how to embed spidermonkey and run a simple javascript script. see the instructions for building and running the sample below the code. the code differs for each spidermonkey version, please choose right version for your spidermonkey. spidermonkey 24 // following code might be needed in some case // #define __stdc_limit_macros // #include <stdint.h> #include "jsapi.h" /* the class of the global object. */ static jsclass global_class = { "global", jsclass_global_flags, js_propertystub, js_deletepropertystub, js_propertystub, js_strictpropertystub, js_enumerates...
...*/ static jsclass global_class = { "global", jsclass_global_flags, js_propertystub, js_deletepropertystub, js_propertystub, js_strictpropertystub, js_enumeratestub, js_resolvestub, js_convertstub, nullptr, nul...
...*/ static jsclass global_class = { "global", jsclass_global_flags, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, js_globalobjecttracehook }; in...
...And 8 more matches
JSAPI User Guide
posed to scripts. hello world using the spidermonkey library to build spidermonkey from source, see spidermonkey build documentation. some systems (such as debian) provide spidermonkey as a prebuilt package. build it from source instead. your program will be easier to debug. c++ code accesses spidermonkey via the jsapi, by including the header "jsapi.h". an overview of jsapi functionality follows. for more details, see the jsapi reference. the spidermonkey universe in order to run any javascript code in spidermonkey, an application must have three key elements: a jsruntime, a jscontext, and a global object. this section describes what these things are. the next section explains how to set them up, using jsapi functions. runtimes. a jsruntime, or runtime, is the space in which the java...
..., it is accessing a global property, in this case window. jsapi applications have full control over what global properties scripts can see. the application starts out by creating an object and populating it with the standard javascript classes, like array and object. then it adds whatever custom classes, functions, 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 requ...
...maximum ecmascript standard compliance, applications should also use js_setoptions to enable jsoption_varobjfix. to get the latest javascript language features, applications may use js_setversion. error reporting is also per-context and is enabled using js_seterrorreporter. the global object: to create this object, you first need a jsclass with the jsclass_global_flags option. the example below defines a very basic jsclass (named global_class) with no methods or properties of its own. use js_newglobalobject to create a global object. use js_initstandardclasses to populate it with the standard javascript globals. 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 ne...
...And 8 more matches
History Service Design
irefox bookmarks and history systems using storage. this system provides additional performance, flexibility, and querying capabilities over the old one, for both end users and extensions developers. view the service interface definition: nsinavhistoryservice.idl. objectives the primary objectives of the new history service implementation in places are: improve access to browsing history allow association of useful metadata with urls flexible query system for both end-users and add-ons developers clean architecture for ease of code reuse and maintainability the most known and visible feature of history are views. the user can query his visits based on a date range, meta contents or revisit behavior. this involves storing informations on all of the user's visits, including visit tim...
...of history are views. the user can query his visits based on a date range, meta contents or revisit behavior. this involves storing informations on all of the user's visits, including visit time, type of visit and meta data. ...
...ring informations on all of the user's visits, including visit time, type of visit and meta data. old history system was instead only storing first and last visit date, and a generic visits counter, creating some problem due to the impossibility to represent real history flow in a timeframe. history views must be organized and as concise as possible. each visit is associated with a favicon, to allow for better recognizability and groupable by common timeframes or domains. ...
...And 8 more matches
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. ...
... 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. ...
...ed by a nscstringcontainer instance.ns_cstringcontainerinitthe ns_cstringcontainerinit function initializes a nscstringcontainer instance for use as a nsacstring.ns_cstringcontainerinit2the ns_cstringcontainerinit2 function initializes a nscstringcontainer instance for use as a nsacstring.ns_cstringcopythe ns_cstringcopy function copies the value from one nsacstring instance to another. ...
...And 8 more matches
Getting Started Guide
ence has relinquished its claim. not all references need to be owning references. in fact, if two objects somehow end up owning each other (even transitively) it becomes difficult for either of those object to be reclaimed without adding some `out-of-band' mechanism for breaking the ownership cycle. the document some com ownership guidelines provides some hints on when ownership is needed. the following lists are good starting point, but by no means complete. you use an owning reference when you created the object; you got the object from a function that might have created it, e.g., any `getter' function, such as queryinterface, or createinstance. all good getters addref the interface pointers they produce, thus providing you with an owning reference; you will hold onto the reference lo...
...ted it, e.g., any `getter' function, such as queryinterface, or createinstance. all good getters addref the interface pointers they produce, thus providing you with an owning reference; you will hold onto the reference longer than the scope of the function in which you acquired it, e.g., you got it as a parameter, but you're hanging onto it in a member variable (see, for example, comparison 1, below). you don't need an owning reference when the object is passed in as a parameter, and you don't need to keep it any longer than the scope of this function; the object's lifetime is known to contain yours in some well defined way, e.g., in the nodes of a tree, parent nodes keep owning references to their children, children need not keep owning references to their parents. it turns out that...
... parents. it turns out that reference counting by hand is hard for programmers to get right. it may sound simple, but in practice it's very easy to forget to release at the appropriate moment. or to addref too many or too few times. how does nscomptr help? nscomptr manages addref, release, and other red-tape for you. an nscomptr looks and acts as much like a raw xpcom interface pointer as c allows, but it knows it owns the object it points to. this takes a little getting used to on your part, but ends up with less typing, clearer, safer code, and less leaks. for instance, here is a typical snippet of code (at its most compact) where you assign a xpcom interface pointer into a member variable, i.e., the body of a `setter' function, side-by-side using raw xpcom interface pointers and nscom...
...And 8 more matches
Using Objective-C from js-ctypes
t cannot be written directly with js-ctypes. this guide explains how to convert objective-c code into js-ctypes code. a simple example is also in standard os libraries page. converting objective-c code to c code to convert objective-c code to js-ctypes, we need to convert it to c code first. we can then convert it straight to js-ctypes code. speech synthesis example let's start with the following objective-c code, which invokes the speech synthesis api to say "hello, firefox!". it uses the default system voice and waits until the speaking is done. #import <appkit/appkit.h> int main(void) { nsspeechsynthesizer* synth = [[nsspeechsynthesizer alloc] initwithvoice: nil]; [synth startspeakingstring: @"hello, firefox!"]; // wait until start speaking. while (![synth isspeaking]) {}...
...eaking is done. #import <appkit/appkit.h> int main(void) { nsspeechsynthesizer* synth = [[nsspeechsynthesizer alloc] initwithvoice: nil]; [synth startspeakingstring: @"hello, firefox!"]; // wait until start speaking. while (![synth isspeaking]) {} // wait while speaking. ...
...[synth isspeaking]) {} // wait while speaking. while ([synth isspeaking]) {} [synth release]; return 0; } save this file as test.m, and run with the following command, inside the same directory as the saved file (needs xcode). $ clang -framework appkit test.m && ./a.out class, message, and selector our task at hand is to convert objective-c syntax to c syntax. let's look at the following codelet: [nsspeechsynthesizer alloc] it passes an alloc message to the nsspeechsynthesizer class, in objective-c syntax. it performs the following through this objective-c syntax: get the nsspeechsynthesizer class definition. register the alloc selector for the message. send a message to the class, with the selector. get a reference to a class class definitions are retrieved with th...
...And 8 more matches
MediaDevices.getUserMedia() - Web APIs
ch as a camera, video recording device, screen sharing service, and so forth), an audio track (similarly, produced by a physical or virtual audio source like a microphone, a/d converter, or the like), and possibly other track types. it returns a promise that resolves to a mediastream object. if the user denies permission, or matching media is not available, then the promise is rejected with notallowederror or notfounderror respectively. note: it's possible for the returned promise to neither resolve nor reject, as the user is not required to make a choice at all and may simply ignore the request. generally, you will access the mediadevices singleton object using navigator.mediadevices, like this: async function getmedia(constraints) { let stream = null; try { stream = await nav...
...media to request, along with any requirements for each type. the constraints parameter is a mediastreamconstraints object with two members: video and audio, describing the media types requested. either or both must be specified. if the browser cannot find all media tracks with the specified types that meet the constraints given, then the returned promise is rejected with notfounderror. the following requests both audio and video without any specific requirements: { audio: true, video: true } if true is specified for a media type, the resulting stream is required to have that type of track in it. if one cannot be included for any reason, the call to getusermedia() will result in an error. while information about a user's cameras and microphones are inaccessible for privacy reasons, a...
... for a media type, the resulting stream is required to have that type of track in it. if one cannot be included for any reason, the call to getusermedia() will result in an error. while information about a user's cameras and microphones are inaccessible for privacy reasons, an application can request the camera and microphone capabilities it needs and wants, using additional constraints. ...
...And 8 more matches
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...
... a single byte, or it can be something larger such as a typed array of a certain size. a single stream can contain chunks of different sizes and types. the chunks placed in a stream are said to be enqueued — this means they are waiting in a queue ready to be read. ...
...ontain chunks of different sizes and types. the chunks placed in a stream are said to be enqueued — this means they are waiting in a queue ready to be read. an internal queue keeps track of the chunks that have not yet been read (see the internal queues and queuing strategies section below). the chunks inside the stream are read by a reader — this processes the data one chunk at a time, allowing you to do whatever kind of operation you want to do on it. the reader plus the other processing code that goes along with it is called a consumer. there is also a construct you’ll use called a controller — each reader has an associated controller that allows you to control the stream (for example, to cancel it if wished). only one reader can read a stream at a time; when a reader is crea...
...And 8 more matches
Cognitive accessibility - Accessibility
w3c), the main international standards organization for the internet. this group is also responsible for the accessible rich internet application (aria) guidelines. wcag are guided by four principles: websites must be perceivable, operable, understandable, and robust. to this end, they define 17 specific guidelines, of which six are especially relevant for cognitive accessibility. all of the following guidelines help more than just people with cognitive disabilities. for example, being able to extend the expiration time on an application requiring an authentication code sent to a mobile device via text message helps with the following scenarios: people with attention or anxiety disorders. people who have a poor short-term memory, or who are multitasking. people who are less technologic...
...uding structure and relationships conveyed through the presentation, should be available in a form that can be perceived by all users to achieve this goal. for example, the information could be spoken aloud via a narration tool. making your content capable of being 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 ...
...sis, 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 time to at least 10 times the original limit before encountering it. alerting the user and providing a buffer of at least 20 seconds to extend the timeout duration by a factor of 10 with a simple action, such as hitting the space bar. provide a toggle on content that allows users to enable a longer session time limit, or no session time limit at all. exam...
...And 8 more matches
Accessibility documentation index - Accessibility
specially those developed with javascript) more accessible to people with disabilities. it supplements html so that interactions and widgets commonly used in applications can be passed to assistive technologies 3 aria screen reader implementors guide aria, accessibility this is just a guide. live region markup is a complex area which is somewhat open to interpretation. the following is intended to provide implementation guidance that respects screen readers developers' need to try different things. the intention is to strike a balance between providing useful guidance on how to use the markup's intended meaning while supporting live regions as an area for screen readers to innovate and compete. 4 aria test cases aria, accessibility for each example we...
...ilure 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 deletion in an editable document), and comments (e.g. an editorial comment related to a part of a document under review). 6 aria guides aria accessible rich internet applications (aria) defines ways to make the web more accessible to people with dis...
...tions inside web documents. typical use cases include edit suggestions (i.e. an addition and/or deletion in an editable document), and comments (e.g. an editorial comment related to a part of a document under review). 6 aria guides aria accessible rich internet applications (aria) defines ways to make the web more accessible to people with disabilities. a few guidelines to follow that ensure better accessibility, like using drag and drop for placement of the widgets. 7 aria live regions aria, accessibility, arialive using javascript, it is possible to dynamically change parts of a page without requiring the entire page to reload — for instance, to update a list of search results on the fly, or to display a discreet alert or notification which does n...
...And 8 more matches
CSS values and units - CSS: Cascading Style Sheets
refer to the page for each value type for more detailed information. ...
...t it to be any other pre-defined css keyword. see the <custom-ident> and <string> reference pages for more details. pre-defined keyword values pre-defined keywords are text values defined by the specification for that property. these keywords are also css identifiers and are therefore used without quotes. when viewing css property value syntax in a css specification or the mdn property page, allowable keywords will be listed in the following form. the following values are the pre-defined keyword values allowed for float. left | right | none | inline-start | inline-end such values are used without quotes: .box { float: left; } css-wide values in addition to the pre-defined keywords that are part of the specification for a property, all css properties accept the css-wide property v...
...nding on whether the property is inherited or not. a fourth value of revert was added in the cascade level 4 specification, but it does not currently have good browser support. urls a <url> type uses functional notation, which accepts a <string> that is a url. this may be an absolute url or a relative url. for example, if you wanted to include a background image, you might use either of the following. .box { background-image: url("images/my-background.png"); } .box { background-image: url("https://www.exammple.com/images/my-background.png"); } the parameter for url() can be either quoted or unquoted. if unquoted, it is parsed as a <url-token>, which has extra requirements including the escaping of certain characters. see <url> for more information. numeric data types <integer>...
...And 8 more matches
Using media queries - CSS: Cascading Style Sheets
to target specific media for the <style>, <link>, <source>, and other html elements with the media= attribute. ...
...aced by speech, which is similar. media features media features describe specific characteristics of the user agent, output device, or environment. media feature expressions test for their presence or value, and are entirely optional. each media feature expression must be surrounded by parentheses. name summary notes any-hover does any available input mechanism allow the user to hover over elements? added in media queries level 4. any-pointer is any available input mechanism a pointing device, and if so, how accurate is it? added in media queries level 4. aspect-ratio width-to-height aspect ratio of the viewport color number of bits per color component of the output device, or zero if the device isn't color ...
...lay mode of the application, as specified in the web app manifest's display member defined in the web app manifest spec. forced-colors detect whether user agent restricts color palette added in media queries level 5. grid does the device use a grid or bitmap screen? height height of the viewport hover does the primary input mechanism allow the user to hover over elements? added in media queries level 4. inverted-colors is the user agent or underlying os inverting colors? added in media queries level 5. light-level light level of the environment added in media queries level 5. monochrome bits per pixel in the output device's monochrome frame buffer, or zero if the device isn't monochrome ...
...And 8 more matches
Specificity - CSS: Cascading Style Sheets
ecificity, 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 no effect on the specificity. selector types the following list of selector types increases by specificity: type selectors (e.g., h1) and pseudo-elements (e.g., ::before). class selectors (e.g., .example), attributes selectors (e.g., [type="radio"]) and pseudo-classes (e.g., :hover). id selectors (e.g., #example). universal selector (*), combinators (+, >, ~, ' ', ||) and negation pseudo-class (:not()) have no effect on specificity. (the select...
...an { color: green; } div span { color: blue; } span { color: red; } no matter the order, text will be green because that rule is most specific. (also, the rule for blue overwrites the rule for red, notwithstanding the order of the rules) as a nonsense special case for (2), duplicate simple selectors to increase specificity when you have nothing more to specify. #myid#myid span { color: yellow; } .myclass.myclass span { color: orange; } how !important can be used: a) overriding inline styles your global css file that sets visual aspects of your site globally may be overwritten by inline styles defined directly on individual elements. both inline styles and !important are considered very bad practice, but sometimes you need the latter to override the former. in this case, you cou...
...the original rule to avoid the use of !important altogether. [id="someelement"] p { color: blue; } p.awesome { color: red; } including an id as part of an attribute selector instead of as an id selector gives it the same specificity as a class. both selectors above now have the same weight. in a specificity tie, the last rule defined wins. ...
...And 8 more matches
<input type="number"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › number
lue can, however, still be changed by javascript code directly 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 a...
... using number inputs <input type="number"> elements can help simplify your work when building the user interface and logic for entering numbers into a form. ...
...r html behind the scenes, so your site must not use simple client-side validation for any security purposes. you must verify on the server side any transaction in which the provided value may have any security implications of any kind. mobile browsers further help with the user experience by showing a special keyboard more suited for entering numbers when the user tries to enter a value. the following screenshot is taken from firefox for android: a simple number input in its most basic form, a number input can be implemented like this: <label for="ticketnum">number of tickets you would like to buy:</label> <input id="ticketnum" type="number" name="ticketnum" value="0"> a number input is considered valid when empty and when a single number is entered, but is otherwise invalid. if the...
...And 8 more matches
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
ich 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 browser shows its own set of controls (e.g. when the controls attribute is specified). the allowed values are nodownload, nofullscreen and noremoteplayback. use t...
...tribute is specified). the allowed values are nodownload, nofullscreen and noremoteplayback. use the disablepictureinpicture attribute if you want to disable the picture-in-picture 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-credential...
... when not present, the resource is fetched without a cors request (i.e. without sending the origin: http header), preventing its non-tainted used in <canvas> elements. if invalid, it is handled as if the enumerated keyword anonymous was used. ...
...And 8 more matches
Content Security Policy (CSP) - HTTP
Web › HTTP › CSP
e 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. ...
...rs 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 (including inline scripts and event-handling html attributes). as an ultimate form of protection, sites that want to never allow scripts to be executed can opt to globally disallow script execution. mitigating packet sniffing attacks in addition to restricting the domains from which content can be loaded, the server can specify which protocols are allowed to be used; for example (and ideally, from a security standpoint), a server can specify that all content must be loaded using https. a complete data transmission securi...
...te and providing automatic redirects from http pages to their https counterparts. sites may also use the strict-transport-security http header to ensure that browsers connect to them only over an encrypted channel. using csp configuring content security policy involves adding the content-security-policy http header to a web page and giving it values to control what resources the user agent is allowed to load for that page. for example, a page that uploads and displays images could allow images from anywhere, but restrict a form action to a specific endpoint. a properly designed content security policy helps protect a page against a cross site scripting attack. this article explains how to construct such headers properly, and provides examples. specifying your policy you can use the conten...
...And 8 more matches
CSP: base-uri - HTTP
the http content-security-policy base-uri directive restricts the urls which can be used in a document's <base> element. if this value is absent, then any uri is allowed. if this directive is absent, the user agent will use the value in the <base> element. csp version 2 directive type document directive default-src fallback no. not setting this allows any url. ...
...rective restricts the urls which can be used in a document's <base> element. if this value is absent, then any uri is allowed. if this directive is absent, the user agent will use the value in the <base> element. csp version 2 directive type document directive default-src fallback no. not setting this allows any url. ...
...the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as the port number, indicating that all legal ports are valid for the source. ...
...And 8 more matches
CSP: default-src - HTTP
the http content-security-policy (csp) default-src directive serves as a fallback for the other csp fetch directives. ...
...the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may us...
...src script-src script-src-elem script-src-attr style-src style-src-elem style-src-attr worker-src csp version 1 directive type fetch directive syntax one or more sources can be allowed for the default-src policy: content-security-policy: default-src <source>; content-security-policy: default-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as the port number, indicating that all legal ports are valid for the source. examples: http://*.example.com: matches all attempts to load from any s...
...And 8 more matches
Numbers and dates - JavaScript
also javascript data types and structures for context with other primitive types in javascript. you can use four types of number literals: decimal, binary, octal, and hexadecimal. decimal numbers 1234567890 42 // caution when using leading zeros: 0888 // 888 parsed as decimal 0777 // parsed as octal in non-strict mode (511 in decimal) note that decimal literals can start with a zero (0) followed by another decimal digit, but if every digit after the leading 0 is smaller than 8, the number gets parsed as an octal number. binary numbers binary number syntax uses a leading zero followed by a lowercase or uppercase latin letter "b" (0b or 0b). if the digits after the 0b are not 0 or 1, the following syntaxerror is thrown: "missing binary digits after 0b". var flt_signbit = 0b1000000000...
...44; // 420 strict mode in ecmascript 5 forbids octal syntax. octal syntax isn't part of ecmascript 5, but it's supported in all browsers by prefixing the octal number with a zero: 0644 === 420 and "\045" === "%". in ecmascript 2015, octal numbers are supported if they are prefixed with 0o, e.g.: var a = 0o10; // es2015: 8 hexadecimal numbers hexadecimal number syntax uses a leading zero followed by a lowercase or uppercase latin letter "x" (0x or 0x). if the digits after 0x are outside the range (0123456789abcdef), the following syntaxerror is thrown: "identifier starts immediately after numeric literal". 0xfffffffffffffffff // 295147905179352830000 0x123456789abcdef // 81985529216486900 0xa // 10 exponentiation 1e3 // 1000 2e6 // 2000000 0.1e2 // 10 number ...
...r numeric literal". 0xfffffffffffffffff // 295147905179352830000 0x123456789abcdef // 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. ...
...And 8 more matches
Regular expression syntax cheatsheet - JavaScript
this page provides an overall cheat sheet of all the capabilities of regexp syntax by aggregating the content of the articles in the regexp guide. if you need 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 d...
...tches "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 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 matche...
...ample, /\s\w*/ matches "foo" in "foo bar". \t matches a horizontal tab. \r matches a carriage return. \n matches a linefeed. \v matches a vertical tab. \f matches a form-feed. [\b] matches a backspace. if you're looking for the word-boundary character (\b), see boundaries. \0 matches a nul character. do not follow this with another digit. \cx matches a control character using caret notation, where "x" is a letter from a–z (corresponding to codepoints u+0001–u+001f). for example, /\cm/ matches "\r" in "\r\n". \xhh matches the character with the code hh (two hexadecimal digits). \uhhhh matches a utf-16 code-unit with the value hhhh (four hexadecimal digits). ...
...And 8 more matches
Function.prototype.bind() - JavaScript
return value a copy of the given function with the specified this value, and initial arguments (if provided). description the bind() function creates a new bound function, which is an exotic function object (a term from ecmascript 2015) that wraps the original function object. calling the bound function generally results in the execution of its wrapped function. a bound function has the following internal properties: [[boundtargetfunction]] the wrapped function object [[boundthis]] the value that is always passed as this value when calling the wrapped function. [[boundarguments]] a list of values whose elements are used as the first arguments to any call to the wrapped function. [[call]] executes code associated with this object. invoked via a function call expression. the ar...
... used as the first arguments to any call to the wrapped function. [[call]] executes code associated with this object. invoked via a function call expression. the arguments to the internal method are a this value and a list containing the arguments passed to the function by a call expression. when a bound function is called, it calls internal method [[call]] on [[boundtargetfunction]], with following arguments call(boundthis, ...args). where boundthis is [[boundthis]], args is [[boundarguments]], followed by the arguments passed by the function call. a bound function may also be constructed using the new operator. doing so acts as though the target function had instead been constructed. the provided this value is ignored, while prepended arguments are provided to the emulated function. p...
...his is [[boundthis]], args is [[boundarguments]], followed by the arguments passed by the function call. a bound function may also be constructed using the new operator. doing so acts as though the target function had instead been constructed. the provided this value is ignored, while prepended arguments are provided to the emulated function. polyfill because older browsers are generally also slower browsers, it is far more critical than most people recognize to create performance polyfills to make the browsing experience in outdated browsers slightly less horrible. thus, presented below are two options for function.prototype.bind() polyfills: the first one is much smaller and more performant, but does not work when using the new operator. the second one is bigger and less performant,...
...And 8 more matches
String.prototype.replace() - JavaScript
tring that is to be replaced by newsubstr. it is treated as a literal string and is not interpreted as a regular expression. only the first occurrence will be replaced. newsubstr (replacement) the string that replaces the substring specified by the specified regexp or substr parameter. a number of special replacement patterns are supported; see the "specifying a string as a parameter" section below. function (replacement) a function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr. the arguments supplied to this function are described in the "specifying a function as a parameter" section below. return value a new string, with some or all matches of a pattern replaced by a replacement. description this method does not change the...
...tion as a parameter" section below. return value a new string, with some or all matches of a pattern replaced by a replacement. description this method does not change the calling string object. it simply returns a new string. to perform a global search and replace, include the g switch in the regular expression. specifying a string as a parameter the replacement string can include the following special replacement patterns: pattern inserts $$ inserts a "$". $& inserts the matched substring. $` inserts the portion of the string that precedes the matched substring. $' inserts the portion of the string that follows the matched substring. $n where n is a positive integer less than 100, inserts the nth parenthesi...
... be invoked after the match has been performed. the function's result (return value) will be used as the replacement string. (note: the above-mentioned special replacement patterns do not apply in this case.) note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. the arguments to the function are as follows: possible name supplied value match the matched substring. (corresponds 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 ...
...And 8 more matches
Web Performance
al rendering path is the sequence of steps the browser goes through to convert the html, css, and javascript into pixels on the screen. optimizing the critical render path improves render performance.the critical rendering path includes the document object model (dom), css object model (cssom), render tree and layout.css and javascript animation performancebrowsers are able to optimize rendering flows. in summary, we should always try to create our animations using css transitions/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 wo...
...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. to understand how to improve performance and perceived performance, it helps to understand how the browser works.recommended web performance timings: how long is too long?there are no clear set rules as to what constitutes a slow pace when loading pages, but there are specific guidelines for indicating content will load (1 second), idling (50ms), animating (16.7s) and responding to user input (50 to 200ms).the business case for web performanceyou know web performance is important, but how do you convince clients and management to invest in performance and make it a priority. in this article, we'll discuss creating a clear...
...e causes of lacency and to test site performance emulating high latency to optimizer for users with lousy connections. this article explains what latency is, how it impacts performance, how to measure latency, and how to reduce it.using dns-prefetchdns-prefetch is an attempt to resolve domain names before resources get requested. this could be a file loaded later or link target a user tries to follow. beginner's tutorials the mdn web performance learning area contains modern, up-to-date tutorials covering performance essentials. start here if you are a newcomer to performance: web performance: brief overview overview of the web performance learning path. start your journey here. what is web performance? this article starts the module off with a good look at what performance a...
...And 8 more matches
/loader - Archive of obsolete content
o indicate where to find modules loaded using require(). this is provided by a mandatory options.paths hash that represents the mapping between module id prefixes and locations. ...
...you may still end up with a relative module id if the...
... of it is then resolved using the paths option. you may still end up with a relative module id if the entry point module id is itself relative. ...
...And 7 more matches
Install Manifests - Archive of obsolete content
<description about="urn:mozilla:install-manifest"> <!-- properties --> </description> </rdf> some properties are required, some are optional. some have simple string values, some are complex resources. required property reference your install manifest must specify these properties correctly otherwise your add-on may not install. id the id of the extension, which must be one of the following: guid (firefox 1.0) a string formatted like so: extensionname@example.org the latter format is significantly easier to generate and manipulate. firefox 1.5 has checking to ensure that your id falls into one format or the other and will refuse to install add-ons that have malformed ids. you should not use a real email address for your id, however, as it might attract spam. note: the id ...
...sion>) 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 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 fire...
...ay specify more if the add-on targets multiple applications that support the add-on manager (e.g. firefox and thunderbird). examples <em:targetapplication> <description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <!--firefox--> <em:minversion>1.5</em:minversion> <em:maxversion>3.0.*</em:maxversion> </description> </em:targetapplication> gecko 1.9 based applications allow you to use the special targetapplication id toolkit@mozilla.org to say that the add-on is compatible with any toolkit app with a toolkit version matching the minversion and maxversion. type an integer value representing the type of add-on. 2 extensions 4 themes 8 locale 32 multiple item package 64 spell check dictionary 128 ...
...And 7 more matches
Appendix D: Loading Scripts - Archive of obsolete content
ir primary functionality by loading and executing javascript code. because there are such a diverse array of add-ons, and because the needs of developers have grown organically over time, the gecko runtime provides a number of means to dynamically load and execute javascript files. each of these means has its own advantages and disadvantages, as well as its own quirks which may trap the unwary. below is an overview of the more common means of loading scripts, along with some of their primary advantages, disadvantages, quirks, and use cases. the examples below which make use of the services global assume that you're previously imported the services.jsm module. as this module only exists on firefox 4 and other gecko 2-based platforms, the services in question will have to be manually loaded on...
...ode and allocate and initialize all of their data structures each time the script is loaded. loading: script loaded via script tags run in partially loaded documents. problems can ensue if the script immediately attempts to access dom nodes. this is easily resolved by deferring the work to a dynamically added onload hander. (a standalone xul window can use an onload attribute.) example the following overlay will load the script “overlay.js” from the same directory as the overlay file into the window which it overlays. the script will be read with the utf-8 encoding, based on the encoding of the overlay, and will execute as javascript version 1.8, based on the version specified in the script tag. <?xml version="1.0" encoding="utf-8"?> <!doctype overlay> <overlay id="script-overlay" ...
...clude: e4x xml objects cannot be wrapped for passage between compartments: bug 613142 there are a number of type detection issues, including: string.replace does not recognize regexp objects from foreign compartments: bug 633830 debugging: support for sandbox evaluation in development tools is uneven. chromebug supports firebug based sandboxes. examples the following code will execute a simple script in a sandbox with the privilege level of the current content page. the globals of the current content window will be available in the scripts global scope. in stack traces, the script will appear to have been loaded from the file "zz-9://plural/zed/alpha", line 42. // use the current content window as the execution context. // to make properties defined by sc...
...And 7 more matches
Venkman Introduction - Archive of obsolete content
atures, procedures, and tips described here will make you a more confident web developer and debugger. venkman is both a graphic and a console debugger. features such as breakpoint management, call stack inspection, and variable/object inspection are available from the user interface and from console commands, letting you work in the way you are most accustomed to. the interactive console also allows for execution of arbitrary javascript code. venkman's keyboard shortcuts are the same as leading visual debugging environments, and gdb users should be familiar with venkman's /break, /step, /next, /finish, /frame, and /where commands. on windows, the javascript debugger compares favorably with visual interdev and other large web development tools. on other platforms, including mac os and unix,...
...tup x, global yyy." this data comes from a counter built in to the application. for more information about this counter and the data, see item 2.2 in the venkman faq.) when you first start venkman, the basic views are arranged as in the screenshot above—though you can customize the layout and presence of the different views however you want, as we describe in the view customization section below. the scripts that have been loaded by the javascript engine appear in the loaded scripts window (for more information about how scripts are loaded and accessed in venkman, see "loading scripts into the debugger"). the menubar, toolbar, and all of the views can be collapsed or hidden, giving you a lot of control over the debugging environment. the source code view is empty until you select a sc...
...n, giving you a lot of control over the debugging environment. the source code view is empty until you select a script, and the interactive session view starts up with basic startup information. each of the views has a label, a float button that lets you display the view in its own window, and a close button that puts the view away until you want to display it again, as seen in figure 2. the following section describes these views and their use within the interface as a whole. getting acquainted with venkman's user interface toolbar the toolbar is located at the top of the debugger. the toolbar contains icons for stop, continue, step over, step into, step out, profile, and pretty print commands. these commands should be self explanatory, with the possible exception of stop, which cause...
...And 7 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
home [ examples | attributes | properties | methods | related ] this element is created by setting the type attribute of the textbox to autocomplete. it is used to create a textbox with a popup containing a list of possible completions for what the user has started to type. toolkit applications (such as firefox) use a different autocomplete mechanism than the mozilla suite. the example below will create an autocomplete textbox that will search the user's history. attributes accesskey, autocompletepopup, autocompletesearch, autocompletesearchparam, completedefaultindex, completeselectedindex,crop, disableautocomplete, disabled, disablekeynavigation, enablehistory, focused, forcecomplete, highlightnonmatches, ignoreblurwhilesearching, inputtooltiptext, label, maxlength, maxrow...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. disable...
...nputtooltiptext type: string the tooltip text for the textbox. 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. 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 th...
...And 7 more matches
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
completed all the steps, you will have a structure like this in the directory where you installed seamonkey: 1. go to the directory where you installed seamonkey, then go to the chrome directory there. note: for information about how to find the directory where you installed seamonkey, see: installation directory if you cannot easily find the directory, you can use the following method to find it. from seamonkey's menu bar, choose tools – web development – javascript console. copy the following code. it is one very long line ending in path—make sure that you get all of it: components.classes["@mozilla.org/file/directory_service;1"].getservice( components.interfaces.nsiproperties).get("achrom", components.interfaces.nsifile).path in the javascript console win...
...other files that are provided by extensions. your toolbar button will be an extension. 2. delete these two files: chrome.rdf overlays.rdf explanation: seamonkey automatically rebuilds these files the next time it starts. when it rebuilds them, it will include your new extension. 3. edit the file: installed-chrome.txt at the end of the file, add the following line. copy and paste the line from here, to avoid typing errors: content,install,url,resource:/chrome/custombutton/ explanation: this line registers your custom toolbar button extension, linking it into seamonkey. 4. create a new directory named: custombutton perform the following steps in this new directory, creating five files there. explanat...
...lbar button extension, linking it into seamonkey. 4. create a new directory named: custombutton perform the following steps in this new directory, creating five files there. explanation: the name is a unique identifier for your extension, and the directory will contain all your extension's files. 5. create a plain text file named contents.rdf. copy the following content, making sure that you scroll to get all of it. paste it into the new file: <?xml version="1.0" encoding="utf-8"?> <!doctype rdf:rdf> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:chrome="http://www.mozilla.org/rdf/chrome#"> <rdf:seq rdf:about="urn:mozilla:package:root"> <rdf:li rdf:resource="urn:mozilla:package:custombutton"/> </rdf...
...And 7 more matches
Advanced Rules - Archive of obsolete content
like the simple rules, full rules are placed within the rule tag. ...
...hould always exist once and only once. it serves as a placeholder as the template builder iterates through the resources. it specifies the name of a variable in which is placed a reference to the root resource while the conditions are analyzed for a match. the root resource is the one specified by the ref attribute on the element containing the template. the syntax of the content element is as follows: <content uri="?var"/> the question mark indicates that the text following it is a variable. you can then use the variable 'var' within the remainder of the conditions. of course, you can name the variable whatever you want. member element the next element is the member element, which is used to iterate through a set of child resources. in rdf terms, that means a container such a seq, bag or al...
...the text following it is a variable. you can then use the variable 'var' within the remainder of the conditions. of course, you can name the variable whatever you want. member element the next element is the member element, which is used to iterate through a set of child resources. in rdf terms, that means a container such a seq, bag or alt. ...
...And 7 more matches
Element Positioning - Archive of obsolete content
ize to hold their text. the third button is larger because it contains more content. the width of the box containing the buttons is the total width of the buttons plus the padding between them. the height of the buttons is a suitable size to hold the text. width and height attributes you may need to have more control over the size of an element in a window. there are a number of features that allow you to control the size of an element. the quick way is to simply add the width and height attributes on an element, much like you might do on an html img tag. an example is shown below: example 1: source view <button label="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 p...
... width this specifies the width of the element. ...
...h 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 needed. the size of these style properties should be specified as a number followed by a unit. flexible elements the sizes are fairly easy to calculate for non-flexible elements. they simply obey their specified widths and heights, and if the size wasn't specified, the element's default size is just large enough to fit the contents. for flexible elements, the calculation is slightly trickier. flexible elements are those that have a flex attribute set to a value greater than...
...And 7 more matches
XUL Questions and Answers - Archive of obsolete content
y have a clear answer.) where can i get more information about creating mozsearch plugins? creating mozsearch plugins contains more help information about creating mozsearch plugin on firefox 2. more documentation on search plugins is available in the search plugins category. is localizing remote xul possible? loading remote dtds for xml documents is currenty not supported in xul. the following bugs were reported on this issue: bug 22942, bug 133698. is there an editor widget in xul that supports syntax highlighting? daniel glazman has been working on this for his projects. he said the code will be open-source, but it is not released yet (as of oct 2006). some teasers are on his blog. overlaying elements without ids the original developers only tend to put ids where they need...
...mplate is planned (bug 321170): xml datasources (bug 321171) storage (sqlite) datasources (bug 321172) when loading an xslt stylesheet into an xml i get the error: "error loading stylesheet: an xslt stylesheet load was blocked for security reasons." that error is from a security check that has been put up to safeguard against cross-site-scripting attacks. a scheme is in development to allow servers to open up their site for cross-site access, but that's not yet done. hidechrome="true" doesn’t work on a mac? unfortunately, no simple solution to this was posted. a workaround is to open the content in a new window using "window.open" and send titlebar=”no” as one of the flags in the 3rd argument. is it possible to have checkbox support for multi column lists? the current ...
...esn’t work on a mac? unfortunately, no simple solution to this was posted. a workaround is to open the content in a new window using "window.open" and send titlebar=”no” as one of the flags in the 3rd argument. is it possible to have checkbox support for multi column lists? the current issue is a person exploring if it is possible to have checkbox support for multi column lists. ...
...And 7 more matches
menuitem - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a single choice in a menupopup element. it acts much like a button but it is rendered on a menu. more information is available in the xul tutorial. ...
...key (accelerator key) to use to invoke the command. if this value is set, it overrides an assigned key set in the key attribute. this attribute does not apply to menus directly on the menubar. 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. allowevents type: boolean if true, events are passed to children of the element. otherwise, events are passed to the element only. 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 ...
...tead of removing the attribute (i.e. do menuitem.setattribute("checked", "false") instead of menuitem.removeattribute("checked")) when the user unchecks the menuitem, as a value of false will both correctly hide the checkmark and persist its hidden state. command type: id set to the id of a command element that is being observed by the element. ...
...And 7 more matches
XForms Custom Controls - Archive of obsolete content
since firefox 4, xbl and xul are disabled by default for all pages not loaded from a chrome:// url. this also includes content loaded from file:// urls. it is possible to re-enable this by following the steps on using remote xul. this is required for all examples here to run! purpose you are in the right place if you would like to create your own custom renderings of the xforms controls like input, output, trigger, etc. we will also show you how to create custom controls that work with the xforms model and are automatically updated just like xforms controls. the purpose of this article is to give you enough background information so that you'll be able to get a good start. to really grasp the following information, a good understanding of xforms, xbl, javascript and css is needed. xpc...
...implementation status the framework we use in the mozilla xforms processor is very much a "work in progress". ...
...re 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 customization will fall into one of the following categories: custom presentation - xforms controls as rendered by the mozilla xforms processor do not provide the right look and feel for you. custom data types - existing xforms controls are not able to work properly with your data type advanced xforms controls - you need your controls to be able to do more things than traditional xforms controls can do new host language - you'd like to suppo...
...And 7 more matches
Building up a basic demo with A-Frame - Game development
the webxr and webgl apis already enable us to start creating virtual reality (vr) experiences inside web browsers, but the community is still waiting for tools and libraries to appear, to make this easier. mozilla's a-frame framework provides a markup language allowing us to build 3d vr landscapes using a system familiar to web developers, which follows game development coding principles; this is useful for quickly and successfully building prototypes and demos, without having to write a lot of javascript or glsl. this article explains how to get up and running with a-frame, and how to use it to build up a simple demo. high level overview the current version of a-frame is 0.3.2, which means it's highly experimental, but it already works and you can test it right away in the browser. it run...
...ectory to store your project in. save a copy of the latest a-frame javascript library file inside your directory (check the github repository 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...
...ing you deem suitable for your scene — milimeters, meters, feet, or miles — it's up to you. adding a background: sky box a sky box is a background for the 3d world, represented by an <a-sky> element. in our case we will use a simple color, but it could also be an image, etc. looking around would give an impression of being inside an open sky, a wooden barn — wherever you like! add the following html before the <a-cube> element: <a-sky color="#dddddd"></a-sky> at this point, if you save the code and refresh your browser you can already see the cube on the screen with our custom background: here's the code we have created so far: you can also check it out on github. a-frame takes care of setting up everything you need: a default light source and camera are included, so the...
...And 7 more matches
Build the brick field - Game development
ing this lesson at gamedev-phaser-content-kit/demos/lesson09.html. building the brick field is a little bit more complicated than adding a single object to the screen, although it's still easier with phaser than in pure javascript. let's explore how to create a group of bricks and print them on screen using a loop. ...
...lesson at gamedev-phaser-content-kit/demos/lesson09.html. building the brick field is a little bit more complicated than adding a single object to the screen, although it's still easier with phaser than in pure javascript. let's explore how to create a group of bricks and print them on screen using a loop. ...
... game.load.image('brick', 'img/brick.png'); } you also need to grab the brick image from github and save it in your /img directory. ...
...And 7 more matches
Plug-in Development Overview - Gecko Plugin API Reference
plan your plug-in: decide on the services you want the plug-in software to provide and how it will interact with the browser and the special media for which the plug-in is created. decide the mime type for the plug-in (see registering plug-ins). set up your development environment properly. ...
.... for more information about mime types, see these mime rfcs: rfc-2045: "multipurpose internet mail extensions (mime) part one: format of internet message bodies" rfc-2046: "multipurpose internet mail extensions (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. ...
...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. ...
...And 7 more matches
What is accessibility? - Learn web development
prerequisites: basic computer literacy, a basic understanding of html and css. ...
...accessibility, including what it is, and how it affects you as a web developer. so what is accessibility? accessibility is the practice of making your websites usable by as many people as possible. we traditionally think of this as being about people with disabilities, but the practice of making sites accessible also benefits other groups such as those using mobile devices, or those with slow network connections. you might also think of accessibility as treating everyone the same, and giving them equal opportunities, no matter what their ability or circumstances. just as it is wrong to exclude someone from a physical building because they are in a wheelchair (modern public buildings generally have wheelchair ramps or elevators), it is also not right to exclude someone from a website ...
... buy your products. building accessible sites benefit everyone: semantic html, which improves accessibility, also improves seo, making your site more findable. caring about accessibility demonstrates good ethics and morals, which improves your public image. other good practices that improve accessibility also make your site more usable by other groups, such as mobile phone users or those on low network speed. in fact, everyone can benefit from many such improvements. did we mention it is also the law in some places? what kinds of disability are we looking at? people with disabilities are just as diverse as people without disabilities, and so are their disabilities. the key lesson here is to think beyond your own computer and how you use the web, and start learning about how others u...
...And 7 more matches
Sizing items in CSS - Learn web development
is an image. an image has a width and a height defined in the image file it is embedding into the page. this size is described as the intrinsic size — which comes from the image itself. if you place an image on a page and do not change its height and width, either using attributes on the <img> tag or css, it will be displayed using that intrinsic size. ...
...it has no height (or size in the block dimension) because there is no content. in the example above, try adding some text inside the empty element. ...
... of course give elements in our design a specific size. when a size is given to an element (and the content of which then needs to fit into that size) we refer to it as an extrinsic size. take our <div> from the example above — we can give it specific width and height values, and it will now have that size no matter what content is placed into it. as we discovered in our previous lesson on overflow, a set height can cause content to overflow if there is more content than the element has space to fit inside it. due to this problem of overflow, fixing the height of elements with lengths or percentages is something we need to do very carefully on the web. using percentages in many ways, percentages act like length units, and as we discussed in the lesson on values and units, they can ofte...
...And 7 more matches
Sending form data - Learn web development
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 request to a server (most of the time a web server like apache, nginx, iis, tomcat, etc.), using the http protocol. the server answers the request using the same protocol. 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...
...if this attribute isn't provided, the data will be sent to the url of the page containing the form — the current page. in this example, the data is sent to an absolute url — https://example.com: <form action="https://example.com"> here, we use a relative url — the data is sent to a different url on the same origin: <form action="/somewhere_else"> when specified with no attributes, as below, the <form> data is sent to the same page that the form is present on: <form> note: it's possible to specify a url that uses the https (secure http) protocol. when you do this, the data is encrypted along with the rest of the request, even if the form itself is hosted on an insecure page accessed using http. on the other hand, if the form is hosted on a secure page but you specify an insecure ...
...tion necessary for the server to process the specific request. the get method the get method is the method used by the browser to ask the server to send back a given resource: "hey server, i want to get this resource." in this case, the browser sends an empty body. because the body is empty, if a form is sent using this method the data sent to the server is appended to the url. ...
...And 7 more matches
HTML table advanced features and accessibility - Learn web development
lly impaired users. prerequisites: the basics of html (see introduction to html). objective: to learn about more advanced html table features, and the accessibility of tables. adding a caption to your table with <caption> you can give your table a caption by putting it inside a <caption> element and nesting that inside the <table> element. you should put it just below the opening <table> tag. <table> <caption>dinosaurs in the jurassic period</caption> ... </table> as you can infer from the brief example above, the caption is meant to contain a description of the table contents. this is useful for all readers wishing to get a quick idea of whether the table is useful to them as they scan the page, but particularly for blind users. rather than have a scre...
... save your code and open it in a browser to see what it looks like. note: you can find our version on github — see timetable-caption.html (see it live also). adding structure with <thead>, <tfoot>, and <tbody> as your tables get a bit more complex in structure, it is useful to give them more structural definition. one clear way to do this is by using <thead>, <tfoot>, and <tbody>, which allow you to mark up a header, footer, and body section for the table. these elements don't make the table any more accessible to screenreader users, and don't result in any visual enhancement on their own. they are however very useful for styling and layout — acting as useful hooks for adding css to your table. to give you some interesting examples, in the case of a long table you could make the ta...
...age, and you could make the table body display on a single page and have the contents available by scrolling up and down. to use them: the <thead> element must wrap the part of the table that is the header — this is usually the first row containing the column headings, but this is not necessarily always the case. if you are using <col>/<colgroup> element, the table header should come just below those. the <tfoot> element needs to wrap the part of the table that is the footer — this might be a final row with items in the previous rows summed, for example. you can include the table footer right at the bottom of the table as you'd expect, or just below the table header (the browser will still render it at the bottom of the table). the <tbody> element needs to wrap the other parts of th...
...And 7 more matches
Accessibility in React - Learn web development
e current situation because we cannot focus on an element until after the <todo /> component renders and react knows where our refs are. change the import statement of todo.js again to add useeffect: import react, { useeffect, useref, usestate } from "react"; useeffect() takes a function as an argument; this function is executed after the component renders. ...
...you should see both messages in your console, with each one repeating three times. note how "main render" logged first, and "side effect" logged second, even though the "side effect" log appears first in the code. ...
... to read the previous value of the isediting constant. using pseudocode, our logic should be something like this: if (wasnoteditingbefore && iseditingnow) { focusoneditfield() } if (waseditingbefore && isnoteditingnow) { focusoneditbutton() } the react team had discussed ways to get a component’s previous state, and has provided an example custom hook we can use for the job. paste the following code near the top of todo.js, above your todo() function. function useprevious(value) { const ref = useref(); useeffect(() => { ref.current = value; }); return ref.current; } now we'll define a wasediting constant beneath the hooks at the top of todo(). we want this constant to track the previous value of isediting, so we call useprevious with isediting as an argument: const was...
...And 7 more matches
Deployment and next steps - Learn web development
to prepare our svelte app for production, and what learning resources you should visit next. note that our application is fully functional and porting it to typescript is completely optional. there are different opinions about it, and in this chapter we will talk briefly about the pros and cons of using typescript. even if you are not planning to adopt it, this article will be useful for allowing you to learn what it has to offer and help you make your own decision. if you are not interested at all in typescript, you can skip to the next chapter, where we will look at different options for deploying our svelte applications, further resources, and more. code along with us git clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte...
...a particularly useful plugin which is also maintained by the svelte team is svelte-preprocess, which pre-processes many different languages in svelte files such as postcss, scss, less, coffeescript, sass, and typescript. deploying your svelte application from the point of view of a web server, a svelte application is nothing more than a bunch of html, css, and jav...
...iles such as postcss, scss, less, coffeescript, sass, and typescript. deploying your svelte application from the point of view of a web server, a svelte application is nothing more than a bunch of html, css, and javascript files. all you need is a web server capable of serving static files, which means you have plenty of options to choose from. let's look at a couple of examples. ...
...And 7 more matches
Introduction to cross browser testing - Learn web development
ur 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 when you are dealing with bleeding edge features that browsers are just getting round to implementing, or if you have to support really old browsers that are no longer being developed, which may have been froze...
...long time before a new feature was even invented. as an example, if you want to use cutting edge javascript features in your site, they might not work in older browsers. if you need to support older browsers, you might have to not use those, or convert your code to old fashioned syntax using some kind of cross-compiler where needed. some devices may have constraints that cause a web site to run slowly, or display badly. for example, if a site has been designed to look nice on a desktop pc, it will probably look tiny and 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 ...
...mple, if a site has been designed to look nice on a desktop pc, it will probably look tiny and 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 t...
...And 7 more matches
Client-side tooling overview - Learn web development
ls" you're going to hit a huge spectrum of results ranging from text editors, to browsers, to the type of pens you can use to take notes. though your choice of code editor is certainly a tooling choice, this series of articles will go beyond that, focusing on developer tools that help you produce web code more efficiently. from a high-level perspective, you can put client-side tools into the following three broad categories of problems to solve: safety net — tools that are useful during your code development. transformation — tools that transform code in some way, e.g. turning an intermediate language into javascript that a browser can understand. post-development — tools that are useful after you have written your code, such as testing and deployment tools. let's look at each ...
...are all using the same processes. this includes anything that makes your development process easier with respect to generating stable and reliable code. safety net tooling should also help you either prevent mistakes or correct mistakes automatically without having to build your code from scratch each time. a few very common safety net tool types you will find being used by developers are as follows. linters linters are tools that check through your code and tell you about any errors that are present, what error types they are, and what code lines they are present on. often linters can be configured to not only report errors, but also report any violations of a specified style guide that you team might be using (for example code that is using the wrong number of spaces for indentation, or...
... 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 whenever you try to use them. it can even handle some code transformation duties for you. webpack is another very popular packaging tool that does similar things. transformation this stage of your web app lifecycle typically allows you to code in either "future code" (such as the latest css or javascript features that might not have native support in browsers yet) or code using another language entirely, such as typescript. transformation tools will then generate browser-compatible code for you, to be used in production. generally web development is thought of as three languages: html, css, and javascript, and there are t...
...And 7 more matches
Debugging on Mac OS X
this time, official builds of firefox 69 and later are notarized. uplifts to firefox 68 and esr 68 to enable notarization are planned. as a result, it is not possible to attach a debugger to these official firefox releases on macos 10.14+ without disabling system integrity protection (sip). this is due to notarization requiring hardened runtime to be enabled with the com.apple.security.get-task-allow entitlement disallowed. rather than disabling sip (which has security implications), it is recommended to debug with try builds or local builds. the differences are explained below. try server builds in most cases, developers needing to debug a build as close as possible to the production environment should use a try build. these builds enable hardened runtime and only differ from production bu...
...ow. try server builds in most cases, developers needing to debug a build as close as possible to the production environment should use a try build. these builds enable hardened runtime and only differ from production builds in that they are not notarized which should not otherwise affect functionality, (other than the ability to easily launch the browser on macos 10.15+ -- see quarantine note below). at this time, developers can obtain a hardened runtime build with the com.apple.security.get-task-allow entitlement allowed by submitting a try build and downloading the dmg generated by the "rpk" shippable build job. a debugger can be attached to firefox processes of these builds. try builds use the developer.entitlements.xml file from the source tree while production builds use production.ent...
...ened 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 disabling system integrity protection (sip). note that disabling sip bypasses hardened runtime restrictions which can mask some bugs that only occur with hardened runtime so it is recommended to test fixes with sip enabled. disabling sip has system security implications that should be understood before taking this step. creating an xcode project if you try to creat...
...And 7 more matches
Displaying Places information using views
nce and displaying the nsinavhistoryresultnode objects contained therein. the built-in views if you need to show the contents of bookmarks or history in your extension or application, you may want to use the built-in places views, which are generic and will save you a lot of time writing basic functionality so that you can focus on building your extension or application. places provides the following built-in views: tree menu toolbar instantiating the three built-in views are simply standard xul elements with a special type attribute whose value is "places". every xul document containing a built-in view must import the stylesheet browser/components/places/content/places.css and overlay the file browser/components/places/content/placesoverlay.xul: <?xml-stylesheet href="chrome://b...
...he place attribute directly in the xul. for more complicated queries or queries whose uris you plan on changing, you will want to set the view's place property dynamically using javascript. note that in the latter case it is not sufficient to call setattribute on the element; use the element's place property instead. see querying places and places query uris for information on query uris. the following example uses the built-in tree view to display bookmarks whose titles or urls contain "mozilla". remember that, because xul is xml, any ampersands in query uris must be written as entity reference &amp; and not simply &. <tree type="places" place="place:terms=mozilla&amp;onlybookmarked=1&amp;querytype=1"> <treecols> <treecol id="title" label="my bookmarks" flex="1" primary="true" /> <...
...title" flex="1" primary="true" /> <treecol id="url" flex="1" /> </treecols> <treechildren /> </tree> the tree view is implemented in browser/components/places/content/tree.xml. see the tree reference and trees tutorial for general information about trees. ...
...And 7 more matches
Overview of Mozilla embedding APIs
f xpcom components. at the heart of xpcom's implementation is the service manager and the component manager. together, these two services provide a centralized point for gaining access to all of the public mozilla interfaces. the service manager exposes all of the available xpcom services - each service represents a global object which provides some piece of functionality. the component manager allows new instances of registered xpcom components to be instantiated. the embedding layer consists of several components built on top of xpcom and its services. much of the gecko functionality is exposed through a component called the nswebbrowser. embedding applications can leverage this component to easily access many of gecko's features. each webbrowser instance represents the "client-area" of a ...
...edding layer consists of several components built on top of xpcom and its services. much of the gecko functionality is exposed through a component called the nswebbrowser. embedding applications can leverage this component to easily access many of gecko's features. each webbrowser instance represents the "client-area" of a typical browser window. the webbrowser exposes a set of interfaces which allow the embedding application to control activity and respond to changes within this client area. using these interfaces an embedding application can build up its own user interface around a webbrowser instance. public classes the following utility classes are available from the xpcom dll. they provide some basic functionality which should be leveraged when building new xpcom components. nscomptr...
... variety of string operations as well as dealing with the memory management issues of storing the underlying data. see the string guide for more details. nsweakptr this is an nscomptr which encapsulates xpcom weak reference support. see the nsiweakreference document for more information. public return codes ns_succeeded ns_error_failure ns_error_not_implemented public functions the following functions are available from the xpcom dll. ns_initembedding this function initializes the gecko embedding support. this must be the first function call made into gecko. ns_termembedding this function shuts down gecko and cleans up any remaining resources... currently, once gecko has been shutdown, it cannot be restarted in the same process space... this should change in the future. ...
...And 7 more matches
Getting Started with Chat
2nd march 2020, mozilla moved away from irc to matrix for its public channels, the irc server was shut down. this page is being retained for historical and reference purposes. the general rules and etiquette are still useful for our new home. please see https://wiki.mozilla.org/matrix for up-to-date information. general rules and etiquette once you have your client set up (see software below) and are connected, there are some basic rules you should follow to ensure the most enjoyable and productive experience: as with all mozilla forums and events, agreeing to our community participation guidelines is a requirement for participation. try to keep messages as concise as possible. if you have something long to post, a code snippet for example, use paste.mozilla.org and paste the gen...
... 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: server: irc.mozilla.org port: 6667 (default) or 6697 (ssl) desktop clients desktop clients tens to allow the most detailed configuration. for example, you can connect using ssl or a non-secure connection, and you can configure the client to automatically connect to a server an...
...formation to configure the server connection: server: irc.mozilla.org port: 6667 (default) or 6697 (ssl) desktop clients desktop clients tens to allow the most detailed configuration. for example, you can connect using ssl or a non-secure connection, and you can configure the client to automatically connect to a server and join a particular set of channels when you start the client. the following are some other options available to you: windows mac linux colloquy ● irssi ● ● ●* xchat ● ○ ● key: ● — binary or executable program available ○ — only available by downloading and compiling source code ●* — binary or executable may be available. if not, you'll have to download sourc...
...And 7 more matches
Power profiling overview
epleted depends on the power consumption of the mobile device. that in turn depends on the software running on the device. web browsers are popular applications and can be power-intensive, and therefore can significantly affect battery life. as a result, it is worth optimizing (i.e. reducing) the power consumption caused by firefox and firefox os. intel processor basics processor layout the following diagram (from the intel power governor documentation) shows how machines using recent intel processors are constructed. the important points are as follows. the processor has one or more packages. these are part of the actual processor that you buy from intel. client processors (e.g. core i3/i5/i7) have one package. server processors (e.g. xeon) typically have two or more packages. each...
...ertop and turbostat (linux) can expose this information. a wakeup occurs when a core or package transitions from an idle state to the active state. this happens when the os schedules a process to run due to some kind of event. common causes of wakeups include scheduled timers going off and blocked i/o system calls receiving data. maintaining c-state residency is crucial to keep power consumption low, and so reducing wakeup frequency is one of the best ways to reduce power consumption. one consequence of the existence of c-states is that observations made during power profiling — even more than with other kinds of profiling — can disturb what is being observed. for example, the gecko profiler takes samples at 1000hz using a timer. each of these samples can trigger a wakeup, which consume...
...h other kinds of profiling — can disturb what is being observed. for example, the gecko profiler takes samples at 1000hz using a timer. each of these samples can trigger a wakeup, which consumes power and obscures firefox's natural wakeup patterns. for this reason, integrating power measurements into the gecko profiler is unlikely to be useful, and other power profiling tools typically use much lower sampling rates (e.g. 1hz.) p-states intel processors also support multiple p-states. p0 is the state where the processor is operating at maximum frequency and voltage, and higher-numbered p-states operate at a lower frequency and voltage to reduce power consumption. processors can have dozens of p-states, but the transitions are controlled by the hardware and os and so p-states are of less in...
...And 7 more matches
about:memory
nd cc, dump gc & cc logs, and dump dmd reports. it is present in all builds and does not require any preparation to be used. how to generate memory reports let's assume that you want to measure firefox's memory usage. perhaps you want to investigate it yourself, or perhaps someone has asked you to use about:memory to generate "memory reports" so they can investigate a problem you are having. follow these steps. at the moment of interest (e.g. once firefox's memory usage has gotten high) open a new tab and type "about:memory" into the address bar and hit "enter". if you are using a communication channel where files can be sent, such as bugzilla or email, click on the "measure and save..." button. this will open a file dialog that lets you save the memory reports to a file of your choosin...
...e presented within trees. for example: 585 (100.0%) -- preference-service └──585 (100.0%) -- referent ├──493 (84.27%) ── strong └───92 (15.73%) -- weak ├──92 (15.73%) ── alive └───0 (00.00%) ── dead leaf nodes represent actual measurements; the value of each internal node is the sum of all its children. the use of trees allows measurements to be broken down into further categories, sub-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 ...
.... 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 memory allocated via explicit calls to heap allocation functions (su...
...And 7 more matches
NSS environment variables
note: nss environment variables are subject to be changed and/or removed from nss. run-time environment variables these environment variables affect the run time behavior of nss shared libraries. there is a separate set of environment variables that affect how nss is built, documented below. ...
... environment variables affect the run time behavior of nss shared libraries. there is a separate set of environment variables that affect how nss is built, documented below. variable type description introduced in version nsrandcount integer (byte count) sets the maximum number of bytes to read from the file named in the environment variable nsrandfile (see below). makes nsrandfile usable with /dev/urandom. 3.12.3 nsrandfile string (file name) uses this file to seed the pseudo random number generator. before 3.0 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_...
...ivities of the nss cryptographic module in fips mode. audit data 3.11.2 nss_enable_pkix_verify boolean (any non-empty value to enable) use libpkix, rather than the old cert library, to verify certificates. 3.12 nss_fips string ("fips","true","on","1") will start nss in fips mode. 3.12.5 nss_hash_alg_support string specifies agorithms allowed to be used in certain applications, such as in signatures on certificates and crls. see documentation at this link. 3.12.3 nss_output_file string (filename) output file path name for the pkcs #11 module logger. default is stdout. 3.7 nss_sdb_use_cache string ("no","yes","auto") controls whether nss uses a local cache of sql database contents. default ...
...And 7 more matches
pkfnc.html
pk11_findcertfromnickname pk11_findkeybyanycert pk11_getslotname pk11_gettokenname pk11_ishw pk11_ispresent pk11_isreadonly pk11_setpasswordfunc pk11_findcertfromnickname finds a certificate from its nickname. syntax #include <pk11func.h> #include <certt.h> certcertificate *pk11_findcertfromnickname( char *nickname, void *wincx); parameters this function has the following parameters: nickname a pointer to the nickname in the certificate database or to the nickname in the token. wincx a pointer to application data for the password callback function. this pointer is set with ssl_setpkcs11pinarg during ssl configuration. to retrieve its current value, use ssl_r...
...tion set with pk11_setpasswordfunc and passes it the pointer specified by the wincx parameter. pk11_findkeybyanycert finds the private key associated with a specified certificate in any available slot. syntax #include <pk11func.h> #include <certt.h> #include <keyt.h> seckeyprivatekey *pk11_findkeybyanycert( certcertificate *cert, void *wincx); parameters this function has the following parameters: cert a pointer to a certificate structure in the certificate database. wincx a pointer to application data for the password callback function. this pointer is set with ssl_setpkcs11pinarg during ssl configuration. to retrieve its current value, use ssl_revealpinarg. ...
...1_findkeybyanycert, you must free it by calling seckey_destroyprivatekey. the pk11_findkeybyanycert function calls the password callback function set with pk11_setpasswordfunc and passes it the pointer specified by the wincx parameter. pk11_getslotname gets the name of a slot. syntax #include <pk11func.h> char *pk11_getslotname(pk11slotinfo *slot); parameters this function has the following parameter: slot a pointer to a slot info structure. returns the function returns one of these values: if successful, a pointer to the name of the slot (a string). if unsuccessful, null. description if the slot is freed, the string with the slot name may also be freed. if you want to preserve it, copy the string be...
...And 7 more matches
A Web PKI x509 certificate primer
public key, a subject, an issuer, and a set of extensions. the extensions define extra properties of the certificate such as extra attributes of the certificate or constraints on the use of the certificate. in order for a certificate to be valid these three requirements must be met: there is a verification path from the site certificate to a trusted certificate of the user agent (ie if you follow the issuer path you will end on a self-signed certificate that is considered trusted by the browser). the attributes of the certificates in the verification path have valid parameters for that verification (for example the validity period of all the certificates are valid for the time the verification is being done) revocation checks are considered ok for that particular validation. one issue...
... 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 be used for more than one fqdn, for example you can have a certificate that is valid for both a.example.com and b.example.com basic constraints this allows certificates to be asserted as issuing certificates (it is mandatory for ca certificates). it can also be used to express the maximum depth of the trust path from the ca. key usage this extension is used to constrain ...
... by losing the private key of the ca. authority information access this extension is primarily used to to describe the ocsp location for revocation checking. it is mandatory for certificates that chain up to a root in the mozilla ca program. self-signed certificates these are the steps to generate a certificate for www.example.com. replace this value with the actual server name in the steps below. 1. generate the key using the following command: openssl genpkey -algorithm rsa -out key.pem -pkeyopt rsa_keygen_bits:2048 2048 is considered secure for the next 4 years. 2. generate csr using this command: openssl req -new -key key.pem -days 1096 -extensions v3_ca -batch -out example.csr -utf8 -subj '/cn=www.example.com' this creates a new certificate signing request (csr) that wi...
...And 7 more matches
Gecko Roles
microsoft windows. role_menubar represents the menu bar (positioned beneath the title bar of a window on most platforms or at the top of the screen on mac os x) from which menus are selected by the user. role_scrollbar represents a vertical or horizontal scroll bar, which is part of the client area or used in a control. role_grip represents a special mouse pointer, which allows a user to manipulate user interface elements such as windows. for example, a user clicks and drags a sizing grip in the lower-right corner of a window to resize it role_sound represents a system sound, which is associated with various system events. role_cursor represents the system mouse pointer. role_caret represents the system caret. role_alert represents an al...
... a main window for an application. role_document represents a document window. a document window is always contained within an application window. role_pane represents a pane within a frame or document window. users can navigate between panes and within the contents of the current pane, but cannot navigate between items in different panes. thus, panes represent a level of grouping lower than frame windows or documents, but above individual controls. role_chart represents a graphical image used to represent data. role_dialog represents a dialog box or message box. role_border represents a window border. role_grouping logically groups other objects. role_separator used to visually divide a space into two regions, such as a separator menu i...
...nts a link to something else. this object might look like text or a graphic, but it acts like a button. role_helpballoon displays a help topic in the form of a tooltip or help balloon. role_character represents a cartoon-like graphic object, such as microsoft office assistant, which is displayed to provide help to users of an application. role_list represents a list box, allowing the user to select one or more items. role_listitem represents an item in a list. role_outline represents an outline or tree structure, such as a tree view control, that displays a hierarchical list and allows the user to expand and collapse branches. role_outlineitem represents an item in an outline or tree structure. role_pagetab represents a page tab, it is a...
...And 7 more matches
Places utilities for JavaScript
by default its only included in browser.xul. its not an interface, and as such it will never be frozen, but it provides some easy to use functions that can save you from reinventing the wheel and cluttering up your own classes/functions when you need it. global objects there are a few global objects and constants defined in utils.js. ...
...faultinsertionpoint, boolean ashowpicker); array object getannotationsforuri(nsiuri auri); array object getannotationsforitem(int aitemid); void setannotationsforuri(nsiuri auri, object aannos); void setannotationsforuri(int aitemid, object aannos); getviewfornode(nsidomnode anode); void markpageastyped(string aurl); void markpageasfollowedbookmark(string aurl); boolean checkurlsecurity(nsinavhistoryresultnode aurinode); string getquerystringforfolder(int afolderid); string getdescriptionfromdocument(nsidomdocument doc); string setpostdataforbookmark(int aboomarkid, string apostdata); string getpostdataforbookmark(int aboomarkid); array string geturlandpostdataforkeyword(string...
...howminimaladdlivemarkui(afeeduri, asiteuri, atitle, adescription, adefaultinsertionpoint, ashowpicker) see showaddlivemarkui for a description of the params. showminimaladdmultibookmarkui() show an "add bookmarks" dialog to allow the adding of a folder full of bookmarks corresponding to the objects in the urilist. this will be called most often as the result of a "bookmark all tabs..." command. showaddmultibookmarkui(aurilist) parameters aurilist list of nsiuri objects representing the locations to be bookmarked. return type return true if any transaction has been performed. showbookmarkproperties() opens the...
...And 7 more matches
Reference Manual
r is stored as an nsisupports* (except in debug builds where nscap_feature_debug_ptr_types is turned on). it is because of these factored routines that nscomptr users must link with the xpcom library. when nscap_feature_debug_ptr_types is turned on, instead of holding its underlying pointer in a variable of type nsisupports*, the nscomptr holds it in a pointer matching the underlying type. this allows source level debuggers to more easily "follow" the pointer. however, the routines that would normally be factored into a base class now must become template-specific inlines. there is no factored base class. this implies that the entire application must be compiled with the same setting of nscap_feature_debug_ptr_types, else some parts will be expecting a base class and others will not. the app ...
...orms assignment into, or initialization of an nscomptr is easy to understand. the nscomptr releases its old value, if any, and then assigns in the new value, addrefing it and/or calling queryinterface as you direct by "annotating" the assignment with directives like dont_addref. this section describes each of the possibilities, though the directives can be more succinctly described in the table below. ...
...and. the nscomptr releases its old value, if any, and then assigns in the new value, addrefing it and/or calling queryinterface as you direct by "annotating" the assignment with directives like dont_addref. this section describes each of the possibilities, though the directives can be more succinctly described in the table below. ...
...And 7 more matches
Index
da thunderbird 3, thunderbird thunderbird includes a new message indexing and search system (gloda) that improves search performance, provides sophisticated full-text search capabilities and categorized search results. "gloda" is short for the thunderbird "global database". 29 gloda debugging the gloda code has log4moz logging statements spread throughout. the following preferences are supported to control how this gets logged: 30 gloda examples thunderbird 3, thunderbird this page provides some examples for using gloda. see creating a gloda message query for more examples. 31 gloda indexing this page provides a big-picture summary of what the indexer does; please see the source for nitty-gritty details or if this pa...
...roducts. it assumes you are already familiar with configuring preferences for deployed builds in addition to setting up thunderbird to use an ldap directory. it should be noted that all of this information applies to both thunderbird and the seamonkey application suite. 34 mail and rdf mozilla mail exposes many of it's data structures to rdf through a few datasources. this allows exposure of mailnews-specific data to user interface using rdf templates. 35 mail client architecture overview sections in grey refer to modules outside of mail/news 36 mail composition back end by richard h. pizzarro <rhp@netscape.com> contents 37 mail event system mozilla mail requires an event system to notify different subsyst...
...the search terms match. for new incoming messages, the protocol specific object that handles new messages calls nsimsgfilterlist::applyfilterstohdr and passes itself in as nsimsgfilterhitnotify interface to handle filter hits. e.g., imap, pop3. 39 mailnews protocols mailnews, thunderbird 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. 40 mailnews fakeserver mailnews, seamonkey, thunderbird fakeserver is a testing server that implements a generic text-based protocol common to all major mailnews protocols (pop, imap, smtp, and nntp) designed for use in automated tests. it can also be used in manual qa tests. 41 mailnews xpcshell-tests automated testing, d...
...And 7 more matches
Plug-in Development Overview - Plugins
plan your plug-in: decide on the services you want the plug-in software to provide and how it will interact with the browser and the special media for which the plug-in is created. decide the mime type for the plug-in (see registering plug-ins). set up your development environment properly. ...
.... for more information about mime types, see these mime rfcs: rfc-2045: "multipurpose internet mail extensions (mime) part one: format of internet message bodies" rfc-2046: "multipurpose internet mail extensions (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. ...
...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. ...
...And 7 more matches
Accessibility Inspector - Firefox Developer Tools
this article takes you through the main features of the accessibility inspector and how to use it. a (very) brief guide to accessibility accessibility is the practice of making your websites usable by as many people as possible. ...
...u first open any of the other developer tools, the accessibility features are turned off (unless you've already got them turned on in another browser tab, or got the firefox accessibility engine started already, e.g., you might be a screenreader user or tester). this is because the accessibility engine runs in the background when the accessibility features are turned on. while it’s running, it slows performance and takes up memory; therefore it interferes with the metrics from other panels such as memory and performance as well as overall browser performance. for this reason, you should keep it turned off when you aren't specifically using it. when first implemented, the accessibility engine had to be explicitly turned on. starting in firefox 79, it is automatically enabled when you do one...
...ce and takes up memory; therefore it interferes with the metrics from other panels such as memory and performance as well as overall browser performance. for this reason, you should keep it turned off when you aren't specifically using it. when first implemented, the accessibility engine had to be explicitly turned on. starting in firefox 79, it is automatically enabled when you do one of the following: choose accessibility in the tools > web developer menu. select the accessibility tab in the developer tools toolbox. right-click in the main browser window, and choose inspect accessibility properties in the context menu. right-click an item in the html pane of the page inspector, and choose show accessibility properties in the context menu. once activated, the accessibility engine re...
...And 7 more matches
Debugger.Frame - Firefox Developer Tools
g the stack back to a previously accessed frame yields the same frame object as before. debugger code can add its own properties to a frame object and expect to find them later, use == to decide whether two expressions refer to the same frame, and so on. (if more than one debugger instance is debugging the same code, each debugger gets a separate debugger.frame instance for a given frame. ...
...elf. visible frames when inspecting the call stack, debugger does not reveal all the frames that are actually present on the stack: while it does reveal all frames running debuggee code, it omits frames running the debugger’s own code, and omits most frames running non-debuggee code. we call those stack frames a debugger does reveal visible frames. a frame is a visible frame if any of the following are true: it is running debuggee code; its immediate caller is a frame running debuggee code; or it is a "debugger" frame, representing the continuation of debuggee code invoked by the debugger. the “immediate caller” rule means that, when debuggee code calls a non-debuggee function, it looks like a call to a primitive: you see a frame for the non-debuggee function that ...
... debuggee is not considered an “immediate caller” of handler methods it triggers. even though the debuggee and debugger share the same javascript stack, frames pushed for spidermonkey’s calls to handler methods to report events in the debuggee are never considered visible frames.) invocation functions and “debugger” frames aninvocation function is any function in this interface that allows the debugger to invoke code in the debuggee: debugger.object.prototype.call, debugger.frame.prototype.eval, and so on. while invocation functions differ in the code to be run and how to pass values to it, they all follow this general procedure: letolder be the youngest visible frame on the stack, or null if there is no such frame. (this is never one of the the debugger’s own frames; thos...
...And 7 more matches
Debugger.Script - Firefox Developer Tools
a sequence of bytecode in the debuggee or to a block of webassembly code. for the former, it is the debugger api’s presentation of a jsapi jsscript object. the two cases are distinguished by their format property being "js" or "wasm". debugger.script for jsscripts for debugger.script instances referring to a jsscript, they are distinguished by their format property being "js". each of the following is represented by a single jsscript object: the body of a function—that is, all the code in the function that is not contained within some nested function. the code passed to a single call to eval, excluding the bodies of any functions that code defines. the contents of a <script> element. a dom event handler, whether embedded in html or attached to the element by oth...
... constructs exactly one debugger.script instance for each underlying script object; debugger code can add its own properties to a script object and expect to find them later, use == to decide whether two expressions refer to the same script, and so on. (if more than one debugger instance is debugging the same code, each debugger gets a separate debugger.script instance for a given script. this allows the code using each debugger instance to place whatever properties it likes on its debugger.script instances, without worrying about interfering with other debuggers.) a debugger.script instance is a strong reference to a jsscript object; it protects the script it refers to from being garbage collected. note that spidermonkey may use the same debugger.script instances for equivalent functions ...
...ger 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. if the behavior does not differ, no ...
...And 7 more matches
EventTarget.addEventListener() - Web APIs
s and constants available to the containing function are also available to the event handler when using an arrow function. ...
... before using a particular value in the options object, it's a good idea to ensure that the user's browser supports it, since these are an addition that not all browsers have supported historically. see safely detecting option support for details. other notes why use addeventlistener()? addeventlistener() is the way to register an event listener as specified in w3c dom. the benefits are as follows: it allows adding more than a single handler for an event. this is particularly useful for ajax libraries, javascript modules, or any other kind of code that needs to work well with other libraries/extensions. it gives you finer-grained control of the phase when the listener is activated (capturing vs. bubbling). it works on any dom element, not just html elements. the alternative, older ...
...r for an event. this is particularly useful for ajax libraries, javascript modules, or any other kind of code that needs to work well with other libraries/extensions. it gives you finer-grained control of the phase when the listener is activated (capturing vs. bubbling). it works on any dom element, not just html elements. the alternative, older way to register event listeners, is described below. adding a listener during event dispatch if an eventlistener is added to an eventtarget while it is processing an event, that event does not trigger the listener. however, that same listener may be triggered during a later stage of event flow, such as the bubbling phase. multiple identical event listeners if multiple identical eventlisteners are registered on the same eventtarget with the sam...
...And 7 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
of interfering with another script's execution, yet also ensures that the microtask runs before the user agent has the opportunity to react to actions taken by the microtask. javascript promises and the mutation observer api both use the microtask queue to run their callbacks, but there are other times when the ability to defer work until the current event loop pass is wrapping up. in order to allow microtasks to be used by third-party libraries, frameworks, and polyfills, the queuemicrotask() method is exposed on the window and worker interfaces through the windoworworkerglobalscope mixin. tasks vs microtasks to properly discuss microtasks, it's first useful to know what a javascript task is and how microtasks differ from tasks. this is a quick, simplified explanation, but if you would li...
...ated with settimeout() or setinterval() is reached, causing the corresponding callback to 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 d...
... until the queue is empty, there's a real risk of getting the event loop endlessly processing microtasks. be cautious with how you go about recursively adding microtasks. using microtasks before getting farther into this, it's important to note again that most developers won't use microtasks much, if at all. they're a highly specialized feature of modern browser-based javascript development, allowing you to schedule code to jump in front of other things in the long set of things waiting to happen on the user's computer. abusing this capability will lead to performance problems. enqueueing microtasks as such, you should typically use microtasks only when there's no other solution, or when creating frameworks or libraries that need to use microtasks in order to create the functionality the...
...And 7 more matches
Timing element visibility with the Intersection Observer API - Web APIs
tracking visibility of ads is being used in this example. it turns out that one of the most common uses of flash or other script in advertising on the web is to record how long each ad is visible, for the purpose of billing and payment of revenues. without the intersection observer api, this winds up being done using intervals and timeouts for each individual ad, or other techniques that tend to slow the page down. using this api lets everything get streamlined by the browser to reduce the impact on performance substantially. let's get started! site structure: the html the site's structure is not too complicated. we'll be using css grid to style and lay out the site, so we can be pretty straightforward here: <div class="wrapper"> <header> <h1>a fake blog</h1> <h2>showing inters...
... observer in action!</h2> </header> <aside> <nav> <ul> <li><a href="#link1">a link</a></li> <li><a href="#link2">another link</a></li> <li><a href="#link3">one more link</a></li> </ul> </nav> </aside> <main> </main> </div> this is the framework for the entire site. at the top is the site's header region, contained within a <header> block. below that, we define the site's sidebar as a list of links within an <aside> block. finally comes the main body. we start with an empty <main> element here. this box will be populated using script later. styling the site with css with the structure of the site defined, we turn to the styling for the site. let's look at the style for each component of the page individually. the basics we provide s...
...ost all remaining available space. the first row will be used specially for the site header. the rows are sized the same way as the columns: the first one is automatically sized and the one uses the remaining space, but at least enough space to provide room for all elements within it. the wrapper's width is fixed at 700px so that it will fit in the available space when presented inline on mdn below. the header the header is fairly simple, since for this example all it contains is some text. its style looks like this: header { grid-column: 1 / -1; grid-row: 1; background-color: aliceblue; } grid-row is set to 1, since we want the header to be placed in the top row of the site's grid. more interesting is our use of grid-column here; here we specify that we want the column to start i...
...And 7 more matches
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
meras are used: when rendering animation—whether for filmmaking or for use within the context of a presentation or game—the virtual camera is used just like a real-world film camera. as much as possible, standard cinematographic techniques are used, since the viewer has likely grown up watching films using those techniques, and has subconscious expectations that a film or animation will follow those methods. deviating from them can pull the viewer out of the moment. in business applications, the 3d camera is used to simply set the apparent size and perspective when rendering things such as graphs and charts. in mapping applications, the camera may either be placed directly over the scene, or might use various angles to show perspective. for 3d gps solutions, the camera is positioned ...
...over the scene, or might use various angles to show perspective. for 3d gps solutions, the camera is positioned to show the area around the user, with the majority of the display showing the area ahead of the user's path of motion. when using webgl to accelerate 2d graphics drawing, the camera is typically placed directly above the center of the scene with the distance and field of view set to allow the entire scene to be presented. when accelerating bitmapped graphics, the renderer would draw the 2d image into a webgl texture's buffer, then redraw the texture to refresh the screen. this essentially uses the texture as a backbuffer for performing multiple buffering in your 2d graphics application. cameras in gaming there are many kinds of games, and as such, there are several ways in whi...
...ced 3d games, a camera or camera-like object could be used to determine what a non-player character can see, relying on the same rendering and physics engine used by player characters for non-player characters. in single-screen 2d games, the camera is not associated directly with the player or any other character in the game, but is instead either fixed above or next to the game play area, or follows the action as the action moves around a scrolling game world. for example, a classic arcade game such as pac-man takes place on a fixed game map, so the camera remains fixed a set distance above the map, always pointed straight down at the game world. in a side-scrolling or top-scrolling game such as super mario bros., the camera moves along left and right (or up and down, or both) to ensure th...
...And 7 more matches
Using the Web Audio API - Web APIs
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. ...
...ntrol. a powerful feature of the web audio api is that it does not have a strict "sound call limitation". for example, there is no ceiling of 32 or 64 sound calls at one time. some processors may be capable of playing more than 1,000 simultaneous sounds without stuttering. example code our boombox looks like this: note the retro cassette deck with a play button, and vol and pan sliders to allow you to alter the volume and stereo panning. we could make this a lot more complex, but this is ideal for simple learning at this stage. check out the final demo here on codepen, or see the source code on github. browser support modern browsers have good support for most features of the web audio api. there are a lot of features of the api, so for more exact information, you'll have to check th...
... web audio api. there are a lot of features of the api, so for more exact information, you'll have to check the browser compatibility tables at the bottom of each reference page. audio graphs everything within the web audio api is based around the concept of an audio graph, which is made up of nodes. the web audio api handles audio operations inside an audio context, and has been designed to allow modular routing. basic audio operations are performed with audio nodes, which are linked together to form an audio routing graph. you have input nodes, which are the source of the sounds you are manipulating, modification nodes that change those sounds as desired, and output nodes (destinations), which allow you to save or hear those sounds. several audio sources with different channel layouts a...
...And 7 more matches
Using Web Workers - Web APIs
ent page. in addition, workers may use xmlhttprequest for network i/o, with the exception that the responsexml and channel attributes on xmlhttprequest always return null. dedicated workers as mentioned above, a dedicated worker is only accessible by the script that called it. in this section we'll discuss the javascript found in our basic dedicated worker example (run dedicated worker): this allows you to enter two numbers to be multiplied together. the numbers are sent to a dedicated worker, multiplied together, and the result is returned to the page and displayed. this example is rather trivial, but we decided to keep it simple while introducing you to basic worker concepts. more advanced details are covered later on in the article. worker feature detection for slightly more controlle...
...together, and the result is returned to the page and displayed. this example is rather trivial, but we decided to keep it simple while introducing you to basic worker concepts. more advanced details are covered later on in the article. worker feature detection for slightly more controlled error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (main.js): if (window.worker) { ... } spawning a dedicated worker creating a new worker is simple. all you need to do is call the worker() constructor, specifying the uri of a script to execute in the worker thread (main.js): var myworker = new worker('worker.js'); sending messages to and from a dedicated worker the magic of workers happens via the postmessage() method and the onm...
... anything you like in the message. in the worker, we can respond when the message is received by writing an event handler block like this (worker.js): onmessage = function(e) { console.log('message received from main script'); var workerresult = 'result: ' + (e.data[0] * e.data[1]); console.log('posting message back to main script'); postmessage(workerresult); } the onmessage handler allows us to run some code whenever a message is received, with the message itself being available in the message event's data attribute. here we simply multiply together the two numbers then use postmessage() again, to post the result back to the main thread. back in the main thread, we use onmessage again, to respond to the message sent back from the worker: myworker.onmessage = function(e) { res...
...And 7 more matches
Color picker tool - CSS: Cascading Style Sheets
; user-select: none; } .ui-input-slider * { float: left; height: 100%; line-height: 100%; } /* input slider */ .ui-input-slider > input { margin: 0; padding: 0; width: 50px; text-align: center; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .ui-input-slider-info { width: 90px; padding: 0px 10px 0px 0px; text-align: right; text-transform: lowercase; } .ui-input-slider-left, .ui-input-slider-right { width: 16px; cursor: pointer; background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center left no-repeat; } .ui-input-slider-right { background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center right no-repeat; } .ui-input-slider-name { width: 90px; padding: 0 10px 0 0; text-align: right; text-tra...
...} .ui-input-slider-left, .ui-input-slider-right { width: 16px; cursor: pointer; background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center left no-repeat; } .ui-input-slider-right { background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center right no-repeat; } .ui-input-slider-name { width: 90px; padding: 0 10px 0 0; text-align: right; text-transform: lowercase; } .ui-input-slider-btn-set { width: 25px; background-color: #2c9fc9; border-radius: 5px; color: #fff; font-weight: bold; line-height: 14px; text-align: center; } .ui-input-slider-btn-set:hover { background-color: #379b4a; cursor: pointer; } /* * color picker tool */ body { max-width: 1000px; margin: 0 auto; font-family: "segoe ui", arial, helvetica, sans-serif; box-sha...
...isplay: table; } /** * picker zone */ #picker { padding: 10px; width: 980px; } .ui-color-picker { padding: 3px 5px; float: left; border-color: #fff; } .ui-color-picker .switch_mode { display: none; } .ui-color-picker .preview-color:hover { cursor: move; } /** * picker container */ #picker-samples { width: 375px; height: 114px; max-height: 218px; margin: 0 10px 0 30px; overflow: hidden; position: relative; float: left; transition: all 0.2s; } #picker-samples .sample { width: 40px; height: 40px; margin: 5px; border: 1px solid #ddd; position: absolute; float: left; transition: all 0.2s; } #picker-samples .sample:hover { cursor: pointer; border-color: #bbb; transform: scale(1.15); border-radius: 3px; } #picker-samples .sample[data-active='true'] { border...
...And 7 more matches
Typical use cases of Flexbox - CSS: Cascading Style Sheets
x use case. when we have a set of items that we want to display horizontally, we may well end up with additional space. we need to decide what to do with that space, and have a couple of options. ...
...you can change how the space is distributed using the space-around value, or where supported, space-evenly. ...
...space-evenly. you could also use flex-start to place the space at the end of the items, flex-end to place it before them, or center to centre the navigation items. space distributed within the items a different pattern for navigation would be to distribute the available space within the items themselves, rather than create space between them. ...
...And 7 more matches
Introduction to formatting contexts - CSS: Cascading Style Sheets
tting context will lay its children out as flex items, etc. each formatting context has specific rules about how layout behaves when in that context. block formatting contexts the outermost element in a document that uses block layout rules establishes the first, or initial block formatting context. this means that every element inside the <html> element's block is laid out according to normal flow following the rules for block and inline layout. elements participating in a bfc use the rules outlined by the css box model, which defines how an element's margins, borders, and padding interact with other blocks in the same context. creating a new block formatting context the <html> element is not the only element capable of creating a block formatting context. any block-level element can be ...
...lined by the css box model, which defines how an element's margins, borders, and padding interact with other blocks in the same context. creating a new block formatting context the <html> element is not the only element capable of creating a block formatting context. any block-level element can be made to create a bfc by the application of certain css properties. ...
...n the following situations: elements made to float using float absolutely positioned elements (including position: fixed or position: sticky) elements with display: inline-block table cells or elements with display: table-cell, including anonymous table cells created when using the display: table-* properties table captions or elements with display: table-caption block elements where overflow has a value other than visible elements with display: flow-root or display: flow-root list-item elements with contain: layout, content, or strict flex items grid items multicol containers elements with column-span set to all this is useful because a new bfc will behave much like the outermost document in that it becomes a mini-layout inside the main layout. a bfc contains everything insi...
...And 7 more matches
Logical properties for margins, borders and padding - CSS: Cascading Style Sheets
the logical properties and values specification defines flow-relative mappings for the various margin, border, and padding properties and their shorthands. in this guide we take a look at these. if you have looked at the main page for css logical properties 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 t...
...ock sets all the block margins. margin-inline sets all the inline margins. padding-block sets the block padding. padding-inline sets the inline padding. margin examples the mapped margin properties of margin-inline-start, margin-inline-end, margin-block-start, and margin-inline-end can be used instead of their physical counterparts. in the example below i have created two boxes and added different sized margins to each edge. i have added an extra container with a border in order to make the margin more obvious to see. one box uses physical properties and the other logical properties. try changing the direction property to rtl to cause the boxes to display in a right-to-left direction, the margins on the first box will stay in the same place, wh...
...ing the direction property to rtl to cause the boxes to display in a right-to-left direction, the margins on the first box will stay in the same place, while the margins on the inline dimension of the second box will switch. you can also try changing the writing-mode from horizontal-tb to vertical-rl. again, notice how the margins stay in the same place for the first box, but switch around to follow the text direction in the second. margin shorthands as we can now target both sides of a box — either both inline sides or both block sides — there are new shorthands available, margin-inline and margin-block, which accept two values. the first value will apply to the start of that dimension, the second to the end. if you only use one value it is applied to both. in a horizontal writing ...
...And 7 more matches
Basic Shapes - CSS: Cascading Style Sheets
s type work. they range from simple circles to complex polygons. before looking at the shapes, it is worth understanding two pieces of information that go together to make these shapes possible: the <basic-shape> type the reference box the <basic-shape> type the <basic-shape> type is used as the value for all of our basic shapes. this type uses functional notation: the type of shape is followed by brackets, inside of which are additional values used to describe the shape. the arguments which are accepted vary depending on the shape that you are creating. we will cover these in the examples below. the reference box understanding the reference box used by css shapes is important when using basic shapes, as it defines each shape's coordinate system. you have already met the reference ...
... understanding the reference box used by css shapes is important when using basic shapes, as it defines each shape's coordinate system. you have already met the reference box in the guide on creating shapes from box values, which directly uses the reference box to create the shape. the firefox shapes inspector helpfully shows the reference box in use when you inspect a shape. in the screenshot below i have created a circle, using shape-outside: circle(50%). the floated element has 20 pixels of padding, border and margin applied, and the shapes inspector highlights these reference boxes. when using a basic shape the reference box used by default is the margin-box. you can see in the screenshot that the shape is being defined with reference to that part of the box model. you can add the var...
...erefore change this in order that your shape uses the different parts of the box model, for example to use the border. .shape { shape-outside: circle(50%) border-box; } what is worth noting is that the margin-box will clip the shape, therefore shapes created in reference to other shapes which extend past the margin box will have the shape clipped to the margin box. we will see this in the following examples of basic shapes. for an excellent description of references boxes as they apply to css shapes see understanding reference boxes for css shapes. inset() the inset() type defines a rectangle, which may not seem very useful as simply floating an item will give you a rectangular shape around it. however the inset() types enables the definition of offsets, thus pulling the content in ov...
...And 7 more matches
Overview of CSS Shapes - CSS: Cascading Style Sheets
tom of the item in a rectangular fashion. if you then apply a circle shape, the text would then wrap round the line of the circle. there are a number of ways to create these shapes and in these guides we will find out how css shapes work, and consider some ways you might like to use them. ...
...i have then applied the shape-outside property to it with a value of circle(50%). ...
...city or greater than the threshold value are used in the shape. any other parts are ignored. shape-margin — sets a margin around the defined shape defining basic shapes the shape-outside property allows us to a define a shape. it takes a variety of values, all of which define different shapes, specified in the <basic-shape> datatype. we can start by looking at a very simple case. in the following example i have an image floated left. i have then applied the shape-outside property to it with a value of circle(50%). the result is that the content now curves around the circular shape rather than following the rectangle created by the box of the image. as in this level of the specification an element has to be floated in order to apply <basic-shape> to it; this has the side-effect of cr...
...And 7 more matches
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
these keywords instead of numeric representations of colors if you choose to do so and there's a keyword representing the exact color you want to use. color keywords include the standard primary and secondary colors (such as red, blue, or orange), shades of gray (from black to white, including colors like darkgray and lightgrey), and a variety of other blended colors including lightseagreen, cornflowerblue, and rebeccapurple. see color keywords in <color> for a list of all available color keywords. rgb values there are three ways to represent an rgb color in css. hexadecimal string notation hexadecimal string notation represents a color using hexadecimal digits to represent each of the color components (red, green, and blue). it may also include a fourth component: the alpha channel (or ...
...exadecimal digits of the color code. the string is case-insensitive. "#rrggbb" specifies a fully-opaque color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. "#rrggbbaa" specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. ...
... as an example, you can represent the opaque color bright blue as "#0000ff" or "#00f". to make it 25% opaque, you can use "#0000ff44" or "#00f4". ...
...And 7 more matches
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
Web › HTML › Element › audio
if you must offer autoplay functionality, you should make it opt-in (requiring a user to specifically enable it). however, this can be useful when creating media elements whose source will be set at a later time, under user control. see our autoplay guide for additional information about how to properly use autoplay. controls if this attribute is present, the browser will offer controls to allow the user to control audio playback, including volume, seeking, 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 or...
.... 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. ...
... when not present, the resource is fetched without a cors request (i.e. without sending the origin: http header), preventing its non-tainted used in <canvas> elements. if invalid, it is handled as if the enumerated keyword anonymous was used. ...
...And 7 more matches
<input type="file"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › file
first selected file. javascript can access the other files through the input's files property. if no file is yet selected, the string is "" (empty). the string is prefixed with c:\fakepath\, to prevent malicious software from guessing the user's file structure. ...
...mpty). the string is prefixed with c:\fakepath\, to prevent malicious software from guessing the user's file structure. additional attributes in addition to the common attributes shared by all <input> elements, inputs of type file also support the following attributes: attribute description accept one or more unique file type specifiers describing file types to allow capture what source to use for capturing image or video data files a filelist listing the chosen files multiple a boolean which, if present, indicates that the user may choose more than one file accept the accept attribute value is a string that defines the file types the file input should accept. this string is a comma-separated list of unique file typ...
...re was previously a boolean attribute which, if present, requested that the device's media capture device(s) such as camera or microphone be used instead of requesting a file input. files a filelist object that lists every selected file. this list has no more than one member unless the multiple attribute is specified. multiple when the multiple boolean attribute is specified, the file input allows the user to select more than one file. non-standard attributes in addition to the attributes listed above, the following non-standard attributes are available on some browsers. you should try to avoid using them when possible, since doing so will limit the ability of your code to function in browsers that don't implement them. attribute description webkitdirectory ...
...And 7 more matches
<input type="url"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › url
absolute url. this doesn't necessarily mean the url address exists, but it is at least formatted correctly. in simple terms, this means urlscheme://restofurl. see validation for details on how urls are validated to ensure that they're formatted properly. ...
...a global attribute which is used to indicate whether or not to enable spell checking for an element. it can be used on any editable content, but here we consider specifics related to the use of spellcheck on <input> elements. the permitted values for spellcheck are: false disable spell checking for this element. true enable spell checking for this element. "" (empty string) or no value follow the element's default behavior for spell checking. this may be based upon a parent's spellcheck setting or other factors. an input field can have spell checking enabled if it doesn't have the readonly attribute set and is not disabled. the value returned by reading spellcheck may not reflect the actual state of spell checking within a control, if the user agent's preferences override the setti...
...pell checking. this may be based upon a parent's spellcheck setting or other factors. an input field can have spell checking enabled if it doesn't have the readonly attribute set and is not disabled. the value returned by reading spellcheck may not reflect the actual state of spell checking within a control, if the user agent's preferences override the setting. non-standard attributes the following non-standard attributes are also available on some browsers. as a general rule, you should avoid using them unless it can't be helped. attribute description autocorrect a string indicating whether or not autocorrect is on or off. safari only. mozactionhint a string indicating the type of action that will be taken when the user presses the enter or retur...
...And 7 more matches
Standard metadata names - HTML: Hypertext Markup Language
Web › HTML › Element › meta › name
note: browsers may use this to identify the application. ...
...when several conflicting policies are defined, the no-referrer policy is applied. theme-color: indicates a suggested color that user agents should use to customize the display of the page or of the surrounding 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...
...e 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 be rendered using the default color palette. [light | dark]+ one or more color schemes supported by the document. specifying the same color scheme more than once has the same effect as specifying it only once. indicating multiple color schemes indicates that the first scheme is preferred by the document, but tha...
...And 7 more matches
itemprop - HTML: Hypertext Markup Language
an itemprop attribute specified, and an itemprop consists of a name-value pair. each name-value pair is called a property, and a group of one or more properties forms an item. property values are either a string or a url and can be associated with a very wide range of elements including <audio>, <embed>, <iframe>, <img>, <link>, <object>, <source> , <track>, and <video>. examples the example below shows the source for a set of elements marked up with itemprop attributes, followed by a table showing the resulting structured data. html <div itemscope itemtype="http://schema.org/movie"> <h1 itemprop="name">avatar</h1> <span>director: <span itemprop="director">james cameron</span> (born august 16, 1954)</span> <span itemprop="genre">science fiction</span> <a href="../movies/a...
... an item with a property whose value is a product id the id is not human-friendly, so the product's name is used the human-visible text instead of the id. <h1 itemscope> <data itemprop="product-id" value="9678aou879">the instigator 2000</data> </h1> for numeric data, the meter element and its value attribute can be used. a meter element <div itemscope itemtype="http://schema.org/produc...
...o properties, "favorite-color" and "favorite-fruit", both set to the value "orange" <div itemscope> <span itemprop="favorite-color favorite-fruit">orange</span> </div> note: there is no relationship between the microdata and the content of the document where the microdata is marked up. ...
...And 7 more matches
MIME types (IANA media types) - HTTP
e'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 strings which, when concatenated with a slash (/) between them, comprise a mime type. no whitespace is allowed in a mime type: type/subtype the type represents the general category into which the data type falls, such as video or text. the subtype identifies the exact kind of data of the specified type the mime type represents. for example, for the mime type text, the subtype might be plain (plain text), html (html source code), or calendar (for icalendar/.ics) files. each type has its own set of pos...
...any mime type whose main type is text, the optional charset parameter can be used to specify the character set used for the characters in the data. if no charset is specified, the default is ascii (us-ascii) unless overridden by the user agent's settings. to specify a utf-8 text file, the mime type text/plain;charset=utf-8 is used. mime types are case-insensitive but are traditionally written in lowercase, with the exception of parameter values, whose case may or may not have specific meaning. types there are two classes of type: discrete and multipart. discrete types are types which represent a single file or medium, such as a single text or music file, or a single video. a multipart type is one which represents a document that's comprised of multiple component parts, each of which may ha...
...'t handle multipart documents in a special way: the message is transmitted to the browser (which will likely show a "save as" window if it doesn't know how to display the document). there are two multipart types: message list at iana a message that encapsulates other messages. this can be used, for instance, to represent an email that includes a forwarded message as part of its data, or to allow sending very large messages in chunks as if it were multiple messages. examples include message/rfc822 (for forwarded or replied-to message quoting) and message/partial to allow breaking a large message into smaller ones automatically to be reassembled by the recipient. multipart list at iana data that is comprised of multiple components which may individually have different mime types. example...
...And 7 more matches
Feature-Policy: geolocation - HTTP
the http feature-policy header geolocation directive controls whether the current document is allowed to use the geolocation interface. when this policy is enabled, calls to getcurrentposition() and watchposition() will cause those functions' callbacks to be invoked with a positionerror code of permission_denied. by default, the geolocation api can be used within top-level documents and their same-origin child frames. this directive allows or prevents cross-origin frames from accessing geolocation. this includes same-origin frames. ...
...rrentposition() and watchposition() will cause those functions' callbacks to be invoked with a positionerror code of permission_denied. by default, the geolocation api can be used within top-level documents and their same-origin child frames. this directive allows or prevents cross-origin frames from accessing geolocation. this includes same-origin frames. ...
...and watchposition() will cause those functions' callbacks to be invoked with a positionerror code of permission_denied. by default, the geolocation api can be used within top-level documents and their same-origin child frames. this directive allows or prevents cross-origin frames from accessing geolocation. this includes same-origin frames. ...
...And 7 more matches
Firefox user agent string reference - HTTP
/5.0 is the general token that says the browser is mozilla compatible, and is common to almost every browser today. platform describes the native platform the browser is running on (e.g. windows, mac, linux or android), and whether or not it's a mobile phone. firefox os phones simply say "mobile"; the web is the platform. note that platform can consist of multiple "; "-separated tokens. see below for further details and examples. though fixed in firefox 69, previous 32-bit versions of firefox running on 64-bit processors would report that the system is using a 32-bit cpu. rv:geckoversion indicates the release version of gecko (such as "17.0"). in recent browsers, geckoversion is the same as firefoxversion. gecko/geckotrail indicates that the browser is based on gecko. on des...
... firefoxversion. the recommended way of sniffing for gecko-based browsers (if you have to sniff for the browser engine instead of using feature detection) is by the presence of the "gecko" and "rv:" strings, since some other browsers include a "like gecko" token. for other products 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 brows...
...droid is used for laptops. also, please use touch detection to find touch devices rather than looking for "mobi" or "tablet", since there may be touch devices which are not tablets. firefox os devices identify themselves without any operating system indication; for example: "mozilla/5.0 (mobile; rv:15.0) gecko/15.0 firefox/15.0". the web is the platform. windows windows user agents have the following variations, where x.y is the windows nt version (for instance, windows nt 6.1). windows version gecko user agent string windows nt on x86 cpu mozilla/5.0 (windows nt x.y; rv:10.0) gecko/20100101 firefox/10.0 windows nt on x64 cpu mozilla/5.0 (windows nt x.y; win64; x64; rv:10.0) gecko/20100101 firefox/10.0 macintosh here, x.y is the version of m...
...And 7 more matches
Closures - JavaScript
a closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). in other words, a closure gives you access to an outer function’s scope from an inner function. in javascript, closures are created every time a function is created, at function creation time. lexical scoping consider the following example code: function init() { var name = 'mozilla'; // name is a local variable created by init function displayname() { // displayname() is the inner function, a closure alert(name); // use variable declared in the parent function } displayname(); } init(); init() creates a local variable called name and a function called displayname(). the displayname() function is an inner function that is defined insid...
...nction. 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() function above. what's different (and interesting) is that the displayname() inner function is returned from the outer function before being ...
...ey 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 an event that is trig...
...And 7 more matches
String.prototype.charCodeAt() - JavaScript
ex is out of range, charcodeat() returns nan. description unicode code points range from 0 to 1114111 (0x10ffff). the first 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 exa...
...gate" 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 the length of the string. backward compatibility: in historic versions (like javascript 1.2) the charcodeat() method returns a number indicating the iso-latin-1 codeset value of the character at the given index. the iso-latin-1 codeset ranges from 0 to 255. the first 0 to 127 are a direct match o...
...or if it is equal to or greater than the length of the string. backward compatibility: in historic versions (like javascript 1.2) the charcodeat() method returns a number indicating the iso-latin-1 codeset value of the character at the given index. the iso-latin-1 codeset ranges from 0 to 255. the first 0 to 127 are a direct match of the ascii character set. examples using charcodeat() the following example returns 65, the unicode value for a. 'abc'.charcodeat(0) // returns 65 fixing charcodeat() to handle non-basic-multilingual-plane characters if their presence earlier in the string is unknown this version might be used in for loops and the like when it is unknown whether non-bmp characters exist before the specified index position. function fixedcharcodeat(str, idx) { // ex. fi...
...And 7 more matches
Template literals (Template strings) - JavaScript
you can use multi-line strings and string interpolation features with them. they were called "template strings" in prior editions of the es2015 specification. syntax `string text` `string text line 1 string text line 2` `string text ${expression} string text` tag`string text ${expression} string text` description template literals are enclosed by the backtick (` `) (grave accent) character instead of double or single quotes. template literals can contain placeholders. these are indicated by the dollar sign and curly braces (${expression}). the expressions in the placeholders and the text between the backticks (` `) get passed to a function. ...
... case, the tag expression (usually a function) gets called with the template literal, which you can then manipulate before outputting. to escape a backtick in a template literal, put a backslash (\) before the backtick. `\`` === '`' // --> true multi-line strings any newline characters inserted in the source are part of the template literal. ...
... order to get multi-line strings: console.log('string text line 1\n' + 'string text line 2'); // "string text line 1 // string text line 2" using template literals, you can do the same like this: console.log(`string text line 1 string text line 2`); // "string text line 1 // string text line 2" expression interpolation in order to embed expressions within normal strings, you would use the following syntax: let a = 5; let b = 10; console.log('fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.'); // "fifteen is 15 and // not 20." now, with template literals, you are able to make use of the syntactic sugar, making substitutions like this more readable: let a = 5; let b = 10; console.log(`fifteen is ${a + b} and not ${2 * a + b}.`); // "fifteen is 15 and // not 20." nesting templat...
...And 7 more matches
Authoring MathML - MathML
ists or tables but fortunately there are many generators from simple notations, wysiwyg editors and other content management systems to help writing web pages. mathematical notations are even more complex with structures like fractions, square roots or matrices that are likely to require their own tags. as a consequence, good mathml authoring tools are more important and we describe some tools below. in particular, the mozilla mathml team has been developing texzilla, a javascript unicode latex-to-mathml converter that is intended to be used in many scenarios described here. of course, the list is by no means exhaustive and you are invited to check out the w3c mathml software list where you can find various other tools. note that by design, mathml is well-integrated in html5 and in particul...
...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. ...
...note that ua string sniffing is not the most reliable method and might break from version to version: var ua = navigator.useragent; var isgecko = ua.indexof("gecko") > -1 && ua.indexof("khtml") === -1 && ua.indexof('trident') === -1; var iswebkit = ua.indexof('applewebkit') > -1 && ua.
...And 7 more matches
Image file type and format guide - Web media technologies
in this guide, we'll cover the image file types generally supported by web browsers, and provide insights that will help you select the most appropriate formats to use for your site's imagery. common image file types there are many image file formats in the world. however, the ones listed below are generally recognized as usable on the web, though bmp is generally not recommended as browser support is potentially constrained; it should usually be avoided for web content. abbreviation file format mime type file extension(s) browser compatibility apng animated portable network graphics image/apng .apng chrome, edge, firefox, opera, safari bmp bitmap file image/bmp .bmp chrome, edge, firefox, internet explorer, opera, safari...
...ons required webp web picture format image/webp .webp chrome, edge, firefox, opera the abbreviation for each format links to a longer description of the format, its capabilities, and detailed browser compatibility information; including which versions introduced support and specific special features that may have been introduced later. image file type details the following sections provide a brief overview of each of the image file types supported by web browsers. in the tables below, the term bits per component refers to the number of bits used to represent each color component. for example, an rgb color depth of 8 indicates that each of the red, green, and blue components are represented by an 8-bit value. bit depth, on the other hand, is the total number of ...
... than 255 or 256 colors, dithering is generally used. it is technically possible to tile multiple image blocks, each with its own color palette, to create truecolor images, but in practice this is rarely done. pixels are opaque, unless a specific color index is designated as transparent, in which case pixels colored that value are entirely transparent. gif supports simple animation, in which following an initial full-size frame, a series of images reflecting the parts of the image that change with each frame are provided. gif has been extremely popular for decades, due to its simplicity and compatibility. its animation support caused a resurgence in its popularity in the social media era, when animated gifs began to be widely used for short "videos", memes, and other simple animation seque...
...And 7 more matches
Populating the page: how browsers work - Web Performance
te of data received. time to first byte (ttfb) is the time between when the user made the request—say by clicking on a link—and the receipt of this first packet of html. the first chunk of content is usually 14kb of data. in our example above, the request is definitely less than 14kb, but the linked resources aren't requested until the browser encounters the links during parsing, described below. ...
...received. time to first byte (ttfb) is the time between when the user made the request—say by clicking on a link—and the receipt of this first packet of html. the first chunk of content is usually 14kb of data. in our example above, the request is definitely less than 14kb, but the linked resources aren't requested until the browser encounters the links during parsing, described below. tcp slow start / 14kb rule the first response packet will be 14kb. this is part of tcp slow start, an algorithm which balances the speed of a network connection. slow start gradually increases the amount of data transmitted until the network's maximum bandwidth can be determined. in tcp slow start, after receipt of the initial packet, the server doubles the size of the next packet to around 28kb. subseq...
... increases the amount of data transmitted until the network's maximum bandwidth can be determined. in tcp slow start, after receipt of the initial packet, the server doubles the size of the next packet to around 28kb. subsequent packets increase in size until a predetermined threshold is reached, or congestion is experienced. if you’ve ever heard of the 14kb rule for initial page load, tcp slow start is the reason why the initial response is 14kb, and why web performance optimization calls for focusing optimizations with this initial 14kb response in mind. tcp slow start gradually builds up transmission speeds appropriate for the network's capabilities to avoid congestion. congestion control as the server sends data in tcp packets, the user's client confirms delivery by returning ackn...
...And 7 more matches
Add to Home screen - Progressive web apps (PWAs)
why a2hs? a2hs is thought to be part of the progressive web app philosophy — giving web apps the same user experience advantages as native apps so they can compete in today's ecosystem wars. ...
... why a2hs? a2hs is thought to be part of the progressive web app philosophy — giving web apps the same user experience advantages as native apps so they can compete in today's ecosystem wars. ...
...ed in all mobile browsers, except ios webview. it's also supported in some chromium desktop browsers. firefox has had mobile support since v58 and is working on desktop support. see caniuse.com for exact details. how do you use it? we've written a very simple example web site (see our demo live, and also see the source code) that doesn't do much, but was developed with the necessary code to allow it to be added to a home screen, as well as a service worker to enable it to be used offline. the example displays a series of fox pictures. if you have firefox for android available, use it to navigate to our demo at https://mdn.github.io/pwa-examples/a2hs/. you'll see fox pictures, but more important, you'll see a "home" icon with a plus (+) icon inside it — this is the "add to home screen" ...
...And 7 more matches
Structural overview of progressive web apps - Progressive web apps (PWAs)
progressive web apps (pwas) can do anything any web content can do, they need to have a particular structure and include specific components in order to be recognized as a web app that can be used both on the web and installed and run as a local application. in 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. architecture of an app there are two main, different approaches to rendering a website — on the server or on the client. they both have their advantages and disadvantages, and you can mix the two approaches to some degree. server-side rendering (ssr) means a website is rendered on the server, so it offers quicker first load, but navigating between pages requires dow...
... server-side rendering (ssr) means a website is rendered on the server, so it offers quicker first load, but navigating between pages requires downloading new html content. it works great across browsers, but it suffers in terms of time navigating between pages and therefore general perceived performance — loading a page requires a new round trip to the server. client-side rendering (csr) allows the website to be updated in the browser almost instantly when navigating to different pages, but requires more of an initial download hit and extra rendering on the client at the beginning. the website is slower on an initial visit, but can be faster to navigate. the best results tend to come when you use both client-side and server-side rendering; you can render a web site on the server, cac...
...ded. the first page load is quick because of the ssr, and the navigation between 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 bef...
...And 7 more matches
SVG and CSS - SVG: Scalable Vector Graphics
note: elements referenced by <use> elements inherit the styles from that element. so to apply different styles to them you should use css custom properties. example make a new svg document as a plain text file, doc8.svg. ...
...ing started - svg demonstration</desc> <defs> <radialgradient id="fade" cx="0" cy="0" r="200" gradientunits="userspaceonuse"> <stop id="fade-stop-1" offset="33%"/> <stop id="fade-stop-2" offset="95%"/> </radialgradient> </defs> <text id="heading" x="-280" y="-270">svg demonstration</text> <text id="caption" x="-280" y="-250">move your mouse pointer over the flower.</text> <g id="flower"> <circle id="overlay" cx="0" cy="0" r="200" stroke="none" fill="url(#fade)"/> <g id="outer-petals"> <g class="quadrant"> <g class="segment"> <path class="segment-fill" d="m0,0 v-200 a40,40 0 0,0 -62,10 z"/> <path class="segment-edge" d="m0,-200 a40,40 0 0,0 -62,10"/> </g> <g class="segment" transform="rotate(18...
... <path class="segment-edge" d="m0,-200 a40,40 0 0,0 -62,10"/> </g> </g> </g> </g> </svg> make a new css file, style8.css. ...
...And 7 more matches
Subresource Integrity - Web security
subresource integrity (sri) is a security feature that enables browsers to verify that resources they fetch (for example, from a cdn) are delivered without unexpected manipulation. it works by allowing you to provide a cryptographic hash that a fetched resource must match. note: for subresource-integrity verification of a resource served from an origin other than the document in which it’s embedded, browsers additionally check the resource using cross-origin resource sharing (cors), to ensure the origin serving the resource allows it to be shared with the requesting origin. how subresource integrity helps using content delivery networks (cdns) to host files such as scripts and stylesheets that are shared among multiple sites can improve site performance and conserve bandwidth. ...
...sing subresource integrity you use the subresource integrity feature by specifying a base64-encoded cryptographic hash of a resource (file) you’re telling the browser to fetch, in the value of the integrity attribute of any <script> or <link> element. an integrity value begins with at least one string, with each string including a prefix indicating a particular hash algorithm (currently the allowed prefixes are sha256, sha384, and sha512), followed by a dash, and ending with the actual base64-encoded hash. note: an integrity value may contain multiple hashes separated by whitespace. a resource will be loaded if it matches one of those hashes. example integrity string with base64-encoded sha384 hash: sha384-oqvuafxrkap7fdgccy5uykm6+r9gqq8k/uxy9rx7hnqlgyl1kpzqho1wx4jwy8wc so oqvuafxr...
...nerator at https://www.srihash.org/ is an online tool you can use to generate sri hashes. ...
...And 7 more matches
Compiling a New C/C++ Module to WebAssembly - WebAssembly
t's look at how to use it to compile a c example to emscripten. there are a number of options available when compiling with emscripten, but the main two scenarios we'll cover are: compiling to wasm and creating html to run our code in, plus all the javascript "glue" code needed to run the wasm in the web environment. compiling to wasm and just creating the javascript. we will look at both below. ...
...the javascript "glue" code needed to run the wasm in the web environment. compiling to wasm and just creating the javascript. we will look at both below. creating html and javascript this is the simplest case 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. ...
...if we don’t specify this, emscripten will just output asm.js, as it does by default. ...
...And 7 more matches
panel - Archive of obsolete content
creates transient dialogs to implement part of an add-on's user interface. usage this module exports a single constructor function panel() which constructs a new panel. a panel is a dialog. its content is specified as html and you can execute scripts in it, so the appearance and behavior of the panel is limited only by what you can do using html, css, and javascript. the screenshot below shows a panel whose content is built from the list of currently open tabs: panels are useful for presenting temporary interfaces to users in a way that is easier for users to ignore and dismiss than a modal dialog, since panels are hidden the moment users interact with parts of the application interface outside them. a panel's content is loaded as soon as it is created, before the panel is shown, a...
...ts only of a static string, don't use contentscript: if you do, you may have problems getting your add-on approved on amo. instead, keep the script in a separate file and load it using contentscriptfile. this makes your code easier to maintain, secure, debug and review. getting user input note: this example uses the action button api, which is only available from firefox 29 onwards. the following add-on adds a button which displays a panel when clicked. the panel just contains a <textarea> element: when the user presses the return key, the contents of the <textarea> is sent to the main add-on code. the add-on consists of six files: main.js: the main add-on code, that creates the button and panel get-text.js: the content script that interacts with the panel content text-entry.ht...
...gle button. if this is supplied the panel will be shown attached to the button. see the section on attaching panels to buttons. a widget object. if this is supplied the panel will be shown attached to the widget. an object which specifies where in the window the panel should be shown. the rest of this section describes this object. the position object has one or more of the following properties: top, right, bottom and left. their values are expressed in pixels. any other properties will be ignored. the default alignment along each axis is centered: so to display a panel centred along the vertical or horizontal axis, just omit that axis: // show the panel centered horizontally and // aligned to the bottom of the content area require("sdk/panel").panel({ positio...
...And 6 more matches
widget - Archive of obsolete content
they can be simple icons or complex web pages. you can attach panels to them that open when they're clicked, or you can define a custom click handler to perform some other action, like opening a web page in a tab. there are a few advantages to using widgets over an ad hoc user interface. first, your users will be accustomed to interacting with add-ons via widgets and the add-on bar. second, it allows firefox to treat your interface as a first-class citizen. for example, in the future firefox may allow the user to drag widgets from the add-on bar to other toolbars. by exposing your interface as a widget, your add-on would automatically inherit such functionality. creation and content widgets can contain images or arbitrary web content. you can include this content inline as a string by usin...
...de this to listen to the widget's mouseover event. onmouseout function include this to listen to the widget's mouseout event. onattach function include this to listen to the widget's attach event. tooltip string optional text to show when the user's mouse hovers over the widget. if not given, the label is used. allow object an optional object describing permissions for the content. it should contain a single key named script whose value is a boolean that indicates whether or not to execute script in the content. script defaults to true. contentscriptfile string,array a local file url or an array of local file urls of content scripts to load. content scripts specified by this...
...hose specified by the contentscript property. contentscript string,array a string or an array of strings containing the texts of content scripts to load. content scripts specified by this property are loaded after those specified by the contentscriptfile property. contentscriptwhen string when to load the content scripts. ...
...And 6 more matches
StringView - Archive of obsolete content
as audio and video manipulation, access to raw data using websockets, and so forth, it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easily manipulate raw binary data. in the past, this had to be simulated by treating the raw data as a string and using the charcodeat() method to read the bytes from the data buffer. however, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats). javascript typed arrays provide a mechanism for accessing raw binary data much more efficiently. the stringview constructor is one level above typed arrays. the code stringview.js "use strict"; /*\ |*| |*| :: number.isintege...
... : nuint6 < 62 ? nuint6 - 4 : nuint6 === 62 ? 43 : nuint6 === 63 ? ...
...ments input (required) the argument the stringview is constructed from. it can be: another stringview a string a number an arraybuffer a typed array of uint8array, uint16array, or uint32array subclass any other kind of ordered object (like arrays, collections, etc.) if it is a number it will become the length of the new stringview; otherwise it will become its content. the following table shows the behavior of the stringview constructor. input class stringview.buffer stringview.rawdata stringview.bufferview stringview a new arraybuffer will be created. object reference to stringview.bufferview or a new arraybufferview of stringview.buffer will be created (depending on startoffset and length arguments passed). a new a...
...And 6 more matches
JavaScript Daemons Management - Archive of obsolete content
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 the javascript programming language, daemons are all processes created by javascript timers or by a worker instantiation. 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. in such a condition it is difficult and unnatural to keep 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.
...mework compatible with internet explorer (which doesn't support sending additional parameters to timers' callback function, neither with settimeout() or setinterval()) we included the ie-specific compatibility code (commented code), which enables the html5 standard parameters' passage functionality in that browser for both timers (polyfill), at the end of the daemon.js module. daemon.js what follows is the module that declares the daemon constructor (the core of this framework). the daemon constructor itself is nothing but a clone of the little framework minidaemon with added support for init and onstart functions (declarable during the instantiation of the daemon). so the minidaemon framework will remain the recommended way for simple animations, because daemon without its collection of me...
...this library requires daemon.js to work. the daemon.safe constructor is a dependent-clone of daemon which uses a recursive invocation of the settimeout timer rather than a single invocation of setinterval. /*\ |*| |*| ******************************* |*| * daemon-safe.js * |*| ********...
...And 6 more matches
Displaying web content in an extension without security issues - Archive of obsolete content
window. the issue that is commonly overlooked here is that the rss feed could contain some malicious javascript code and it would then execute with the privileges of the extension — meaning that it would get full access to the browser (cookies, history etc) and to user’s files. these issues can easily be avoided by making use of the existing security mechanisms in the mozilla codebase. the following article explains these security mechanisms, ideally an extension that needs to display web content (which is always potentially dangerous) will use all of them. displaying untrusted data as content in firefox, there is a distinction between chrome and content documents. the top document in a window is always a chrome document. if you look at the frames it loads, those will usually be chrome do...
... the value of the "type" attribute. but if you really have to do this, you will also have to remove the frame element from the document and insert it back. not giving privileges to documents that contain untrusted data the privileges that a document gets depend on where it comes from. for example, "chrome://foo/content/foo.xhtml" will have full privileges, "http://example.com/foo.xhtml" will be allowed to access example.com, "file:///c:/foo.xhtml" will be allowed to read files from disk (with some restrictions). as for the document that displays untrusted data, you don’t want it to have any privileges at all. here the "data:" protocol is useful. this protocol is special because it inherits the privileges from its parent document. however, if a "data:" document is the topmost content documen...
...t way you can have the template in your extension but still strip it off all privileges when it is loaded in a frame. restricting what documents that contain untrusted data can do there are several restrictions that can be applied per frame. here it is most important to disable javascript and plugins. ...
...And 6 more matches
JavaScript Object Management - Archive of obsolete content
n. the first step to good javascript object management is having a namespace, or a javascript object that contains our code and data, that you know will not conflict with firefox code or other extensions. namespace declaration is best located in a file of its own, so that you have this one js file that should be included in all of your xul files. we'll be using the placeholder 〈namespace〉 below. ...
... 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 need the namespace to be a global o...
... requires too much code, look for ways to divide it into multiple objects and files. you can include as many scripts in a xul window as you need. to initialize your chrome objects, it's usually better to run the initialization code from the "load" event handler for the window. the load event is fired after the dom on the window has loaded completely, but before it's displayed to the user. this allows you to manipulate and possibly change elements in the window without the user noticing the changes. /** * controls the browser overlay for the hello world extension. */ 〈namespace〉.browseroverlay = { /** * initializes this object. */ init : function(aevent) { this._stringbundle = document.getelementbyid("xulschoolhello-string-bundle"); // you can make changes to the wi...
...And 6 more matches
Source code directories overview - Archive of obsolete content
urce code for macos: both the powerpc and 68000 versions. gtk contains source code for gtk (a.k.a. the gimp toolkit) which runs on x-windows on unix. motif contains source code for motif, a toolkit which runs on x-windows on unix. os2 contains source code for os/2 warp. rhapsody contains source code for mac os x server (which is based on nextstep which is based on x-windows on unix) using yellow box (cocoa). beos contains source code for beos. qt contains source code for the qt toolkit, a c class library which runs on x-windows on unix, windows 95, windows 98 and window nt 4.0. photon contains source code for photon, a microkernel windowing system used in several real-time operating systems from qnx software systems ltd. seamonkey seamonkey is the development name for the mozilla b...
...photon contains source code for photon, a microkernel windowing system used in several real-time operating systems from qnx software systems ltd. seamonkey seamonkey is the development name for the mozilla browser suite. accessible contains code to support microsoft active accessibility and sun's atk accessibility api for linux. browser contains the 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...
...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 directory). content was split off from layout and contains objects as they are exposed to the dom. db contains c code for the mdb/mork database which is a low-level, general-purpose and cross-platform file library. it is used to store mail box data, news data and global history data. it has not been updated to support xpcom yet. this code originated in the mozilla classic code base. dbm contains c code for managing, reading and writing hash tables. it is used for the auto-completion feature on the url edit box (stored in netscape.hst in mozilla classi...
...And 6 more matches
Java in Firefox Extensions - Archive of obsolete content
ls will be deprecated (in the context of applets), "firefox and the java plug-in will continue to support the global java/packages keywords, in particular in the context of firefox extensions."). these 2 objects let you make use of the standard jdk classes, e.g., var ajavalist = new java.util.linkedlist(); if you want to load your own jars, then you can create your own java class loader. the following technique only works in javascript code linked from or contained in xul files. if you wish to call java code from within javascript code that implements some xpcom components, at this time, you need a different technique (refer to the complete java firefox extension). a good reason for calling java from within an xpcom component rather than from xul is to maintain a singleton (some singular ja...
...e xpcom components, at this time, you need a different technique (refer to the complete java firefox extension). a good reason for calling java from within an xpcom component rather than from xul is to maintain a singleton (some singular java object) across all firefox windows. if you call java from xul, then each firefox window will have its own class loader and hence its own "singleton". ...
... you must use the latest version, currently still in the sandbox, as prior versions only worked with liveconnect before java 6 update 11) which borrows some of the code of the java firefox extension in order to grant full privileges to java within a firefox extension, but it is easier to understand and doesn't require creation of a xpcom component. ...
...And 6 more matches
Space Manager Detailed Design - Archive of obsolete content
/** * remove the region associated with afrane. * * returns ns_ok if successful and ns_error_invalid_arg if there is no region * tagged with aframe */ nsresult removeregion(nsiframe* aframe); /** * clears the list of regions representing the unavailable space. */ void clearregions(); /** * methods for dealing with the propagation of float damage during * reflow. */ prbool hasfloatdamage() { return !mfloatdamage.isempty(); } void includeindamage(nscoord aintervalbegin, nscoord aintervalend) { mfloatdamage.includeinterval(aintervalbegin + my, aintervalend + my); } prbool intersectsdamage(nscoord aintervalbegin, nscoord aintervalend) { return mfloatdamage.intersects(aintervalbegin + my, aintervalend + my); } #ifdef debug...
...nscoord dy); /** * remove the region associated with afrane. * * returns ns_ok if successful and ns_error_invalid_arg if there is no region * tagged with aframe */ nsresult removeregion(nsiframe* aframe); /** * clears the list of regions representing the unavailable space. */ void clearregions(); float impact /** * methods for dealing with the propagation of float damage during * reflow. */ prbool hasfloatdamage() { return !mfloatdamage.isempty(); } void includeindamage(nscoord aintervalbegin, nscoord aintervalend) { mfloatdamage.includeinterval(aintervalbegin + my, aintervalend + my); } prbool intersectsdamage(nscoord aintervalbegin, nscoord aintervalend) { return mfloatdamage.intersects(aintervalbegin + my, aintervalend + my); } debug only methods /** * dump the s...
...ional * interfaces. */ nsiframe* getframe() const { return mframe; } implementation notes algorithm 1: getbanddata getbanddata is used to provide information to clients about what space if available and unavailable in a band of space. the client provides a vertical offset, the yoffset, that corresponds to the band that is of interest. ...
...And 6 more matches
Binding Attachment and Detachment - Archive of obsolete content
g property. -moz-binding value: none | [,]* <uri> | inherit initial value: none applies to: all elements (not generated content or pseudo-elements) inherited: no percentages: n/a the value of the -moz-binding property is a set of urls that identify specific bindings. an individual url in the set consists of the binding document's url and the binding's document-unique identifier. 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 differe...
...attribute, then the base binding at the end of the inheritance chain is the one that will inherit from the most derived binding that is already attached. for example, given a binding d1, with an explicit inheritance chain of d1 -> d2 -> d3 if this element is attached to an element using element.style.mozbinding that already has a binding chain of s1 -> s2 -> s3 the resulting binding chain following the addition of the binding is d1 -> d2 -> d3 -> s1 -> s2 -> s3 the inheritance between d3 and s1 is implicit, meaning that there is no connection in the xbl documents between the two bindings. the inheritance link has been forged dynamically through the invocation of the element.style.mozbinding. <constructor> call as a document is loaded and style rules are matched for elements, any bind...
...loads suppress the firing of the dom load event for the bound document. when the load event fires, and if all binding documents loaded successfully, it can be assumed that all bindings are attached to all elements in the page. for elements that are created during or after the load event is fired, no assumptions can be made regarding order of binding attachment. when a binding is attached, the following events occur: if required, anonymous content is cloned from the binding's content template and inserted around the bound element. the methods and properties of the binding are installed on the element and become available to scripts that reference the bound element. any specified event handlers are installed on their requested targets. if the binding needs to execute any initialization ...
...And 6 more matches
Menus - Archive of obsolete content
e attached to buttons. submenus may be created by nesting one menu inside of another. no special code needs to be written to open or close a menu or submenu, and, in addition, the menus are placed on screen in the appropriate locations automatically. there are four elements that a menupopup can be attached to. in each case, the menupopup element is placed as a direct child of the element. the following is a brief summary of these elements, examples of each will be provided later. menu the menu tag is used when placing menus on a menu bar. for example, the file and edit menus along the top of an application window (or the menubar on the top of screen). this type of menu is usually used for commands that apply to the entire application. commands that don't apply at a given time should be d...
...lication. commands that don't apply at a given time should be disabled. however, the actual top level menus do not generally change for a given window. button a menu may be attached to a button by setting the type attribute of the button to 'menu'. instead of creating a standard button, this will create a button with a small arrow or other indicator. clicking the button will display the menu, allowing a command to be selected. this type of menu would be used when you want to have a set of commands yet don't want to use a menu bar, for example in a dialog box. see menu buttons for more information. toolbarbutton toolbar buttons can also support menus. this works just like it does for other buttons. see menu buttons for more information. menulist a menulist is used when you wish the user ...
...ect from a list of items. for this type of menu, one of the items within it is selected. when another item is selected, the label of the item is set as the label of the menulist. other user interfaces call this type of widget a combobox. you may also see a popup tag used in place of the menupopup tag. the popup tag is deprecated but is equivalent to the menupopup tag. menu tag overview the following shows a simple menu example, containing a menubar with a single menu labeled 'file'. <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> </menubar> there are five tags use...
...And 6 more matches
Adding Event Handlers - Archive of obsolete content
etter to include code in a separate file as the xul window will load slightly faster. the src attribute is used to link in an external script file. our find files example let's add a script to the find file dialog. although it does not matter what the script file is called, usually it would be the same as the xul file with a .js extension. in this case, findfile.js will be used. add the line below just after the opening window tag and before any elements. <script src="findfile.js"/> we'll create the script file later when we know what we want to put in it. we'll define some functions in the file and we can call them in event handlers. you can include multiple scripts in a xul file by using multiple script tags, each pointing to a different script. you may use relative or absolute urls...
...ore any elements. <script src="findfile.js"/> we'll create the script file later when we know what we want to put in it. we'll define some functions in the file and we can call them in event handlers. you can include multiple scripts in a xul file by using multiple script tags, each pointing to a different script. you may use relative or absolute urls. for example, you may use urls of the following form: <script src="findfile.js"/> <script src="chrome://findfiles/content/help.js"/> <script src="http://www.example.com/js/items.js"/> this tutorial does not attempt to describe how to use javascript (except as related to event handling) as this is a fairly large topic and there are plenty of other resources that are available for this. by default the javascript console only shows errors ...
... when an action occurs that would trigger an event, such as the user moving the mouse, an event object is created corresponding to that event type. various properties are set on the event object such as the mouse position, the key that was pressed, and so forth. the event is then sent to the xul in phases. in the capturing phase, the event is first sent to the window, then to the document, followed by each ancestor of the xul element where the event occured downwards until it reaches that element. in the target phase, the event is sent to the target xul element. in the bubbling phase, the event is sent to each element back upwards until it reaches the window again. you can respond to an event during either the capturing or bubbling phase. once the event has finished propagating, any d...
...And 6 more matches
Keyboard Shortcuts - Archive of obsolete content
could be necessary when one's key commands are only triggered when the user is focused on a particular element). creating a keyboard shortcut xul provides methods in which you can define keyboard shortcuts. we've already seen in the section on menus that we can define an attribute called accesskey which specifies the key which a user can press to activate the menu or menu item. in the example below, the file menu can be selected by pressing alt + f together (or some other key combination for a specific platform). once the file menu is open, the close menu item can be selected by pressing c. example 1 : source view <menubar id="sample-menubar"> <menu id="file-menu" label="file" accesskey="f"> <menupopup id="file-popup"> <menuitem id="close-command" label="close" accesskey="c"/>...
...ar> you can also use the accesskey attribute on buttons. when the key is pressed in this case, the button is selected. you might want to set up more general keyboard shortcuts however. for example, pressing ctrl + c to copy text to the clipboard. although shortcuts such as this might not always be valid, they will usually work any time the window is open. usually, a keyboard shortcut will be allowed at any time and you can check to see whether it should do something using a script. for example, copying text to the clipboard should only work when some text is selected. key element xul provides an element, key, which lets you define a keyboard shortcut for a window. it has attributes to specify the key that should be pressed and what modifier keys (such as shift or ctrl) need to be pressed...
...an check to see whether it should do something using a script. for example, copying text to the clipboard should only work when some text is selected. key element xul provides an element, key, which lets you define a keyboard shortcut for a window. it has attributes to specify the key that should be pressed and what modifier keys (such as shift or ctrl) need to be pressed. an example is shown below: <keyset> <key id="sample-key" modifiers="shift" key="r"/> </keyset> this sample defines a keyboard shortcut that is activated when the user presses the shift key and r. the key attribute (note that it has the same name as the element itself) can be used to indicate which key should be pressed, in this case r. you could add any character for this attribute to require that key to be pressed. ...
...And 6 more matches
Manifest Files - Archive of obsolete content
browser, you can do this easily by just using a manifest with only one line in it: create a new directory somewhere. for example, on a windows machine, you might use c:\testfiles create a new ascii1 file called test.manifest in the chrome directory. it doesn't actually matter what the file is called as long as it has the .manifest extension. ( 1. doesn't work with utf-8 with bom.) add the following line to it: content tests file:///c:/testfiles/ the file path in that line should point to the directory created above. if you aren't sure what the file path is, open that directory in a browser and copy the url from the address field. that's it! now, all you need to do is add some xul files into that new directory, and you will be able to load them by typing in a chrome url of the form chro...
...vewrappers=yes overlay chrome://global/content/viewsource.xul chrome://browser/content/viewsourceoverlay.xul overlay chrome://global/content/viewpartialsource.xul chrome://browser/content/viewsourceoverlay.xul overlay chrome://browser/content/pageinfo.xul chrome://pippki/content/pageinfooverlay.xul two packages are listed here, 'branding' and 'browser'. three overlays are also specified, which allow content from different packages to combine together. extensions will make the most use of overlays, since they merge their ui with the browser ui. the file paths for the branding and browser packages use jar urls as the content is packaged up into an archive. a jar archive can be created with a zip utility. for a jar file located in the chrome directory, the syntax is fairly simple: jar:<filename...
...les, see localization. our example find files dialog let's create a manifest file for the find files dialog we'll be creating. you can combine all of the three types into a single file if you wish. this may be done when creating an extension such that all of the parts are in one file. we will do this for the find files dialog. create a file findfile.manifest in the chrome directory. add the following to the file: content findfile file:///findfile/content/ skin findfile classic/1.0 file:///findfile/skin/ locale findfile en-us file:///findfile/locale/ create the new directories listed above. it doesn't matter where the directories are created, but the file paths in the manifest file should point to the directories. naturally, you will want to use directory paths suitable for your system. ...
...And 6 more matches
XUL Event Propagation - Archive of obsolete content
you must be aware of what the actual process for raising, listening to, and handling events is. collectively, this process is referred to as the event model. events are used for different purposes, but they play a particularly important role in creating interactive xul-based user interfaces, since it is events that bring the information about user actions to the code behind the interface. the following image describes in a very basic way how the various actors in the event model interact with one another. the user clicks a button in the interface. this button responds to the user action by raising an event, a message meant to travel 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 el...
...t by displaying a simple alert dialog: <button value="click me" onclick="alert('thank you')" /> the opposite of event bubbling is event capturing. where event bubbling propagates an event from its target up higher into the node hiearchy, event capturing intercepts an event before it is received by other elements, even by the event target itself. ...
...s an event before it is received by other elements, even by the event target itself. the combination of basic these two basic event flow mechanisms, event bubbling and event capturing, mean that events raised in the interface can be caught anywhere above the element that raised the event. this flexibility in the xul event model is the focus of this article. ...
...And 6 more matches
Archived Mozilla and build documentation - Archive of obsolete content
suited to xbl. there is, however, no practical obstacle to the interface being implemented by any javascript object associated with a group of dom nodes, even non-anonymous xul nodes. calicalendarviewcontroller a calicalendarviewcontroller provides a way for a calicalendarview to create, modify, and delete items. implementing a calicalendarviewcontroller allows for these actions to be performed in a manner consistent with the rest of the application in which the calicalendarview is included. califiletype the califiletype interface provides information about a specific file type. chromeless [this project may not be active — check github https://github.com/mozilla/chromeless] creating a firefox ...
... 1.0 launch roadmap comments, ideas, questions and other discussion should be added on the devmo talk:1.0 launch roadmap page. further details on smaller tasks being done are available at user:dria:todo page. see also current events. download manager improvements in firefox 3 firefox 3 offers improvements to the download manager that allow multiple progress listeners, use of the storage api for data management, download resuming, and more. in addition, you can augment or replace the download manager's user 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. ...
...gerui 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 dragged around and dropped onto other objects. dtrace dtrace is sun microsystem's dynamic tracing framework that allows developers to instrument a program with probes that have little to no effect on performance when not in use and very little when active. probe data can be collected with scripts written in d (no, not that one). mozilla dtrace support has been added by the sun dtrace team and can be used on solaris 10 and mac os x 10.5. embedding faq em...
...And 6 more matches
TCP/IP Security - Archive of obsolete content
tcp/ip is widely used throughout the world to provide network communications. tcp/ip communications are composed of four layers that work together. when a user wants to transfer data across networks, the data is passed from the highest layer through intermediate layers to the lowest layer, with each layer adding information. at each layer, the logical units are typically composed of a header and a payload. the payload consists of the information passed down from the previous layer, while the header contains layer-specific information such as addresses. at the application layer, the payload is the actual application data. the lowest layer sends the accumulated data through the physical network; the data is then passed up through the layers to its destination. essentially, the data pr...
... application layer. ...
... application layer. this layer sends and receives data for particular applications, such as domain name system (dns), hypertext transfer protocol (http), and simple mail transfer protocol (smtp). transport layer. ...
...And 6 more matches
Mozilla XForms User Interface - Archive of obsolete content
elements will be presented in mozilla since the xforms specifications give only a hint of how controls might be rendered. currently xforms can be hosted by xhtml and xul in seamonkey and firefox. later we have plans to support xforms hosted by svg. the xforms specs define two kinds of xforms ui elements, called 'form controls' and 'xforms user interface'. elements from the "form controls" group allows users to interact with instance data. the set of "xforms user interface" elements exist to aid form authors in combining host language markup and xforms markup together in order to build user interfaces. some of the 'form controls' can have multiple appearances and thus may be rendered in multiple ways. we use the data type of the instance node that the form control is bound to as a clue when ma...
... when the spec reaches 'recommendation'-level status. if you see xhtml/xul then it means the control is available when xforms is hosted in either xhtml or xul. similarly, if you see xhtml only or xul only, then it means the control is available only in that host language. attribute sets this section describes attributes that are often used on xforms elements. these attributes are combined into following 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: ...
...orms 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-represented by a string (see the spec). it can have the following representations: text field - default representation. used for most data types, especially text data. checkbox - used for boolean instance data datepicker - default representation for date data types. similar to a combobox. consists of a text field for direct input and a dropdown calendar that can also be used to input the date value. calendar - used for date data types when appearanc...
...And 6 more matches
Anatomy of a video game - Game development
it helps beginners to the modern game development arena understand what is required when building a game and how web standards like javascript lend themselves as tools. experienced game programmers who are new to web development could also benefit, too. present, accept, interpret, calculate, repeat the goal of every video game is to present the user(s) with a situation, accept their input, interpret those signals into actions, and calculate a new situation resulting from those acts. ...
...call methods right as they are needed and idle (or do their other tasks) in the gaps. it is an excellent idea to attach your code to the moments that are appropriate for them. think about whether your function really needs to be called on a strict interval of time, every frame, or only after something else happens. being more specific with the browser about when your function needs to be called allows the browser to optimize when it is called. also, it will probably make your job easier. some code needs to be run frame-by-frame so why attach that function to anything other than the browser's redraw schedule? on the web, window.requestanimationframe() will be the foundation of most well-programmed per-frame main loops. a callback function must be passed in to it when it is called. that callb...
...n() 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. but do not immediately assume animations require frame-by-fram...
...And 6 more matches
CSS FAQ - Learn web development
Learn › CSS › Howto › CSS FAQ
nder correctly? browsers use the doctype declaration to choose whether to show the document using a mode that is more compatible with web standards or with old browser bugs. using a correct and modern doctype declaration at the start of your html will improve browser standards compliance. modern browsers have two main rendering modes: quirks mode: also called backwards-compatibility mode, allows legacy webpages to be rendered as their authors intended, following the non-standard rendering rules used by older browsers. documents with an incomplete, incorrect, or missing doctype declaration or a known doctype 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 d...
...ve it with this type, it won't be applied. what is the difference between id and class? html elements can have an id and/or class attribute. the id attribute assigns a name to the element it is applied to, and for valid markup, there can be only one element with that name. the class attribute assigns a class name to the element, and that name can be used on many elements within the page. css allows you to apply styles to particular id and/or class names. use a class-specific style when you want to apply the styling rules to many blocks and elements within the page, or when you currently only have element to style with that style, but you might want to add more later. use an id-specific style when you need to restrict the applied styling rules to one specific block or element. this styl...
... it is generally recommended to use classes as much as possible, and to use ids only when absolutely necessary for specific uses (like to connect label and form elements or for styling elements that must be semantically unique): using classes makes your styling extensible — even if you only have one element to style with a particular ruleset now, you might want to add more later. classes allow you to style multiple elements, therefore they can lead to shorter stylesheets, rather than having to write out the same styling information in multiple rules that use id selectors. shorter stylesheets are more performant. class selectors have lower specificity than id selectors, so are easier to override if needed. note: see selectors for more information. how do i restore the default valu...
...And 6 more matches
Creating hyperlinks - Learn web development
getting started with html. html text formatting, as covered in html text fundamentals. objective: to learn how to implement a hyperlink effectively, and link multiple files together. what is a hyperlink? hyperlinks are one of the most exciting innovations the web has to offer. they've been a feature of the web since the beginning, and are what makes the web a web. hyperlinks allow us to link documents to other documents or resources, link to specific parts of documents, or make apps available at a web address. almost any web content can be converted to a link so that when clicked or otherwise activated the web browser goes to another web address (url). note: a url can point to html files, text files, images, text documents, video and audio files, or anything else that li...
...in/registration pages (user tools), and more. anatomy of a link a basic link is created by wrapping the text or other content, see block level links, inside an <a> element and using the href attribute, also known as a hypertext reference, or target, that contains the web address. <p>i'm creating a link to <a href="https://www.mozilla.org/">the mozilla homepage</a>. </p> this gives us the following result: i'm creating a link to the mozilla homepage. adding supporting information with the title attribute another attribute you may want to add to your links is title. the title contains additional information about the link, such as which kind of information the page contains, or things to be aware of on the web site. <p>i'm creating a link to <a href="https://www.mozilla.org/" title...
... to your links is title. the title contains additional information about the link, such as which kind of information the page contains, or things to be aware of on the web site. <p>i'm creating a link to <a href="https://www.mozilla.org/" title="the best place to find more information about mozilla's mission and how to contribute">the mozilla homepage</a>. </p> this gives us the following result and hovering over the link displays the title as a tooltip. i'm creating a link to the mozilla homepage. note: a link title is only revealed on mouse hover, which means that people relying on keyboard controls or touchscreens to navigate web pages will have difficulty accessing title information. if a title's information is truly important to the usability of page, then you should pr...
...And 6 more matches
Adding vector graphics to the Web - Learn web development
in this article we'll show you how to include one in your webpage. prerequisites: you should know the basics of html and how to insert an image into your document. objective: learn how to embed an svg (vector) image into a webpage. ...
...n showing exactly where each pixel is to be placed, and exactly what color it should be. popular web raster formats include bitmap (.bmp), png (.png), jpeg (.jpg), and gif (.gif.) vector images are defined using algorithms — a vector image file contains shape and path definitions that the computer can use to work out what the image should look like when rendered on the screen. 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...
...e shapes. svg is for marking up graphics, not content. at the simplest end of the spectrum, you've got elements for creating simple shapes, like <circle> and <rect>. more advanced svg features include <fecolormatrix> (transform colors using a transformation matrix,) <animate> (animate parts of your vector graphic,) and <mask> (apply a mask over the top of your image.) as a simple example, the following code creates a circle and a rectangle: <svg version="1.1" baseprofile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="100%" fill="black" /> <circle cx="150" cy="100" r="90" fill="blue" /> </svg> this creates the following output: from the example above, you may get the impression that svg is easy to handcode. yes, you can h...
...And 6 more matches
Video and audio content - Learn web development
, easy way to host and consume videos, so you don't have to worry about the enormous bandwidth consumption. ovps even usually offer ready-made code for embedding video/audio in your webpages; if you use that route, you can avoid some of the difficulties we discuss in this article. we'll be discussing this kind of service a bit more in the next article. the <video> element the <video> element allows you to embed a video very easily. a really simple example looks like this: <video src="rabbit320.webm" controls> <p>your browser doesn't support html5 video. here is a <a href="rabbit320.webm">link to the video</a> instead.</p> </video> the features of note are: src in the same way as for the <img> element, the src (source) attribute contains a path to the video you want to embed. it wor...
...trols 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 video file, so the user can at least access it some way regardless of what browser they are using. the embedded video will look something like this: you can try the example live here (see also the source code.) using multiple source formats to improve compatibilit...
...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 spanish, in addition to audio for an english commentary track can be conceptualized as shown in the diagram below. also included are text tracks containing closed captions for the feature film, spanish subtitles for the film, and english captions for the commentary. the audio and video tracks within the container hold data in the appropriate format for the codec used to encode that media. different formats are used for audio tracks versus video tracks. each audio track is encoded using an audio codec, whi...
...And 6 more matches
Storing the information you need — Variables - Learn web development
bles contain values. this is an important distinction to make. variables aren't the values themselves; they are containers for values. you can think of them being like little cardboard boxes that you can store things in. declaring a variable to use a variable, you've first got to create it — more accurately, we call this declaring the variable. to do this, we type the keyword var or let followed by the name you want to call your variable: let myname; let myage; here we're creating two variables called myname and myage. try typing these lines into your web browser's console. after that, try creating a variable (or two) with your own name choices. note: in javascript, all code instructions should end with a semi-colon (;) — your code may work correctly for single lines, but probabl...
... a variable that doesn't exist at all — they are very different things. in the box analogy you saw above, not existing would mean there's no box (variable) for a value to go in. no value defined would mean that there is a box, but it has no value inside it. initializing a variable once you've declared a variable, you can initialize it with a value. you do this by typing the variable name, followed by an equals sign (=), followed by the value you want to give it. for example: myname = 'chris'; myage = 37; try going back to the console now and typing in these lines. you should see the value you've assigned to the variable returned in the console to confirm it, in each case. again, you can return your variable values by simply typing their name into the console — try these again: mynam...
...as first created, there was only var. this works basically fine in most cases, but it has some issues in the way it works — its design can sometimes be confusing or downright annoying. so, let was created in modern versions of javascript, a new keyword for creating variables that works somewhat differently to var, fixing its issues in the process. a couple of simple differences are explained below. we won't go into all the differences now, but you'll start to discover them as you learn more about javascript (if you really want to read about them now, feel free to check out our let reference page). for a start, if you write a multiline javascript program that declares and initializes a variable, you can actually declare a variable with var after you initialize it and it will still work. fo...
...And 6 more matches
Object-oriented JavaScript for beginners - Learn web development
ects article. a simple example let's start by looking at how you could define a person with a normal function. ...
...notice that it has all the features you'd expect in a function, although it doesn't return anything or explicitly create an object — it basically just defines properties and methods. notice also the thi...
...t's name property will be equal to the name value passed to the constructor call, and the greeting() method will use the name value passed to the constructor call too. note: a constructor function name usually starts with a capital letter — this convention is used to make constructor functions easier to recognize in code. ...
...And 6 more matches
Framework main features - Learn web development
he big 4” frameworks, looking at how frameworks tend to work from a high level, and the differences between them. prerequisites: familiarity with the core html, css, and javascript languages. objective: to understand the main code features of frameworks. domain-specific languages all of the frameworks discussed in this module are powered by javascript, and all allow you to use domain-specific languages (dsls) in order to build your applications. in particular, react has popularized the use of jsx for writing its components, while ember utilizes handlebars. unlike html, these languages know how to read data variables, and this data can be used to streamline the process of writing your ui. angular apps often make heavy use of typescript. typescript is not con...
...reamline your development process and make it easier to find help from the communities around those frameworks. jsx jsx, which stands for javascript and xml, is an extension of javascript that brings html-like syntax to a javascript environment. it was invented by the react team for use in react applications, but can be used to develop other applications — like vue apps, for instance. the following shows a simple jsx example: const subject = "world"; const header = ( <header> <h1>hello, {subject}!</h1> </header> ); this expression represents an html <header> element with a <h1> element inside. the curly braces around subject on line 4 tell the application to read the value of the subject constant and insert it into our <h1>. when used with react, the jsx from the previous snip...
... handlebars template: <header> <h1>hello, {{subject}}!</h1> </header> and this data: { subject: "world" } handlebars will build html like this: <header> <h1>hello, world!</h1> </header> typescript typescript is a superset of javascript, meaning it extends javascript — all javascript code is valid typescript, but not the other way around. typescript is useful for the strictness it allows developers to enforce on their code. for instance, consider a function add(), which takes integers a and b and returns their sum. in javascript, that function could be written like this: function add(a, b) { return a + b; } this code might be trivial for someone accustomed to javascript, but it could still be clearer. javascript lets us use the + operator to concatenate strings together, so...
...And 6 more matches
Styling Vue components with CSS - Learn web development
at how this is done. to start with, create a file called reset.css in the src/assets directory. files in this folder get processed by webpack. this means we can use css pre-processors (like scss) or post-processors (like postcss). while this tutorial will not be using such tools, it's good to know that when including such code in the assets folder it will be processed automatically. ...
... it will be processed automatically. ...
...rflow: visible; background: transparent; color: inherit; font: inherit; line-height: normal; -webkit-font-smoothing: inherit; -moz-osx-font-smoothing: inherit; -webkit-appearance: none; } button::-moz-focus-inner { border: 0; } button, input, optgroup, select, textarea { font-family: inherit; font-size: 100%; line-height: 1.15; margin: 0; } button, input { /* 1 */ overflow: visible; } input[type="text"] { border-radius: 0; } body { width: 100%; max-width: 68rem; margin: 0 auto; font: 1.6rem/1.25 "helvetica neue", helvetica, arial, sans-serif; background-color: #f5f5f5; color: #4d4d4d; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; } @media screen and (min-width: 620px) { body { font-size: 1.9rem; line-height: 1.
...And 6 more matches
Chrome registration
and it can be any file type viewable from within mozilla. it will typically be a xul file, since xul is designed for describing the contents of windows and dialogs. the javascript files that define the user interface are also contained within the content packages, as well as most xbl binding files. locale localizable applications keep all their localized information in locale providers. this allows translators to plug in a different chrome package to translate an application without altering the rest of the source code. the two main types of localizable files are dtd files and java-style properties files. skin a skin provider is responsible for providing a complete set of files that describe the visual appearance of the chrome. typically a skin provider will provide css files and images.
...ests are in a simple line-based format. each line is parsed individually; if the line is parsable the chrome registry takes the action identified by that line, otherwise the chrome registry ignores that line (and prints a warning message in the runtime error console). locale packagename localename path/to/files skin packagename skinname path/to/files note: the characters @ # ; : ? / are not allowed in the packagename. firefox 2, thunderbird 2, and seamonkey 1.1 will not find the chrome when packagename is mixed case. if the above example had a packagename of camelcasepackage, you would get an error message similar to "no chrome registered for chrome://camelcasepackage/path/to/files". firefox 3, thunderbird 3, and seamonkey 2 support mixed case. bug resolved in mozilla 1.9; see bug 13218...
...of camelcasepackage, you would get an error message similar to "no chrome registered for chrome://camelcasepackage/path/to/files". firefox 3, thunderbird 3, and seamonkey 2 support mixed case. bug resolved in mozilla 1.9; see bug 132183. manifest instructions comments # this line is a comment - you can put here whatever you want a line is a comment if it begins with the character '#'. any following character in the same line is ignored. manifest manifest subdirectory/foo.manifest [flags] this will load a secondary manifest file. this can be useful for separating component and chrome registration instructions, or separate platform-specific registration data. binary-component binary-component components/mycomponent.dll [flags] instructs mozilla to register and use a binary comp...
...And 6 more matches
The Firefox codebase: CSS Guidelines
s more descriptive and usually better. boilerplate make sure each file starts with the standard copyright header (see license boilerplate). before adding more css it is good practice to check if the css that is being written is needed, it can be the case that a common component has been already written could be reused with or without changes. most of the time, the common component already follows the a11y/theme standards defined in this guide. so, when possible, always prefer editing common components to writing your own. also, it is good practice to introduce a common class when the new element you are styling reuses some styles from another element, this allows the maintenance cost and the amount of code duplication to be reduced. formatting spacing & indentation 2 spaces indenta...
...ide 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 harder to override. using descend...
...tates (:hover, :active, [checked] or [disabled]). however, never try to increase the selector of the rule you are adding as it can easily become hard to understand. finally, once you have checked all the things above, you can permit yourself to use !important along with a comment why it is needed. using css variables adding new variables before adding new css variables, please consider the following questions: is the variable value changed at runtime? (either from javascript or overriden by another css file) if the answer is no, consider using a preprocessor variable or simply inlining the value. is the variable value used multiple times? if the answer is no and the value isn't changed at runtime, then you likely don't need a css variable. is there an alternative ...
...And 6 more matches
Obsolete Build Caveats and Tips
(warning ! from firefox 10, the compilator is visual studio 2010; if you want to use it, you must use a previous version of it !), or 2005 professional from build_instructions those who need to work with the code for firefox 3/mozilla 1.9 and earlier can check out the latest source using cvs. in reality, you should probably not need to do this, since that code is very obsolete. this note below seems redundant as this is true by default https://msdn.microsoft.com/en-us/library/dh8che7s%28v=vs.110%29.aspx note: starting with gecko 7.0, you should no longer include "-zc:wchar_t-" in the command line when building on windows. if you're using visual studio, go to project properties > c/c++ > language > treat wchar_t as built-in type and set it to "yes". from source_code/mercurial mo...
...g with gecko 7.0, you should no longer include "-zc:wchar_t-" in the command line when building on windows. if you're using visual studio, go to project properties > c/c++ > language > treat wchar_t as built-in type and set it to "yes". from source_code/mercurial mozilla-2.0 (firefox 4.0) code for the firefox 4.0 (gecko 2.0) release lives in releases/mozilla-2.0. ...
...ives in releases/mozilla-2.0. to get this code, do the following: # pull the mozilla source to the folder 20src/ - may take a while # as hundreds of megabytes of history is downloaded to .hg hg clone https://hg.mozilla.org/releases/mozilla-2.0/ 20src cd 20src mozilla-1.9.2 (firefox 3.6) code for the firefox 3.6 (gecko 1.9.2) release lives in releases/mozilla-1.9.2. to get this code, do the following: # pull the mozilla source to the folder 192src/ - may take a while # as hundreds of megabytes of history is downloaded to .hg hg clone https://hg.mozilla.org/releases/mozilla-1.9.2/ 192src cd 192src mozilla-1.9.1 (firefox 3.5) code for the firefox 3.5 (gecko 1.9.1) release lives in releases/mozilla-1.9.1. ...
...And 6 more matches
Extending a Protocol
to be done before we can successfully recompile. we will try to compile our code as we go, noting what we need to do along the way. to be sure, ipdl looks like a crazy mix of webidl, c++ header files, and es6. the syntax should hopefully be fairly obvious though. unfortunately, it's not really fully documented anywhere - and the ipdl parser gets easily confused (hence us excluding comments below). creating the protocol pecho.ipdl let's start by saving the following file to ./dom/ipc/pecho.ipdl. we will explain what all the parts mean below. note that the file's name and the protocol name must match. include protocol pwindowglobal; namespace mozilla { namespace dom { async refcounted protocol pecho { manager pwindowglobal; parent: async echo(nscstring data) returns (nscstring ...
...leanup if needed. ok, if we now try to compile this (./mach build), it will say: |manager| declaration in protocol `pecho' does not match any |manages| declaration in protocol `pwindowglobal' that's good! it means the syntax is correct, and now we need to pwindowglobal.ipdl to manage our pecho protocol. updating pwindowglobal.ipdl open up ./dom/ipc/pwindowglobal.ipdl. we need to add the following things: at the top of the file: include protocol pecho; after "manager pbrowser or pinprocess;", add: manages pecho; finally, under parent: add async pecho(); - this is the "constructor" part we talked about before, which will allow us to eventually send messages. so roughly, it looks like this (things in bold is what we added). // stuff.. include protocol pecho; async protoco...
... handle sending and receiving messages. and we also need to implement the actual management of these objects by dom/ipc/windowglobalchild.{h|cpp} and dom/ipc/windowglobalparent.{h|cpp}. if we now do ./mach build, it complains that "fatal error: 'mozilla/dom/echochild.h' file not found". that gives us a good place to start. defining echochild.h create ./dom/ipc/echochild.h, and define it as follows - the inline comments describe what's going on: #ifndef mozilla_dom_echochild_h #define mozilla_dom_echochild_h // we include the protocol, which is automatically generated for us. #include "mozilla/dom/pechochild.h" namespace mozilla { namespace dom { // note that echochild extends the protocol implementation. // the protocol implementation will give us the actual // methods for sending mes...
...And 6 more matches
PromiseWorker.jsm
like chromeworker objects, promiseworker is mostly used for js-ctypes but it is not limited to that. there is no xpcom access, similar to chromeworker. ...
...sm 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 promiseworker.js file should be brought in with the require() method. finally, the te...
...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 promiseworker.js file should be brought in with the require() method. finally, the template code should be added in. the code below is what should be copied and pasted: importscripts('resource://gre/modules/workers/require.js'); let promiseworker = require('resource://gre/modules/workers/promiseworker.js'); // instantiate abstractworker (see below). let worker = new promiseworker.abstractworker() worker.dispatch = function(method, args = []) { // dispatch a call to method `method` with args `args` return self[method](.
...And 6 more matches
Localization content best practices
example: bookmark. is this a noun or a verb? using meaningful ids could also help in these cases. strings are used in a specific context. for example accessibility (a11y) strings: in this case space is less important than clarity, since these strings are not displayed in the ui but used by tools like screen readers. there is an established format for localization comments: it's important to follow the format as closely as possible, since there are a number of automated tools that parse these comments for easier access and use by localizers. dtd files <!-- localization note (entity name): {{privacy}} will be replaced at run-time by an active link. the string 'privacy-link' will be used as text for this link. --> properties files # localization note(privacy-text): {{privacy}} will ...
... some don't, some use a non-breaking space. splitting splitting sentences into several keys often inadvertently presumes a grammar, a sentence structure, and such composite strings are often very difficult to translate. when a composite string is needed, try to give the translators "room to move". word order if a string will contain a placeholder, always add the placeholder to the string to allow the localizer to change the word order if necessary. for example, it might seem ok in english to present the strings [username] says: to localizers simply as says: but this will cause serious issues in many other languages as the agent of an action often will not come in front of the verb, but some other position. for example in irish/gaelic the correct order is be [username] at saying:. if a pla...
...rsion for translation. present the whole string or, if there is a significant need for a placeholder, use a placeholder. the word version may have to go before or after flash and one or both may need to be inflected. idiom idiom, in a loose sense, also has an impact on localization if it leads to strings being prepared in a way that renders them unlocalizable. for example, in english all the following begin with the same clause: the url of this feed is invalid; the url of this feed cannot be reached; the url of this feed cannot be parsed. it might be tempting to 'save time' by presenting this as the url of this feed %s and then is invalid; cannot be reached and cannot be parsed. however, linguistically these are different types of sentences and will be handled differently in other languages...
...And 6 more matches
Localization formats
ox</h1> the localizer then submits the translated html or php back to us by either checking in changes to svn or sending us a patch that pascal checks in. advantages to html good for small projects very simple for web developers gives localizers the exact context of translations a localizer who knows basic html can style translations to make sure translations display correctly...we can allow slight modifications (e.g. rtl or wider display) gives the possibility to customize content per locale simple workflow, just put the file on svn and it can appear on the staging server disadvantages to html very hard for qa if localizer changes something incorrectly (i.e. accidentally removes some html like </h1>, that localizer can break everything.) very hard to update automa...
...php/.po library, so if our webdev team sets up a site without gettext support, we still have .lang. (it should be noted that this is near impossibility since most sites will be set up with gettext support.) .lang files can be easily edited in a text editor with this setup, a localizer is given a "[something].lang" file containing all the strings needing localization. that file will have the following structure: ;getting started débuter avec firefox the english content is designated by the semi-colon and the localizer provides the translation underneath. that content is placed into an array that is used by the php code later. $array["getting started"] = "débuter avec firefox" the php code searches the array and returns the translation that is associated with the english term used...
...r avec firefox the english content is designated by the semi-colon and the localizer provides the translation underneath. that content is placed into an array that is used by the php code later. $array["getting started"] = "débuter avec firefox" the php code searches the array and returns the translation that is associated with the english term used by the web developer. see the example below. ...
...And 6 more matches
A guide to searching crash reports
teria. to achieve full power and flexibility requires a good understanding of both of these functions. search is easy to understand, but the grouping capabilities are easy to overlook. searching the search form you can get to the search page by clicking on the "super search" link near the toolbar at the top right of any page in crash-stats. ...
... by default, the "signature facet" tab is selected. ("facet" is a term that means "group".) in these results, the found crash reports are grouped according to crash signature and ranked by group size. ...
...e. the numbers are large because this search matched all firefox crash reports from the past seven days. the first group has over 100,000 crash reports, which accounts for 7.77% of all matching crashes. this indicates there are over 1.3 million crash reports matching this search. you can reorder the groups in various ways by clicking on the column headers. the links within the results do the following things. the first link in each "signature" column cell links to a signature report, which contains additional details about crash reports with that signature. the "add term" link in each "signature" column cell lets you perform a narrower subsequent search among crash reports with that signature. the links in each "bugs" column cell link to bug reports in bugzilla. the default search: c...
...And 6 more matches
AsyncTestUtils extended framework
the asynctestutils extended framework is one mechanism for testing the mailnews component of thunderbird. see mailnews automated testing for a description of the other testing mechanisms. ...
...ile to import everything you need: load("../../mailnews/resources/loghelper.js"); load("../../mailnews/resources/asynctestutils.js"); load("../../mailnews/resources/messagegenerator.js"); load("../../mailnews/resources/messagemodifier.js"); load("../../mailnews/resources/messageinjection.js"); if the directory where you are adding the tests does not have a head_*.js file that has the two following lines, add them at the top of your test file (before the lines shown above): load("../../mailnews/resources/maildirservice.js"); load("../../mailnews/resources/mailtestutils.js"); at the bottom of the test file, add the following: var tests =[ // list your tests here ]; function run_test() { configure_message_injection({mode: "local"}); async_run_tests(tests); } asynchronous t...
...probably move the asynctestutils framework to a nested event loop in a backwards-compatible fashion. how does this affect my tests? thanks to javascript enhancements available on the mozilla platform, it is possible for a function to yield control in such a way that the function stops running at the line where you use a yield statement and resumes execution on the next line when resumed. this allows you to write reasonably normal looking functions instead of having to chain together a whole bunch of functions and callbacks. your test functions need to agree to the following contract: the asynchronous function contract a function should yield false or return false when something asynchronous is going on. when the asynchronous operation is complete, something needs to call async_driver().
...And 6 more matches
NSS tools : certutil
sword to a key database. --merge merge two databases into one. --upgrade-merge upgrade an old database and merge it into a new database. this is used to migrate legacy nss databases (cert8.db and key3.db) into the newer sqlite databases (cert9.db and key4.db). arguments arguments modify a command option and are usually lower case, numbers, or symbols. -a use ascii format or allow the use of ascii format for input or output. this formatting follows rfc 1113. for certificate requests, ascii output defaults to standard output unless redirected. -b validity-time specify a time at which a certificate is required to be valid. use when checking ...
...specifying seconds (ss) is optional. when specifying an explicit time, use a z at the end of the term, yymmddhhmmssz, to close it. when specifying an offset time, use yymmddhhmmss+hhmm or yymmddhhmmss-hhmm for adding or subtracting time, respectively. ...
...it contains spaces. -d [prefix]directory specify the database directory containing the certificate and key database files. certutil supports two types of databases: the legacy security databases (cert8.db, key3.db, and secmod.db) and new sqlite databases (cert9.db, key4.db, and pkcs11.txt). nss recognizes the following prefixes: · sql: requests the newer database · dbm: requests the legacy database if no prefix is specified the default type is retrieved from nss_default_db_type. if nss_default_db_type is not set then dbm: is the default. --dump-ext-val oid for single cert, print binary der encoding of extension oid. -e ch...
...And 6 more matches
NSS tools : crlutil
for information on security module database management, see using the security module database tool. for information on certificate and key database management, see using the certificate database tool. ...
... -i import a crl to the cert database -e erase all crls of specified type from the cert database -l list existing crl located in cert database file. ...
...ficate revocation list from cert database. -i import a crl to the cert database -e erase all crls of specified type from the cert database -l list existing crl located in cert database file. -m modify existing crl which can be located in cert db or in arbitrary file. if located in file it should be encoded in asn.1 encode format. -g arguments option arguments modify an action and are lowercase. -b bypass ca signature checks. -p dbprefix specify the prefix used on the nss security database files (for example, my_cert8.db and my_key3.db). this option is provided as a special case. changing the names of the certificate and key databases is not recommended. -a use ascii format or allow the use of ascii format for input and output. this formatting follows rfc #1113. -c crl-...
...And 6 more matches
gtstd.html
oftware. netscape provides a built-in pkcs #11 module with nss. other kinds of pkcs #11 modules include the netscape fortezza module, used by the government, and the litronic pkcs #11 module for smart card readers. figure 2.1 illustrates the relationships between nspr, ssl, pkcs #11, and the available cryptographic modules. ssl is built on top of nspr, which handles sockets, threads, and related low-level os operations. on any given server or client, one or more pkcs #11 modules may be available. figure 2.1 relationships among nss libraries, cryptographic modules, slots, and tokens as shown in the figure, ssl communicates with pkcs #11 modules through the pkcs #11 interface. any pkcs #11 module that supports pkcs #11 can be used with the nss libraries. netscape software uses a file c...
...ion, you can use either the certificate database tool or the communicator security interface to create the database files and populate them with the appropriate certificates and keys. you can use communicator to set up client certificate databases by obtaining certificates from either a public ca or from a certificate server such as netscape certificate management system. ...
...icate server such as netscape certificate management system. the instructions that follow assume you are using the certificate database tool to set up both the server and client databases for testing purposes. you can use the security module database tool, a command-line utility that comes with nss, to manage pkcs #11 module information within secmod.db files. the security module database tool allows you to add and delete pkcs #11 modules, change passwords, set defaults, list module contents, enable or disable slots, enable or disable fips-140-1 compliance, and assign default providers for cryptographic operations. setting up the certificate and key databases before you can run the sample programs (server.c and client.c) that come with nss, you must set up certificate, key, and securit...
...And 6 more matches
NSS Tools crlutil
tool. for information on certificate and key database management, see using the certificate database tool. availability see the release notes for the platforms this tool is available on. ...
... option [arguments] where options and arguments are combinations of the options and arguments listed in the following section. each command takes one option. each option may take zero or more arguments. to see a usage string, issue the command without options, or with the -h option. options and arguments options specify an action and are uppercase. option arguments modify an action and are lowercase. certificate revocation list management tool command options and their arguments are defined as follows: options -g create new certificate revocation list(crl). -d delete certificate revocation list from cert database. ...
... bypass ca signature checks. -p dbprefix specify the prefix used on the nss security database files (for example, my_cert8.db and my_key3.db). this option is provided as a special case. changing the names of the certificate and key databases is not recommended. -a use ascii format or allow the use of ascii format for input and output. this formatting follows rfc #1113. -c crl-gen-file specify script file that will be used to control crl generation/modification. see crl-cript-file format below. if options -m|-g is used and -c crl-script-file is not specified, crlutil will read script data from standard input. ...
...And 6 more matches
NSS tools : crlutil
Mozilla › Projects › NSS › tools › crlutil
n on security module database management, see using the security module database tool. for information on certificate and key database management, see using the certificate database tool. ...
... -d delete certificate revocation list from cert database. -i import a crl to the cert database -e erase all crls of specified type from the cert database -l list existing crl located in cert database file. ...
...t database -e erase all crls of specified type from the cert database -l list existing crl located in cert database file. -m modify existing crl which can be located in cert db or in arbitrary file. if located in file it should be encoded in asn.1 encode format. ...
...And 6 more matches
WebReplayRoadmap
replay was an early-stage experiment and is no longer part of firefox. this document describes existing, planned, and potential features for the firefox developer tools that are based on web replay, along with their ui. the low level, yet flexible architecture (described here) provides an extremely powerful platform for implementing debugging and analysis features. we would like to use web replay to radically improve not just the debugging experience but the entire web development experience. to that end, this document will be revised over time as we find new and better ways of helping developers. time travel features more features are planned for the timeline, as described below. retroactive console logging console logging is one of the primary tools most developers use to ...
...sages 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 preference. set a breakpoint and right click on it to change it to a log point. in a non-recording tab this will update the conso...
... immediately. these messages will show up on the timeline and can be seeked to in the same way as other console messages. dom/css integration (partially implemented) when paused, the inspector panel can be used to inspect the dom and css state of the page. ...
...And 6 more matches
XForms Accessibility
rom firefox 3 (gecko 1.9). implementation of accessible objects for xforms elements is based on top of the existing object hierarchy introduced in the mozilla accessibility module. xforms elements behavior is implemented in accordance with accessible toolkit checklist. in general, when elements are similar to html elements, they are exposed to msaa/atk in a similar way. get build subsections below explain how you can obtain accessible xforms-enabled build. these are either downloading latest build of firefox or building it yourself. downloading builds notion: xforms is no longer distributed with firefox build. you must build it yourself. see section below. for firefox, you may directly download the nighly "trunk" build of firefox and install the xforms extension which lives in 'xpi' dir...
...nux testing has not yet been done, although everything should work and is ready to be tested. you will find trunk builds of firefox at ftp.mozilla.org, trunk builds of xforms extension (windows) at ftp.mozilla.org or trunk builds of xforms extension (linux) ftp.mozilla.org. build it yourself if you would like to build firefox/seamonkey yourself then please ensure your .mozconfig file has the following option: ac_add_options --enable-extensions=default,xforms,schema-validation how to test there are two approaches to test xforms accessibility. the first is to use and assistive technology such as a screen reader, or an accessibility testing tool, to make sure xforms elements have proper accessible objects. or you may be guided by toolkit checklist to check keyboard navigation for xforms ...
...--enable-extensions=default,xforms,schema-validation how to test there are two approaches to test xforms accessibility. the first is to use and assistive technology such as a screen reader, or an accessibility testing tool, to make sure xforms elements have proper accessible objects. or you may be guided by toolkit checklist to check keyboard navigation for xforms controls. ...
...And 6 more matches
Using the Places history service
r like marking pages as typed in the url bar, and removing pages as from the history interface. nsinavhistoryservice: complex query functions, more fine-grained getters and setters. nsiautocompletesearch: url-bar autocomplete from history from 1.9.1 (firefox3.1) on, don't use any places service on (or after) quit-application has been notified, since the database connection will be closed to allow the last sync, and changes will most likely be lost. use quit-application-granted instead. differences from previous implementations the previous nsglobalhistory service stored one entry for each page in history. this entry contained the url, title, visit count, last visit date, first visit date, host name, last referrer, flags for typed, hidden, and gecko flags (gecko flags is trunk only). th...
...nd typed. stored separately is the information specific to each visit. this information is called a "visit" in this document and in the code. a visit contains a reference to the url table for the page, the visit date, the transition type (typed, click, redirect, bookmark, etc.), a reference to the referring visit, and the session id. this separation of the global page information and the visit allows us to store information about each time the page was visited instead of just the last time. using the referrer information in each visit, the browsing path can be reconstructed at any time. the "session id" allows these paths to be reconstructed more easily. when the user starts browsing (for example, by typing in a link or following a bookmark), a new session id is created. new visits get the ...
...rer information in each visit, the browsing path can be reconstructed at any time. the "session id" allows these paths to be reconstructed more easily. when the user starts browsing (for example, by typing in a link or following a bookmark), a new session id is created. new visits get the same session id as their referrer. this means that one "session" is comprised of going to a new page, and following a bunch of links or redirects. a session is ended when a new url is typed in or selected from bookmarks. these session ids allow the dotted lines separating related pages in the history view to be easily computed. creating the history service the places history service's contract id is "@mozilla.org/browser/nav-history-service;1": var historyservice = components.classes["@mozilla.org/browse...
...And 6 more matches
Finishing the Component
hen they are finished they can ns_release() the service as usual. * * a user of a service may keep references to particular services * indefinitely and only must call release when it shuts down. * * @status frozen */ these frozen interfaces and functions are part of the gecko sdk. the rule of thumb is that interfaces outside of the sdk are considered "experimental" or unfrozen. see the following sidebar for information about how frozen and unfrozen interfaces can affect your component development, and for technical details about how interface changes beneath your code can cause havoc. the danger of using unfrozen interfaces suppose that you need to use the interface nsifoo that isn't frozen. you build your component using this interface, and it works great with the version of gecko...
...ce was never supposed to be used by clients other than gecko or mozilla, the maintainers of the interface don't know that it's being used, and don't change the iid of the interface. when your component runs in a version of gecko in which this interface is updated, your method calls will be routed through a different v-table than the one the component expected, most likely resulting in a crash. below, the component is compiled against a version of the nsifoo interface that has three methods. the component calls the method testa and passes an integer, 10. this works fine in any gecko installation where a contract guarantees that the interface that was compiled against has the same signature. however, when this same component is used in a gecko installation where this interface has changed, the...
...weblock class to implement the nsicontentpolicy interface. the weblock class will then support four interfaces: nsisupports, nsiobserver, nsicontentpolicy, and iweblock. weblock interfaces interface name defined by status summary nsisupports xpcom frozen provides interface discovery, and object reference counting nsiobserver xpcom frozen allows messaging passing between objects nsicontentpolicy content not frozen interface for policy control mechanism iweblock web lock not frozen enables and disables weblock. also, provides access to the url that are whitelisted. implementing the nsicontentpolicy interface to implement the new interface, you must #include the unfrozen nsicontentpolicy, and yo...
...And 6 more matches
nsIHttpChannel
netwerk/protocol/http/nsihttpchannel.idlscriptable this interface allows for the modification of http request parameters and the inspection of the resulting http response status and headers when they become available. inherits from: nsichannel last changed in gecko 1.3 to create an http channel, use nsiioservice with a http uri, for example: var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var ch = ios.newchannel("https://www.example.com/", null, null); method overview void getoriginalresponseheader(in acstring aheader, in nsihttpheadervisitor avisitor); acstring getrequestheader(in acstring aheader); acstring getresponseheader(in acstring header); bo...
...this should be set to false, for example, if the application knows that the corresponding document is likely to be very large. this attribute is true by default, though other factors may prevent pipelining. ...
... default; only send the origin of the referring uri for cross-origin requests referrer_policy_unsafe_url always send the referrer, even when downgrading from https to http attributes attribute type description allowpipelining boolean this attribute is a hint to the channel to indicate whether or not the underlying http transaction should be allowed to be pipelined with other transactions. this should be set to false, for example, if the application knows that the corresponding document is likely to be very large. this attribute is true by default, though other factors may prevent pipelining. this attribute may only be set before the channel is opened. exceptions thrown ns_error_failure if set after the channe...
...And 6 more matches
nsIParserUtils
note: if -moz-binding is absent, properties that might be xss risks in other web engines are preserved! sanitizercidembedsonly (1 << 2) flag fo...
...nsigned long flags, in unsigned long wrapcol); nsidomdocumentfragment parsefragment(in astring fragment, in unsigned long flags, in boolean isxml, in nsiuri baseuri, in nsidomelement element); astring sanitize(in astring src, in unsigned long flags); constants constant value description sanitizerallowcomments (1 << 0) flag for sanitizer: allow comment nodes. ...
...pcol); nsidomdocumentfragment parsefragment(in astring fragment, in unsigned long flags, in boolean isxml, in nsiuri baseuri, in nsidomelement element); astring sanitize(in astring src, in unsigned long flags); constants constant value description sanitizerallowcomments (1 << 0) flag for sanitizer: allow comment nodes. sanitizerallowstyle (1 << 1) flag for sanitizer: allow <style> elements and style attributes (with contents sanitized in case of -moz-binding). note: if -moz-binding is absent, properties that might be xss risks in other web engines are preserved! sanitizercidembedsonly (1 << 2) flag for sanitizer: only allow cid: urls for embedded content. at present, sanitizing css ba...
...And 6 more matches
wrappedJSObject
f this article demonstrates what xpconnect wrappers do and how wrappedjsobject can be used to bypass them. example component to see how the wrappedjsobject property works, we need an example xpcom component implemented in js. see how to build an xpcom component in javascript for details on creating one. for simplicity we omit the component registration code. ...
... can be used to bypass them. example component to see how the wrappedjsobject property works, we need an example xpcom component implemented in js. see how to build an xpcom component in javascript for details on creating one. for simplicity we omit the component registration code. suppose we register the component below with the @myself.com/my-component;1 contract. // constructor function helloworld() { }; helloworld.prototype = { hello: function() { return "hello world!"; }, queryinterface: function(aiid) { if (!aiid.equals(components.interfaces.nsisupports) && !aiid.equals(components.interfaces.nsihelloworld)) throw components.results.ns_error_no_interface; return this; } }; xpconnect wrapping now let's get a reference to our component. in this ...
...this also makes the public interface of the component clearer and provides protection for the component's internal data. calling queryinterface on the wrap...
...And 6 more matches
Working with ArrayBuffers
section of the type conversion page explains the fundamentals of this operation. the second code example provides a specific illustration of the operation. an arraybuffer is a simply byte array. the js-ctypes equivalent is a ctypes.uint8_t.array(###) (ctypes.unsigned_char are also ctypes.uint8_t). bug 732936 includes a discussion of working with an arraybuffer. this feature is based on the following work: //github.com/realityripple/uxp/blob/master/js/src/ctypes/ctypes.cpp#3080 //github.com/realityripple/uxp/blob/master/js/src/vm/arraybufferobject.cpp#1301 example 1 - image data the following example illustrates how to transfer a byte array pointed by ctypes.uint8_t.ptr to imagedata of canvas. this example is based on the fact that the imagedata returned from canvasrenderingcontext2d.g...
...ctypes.cpp#3080 //github.com/realityripple/uxp/blob/master/js/src/vm/arraybufferobject.cpp#1301 example 1 - image data the following example illustrates how to transfer a byte array pointed by ctypes.uint8_t.ptr to imagedata of canvas. this example is based on the fact that the imagedata returned from canvasrenderingcontext2d.getimagedata is a uint8clampedarray view for an arraybuffer. ...
... 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.uint64("0x352e0000"))" var imgwidth = 400; var imgheight = 400; var myimgdat = new imagedata(imgwidth, imgheight); method 1: passing arraytype cdata to uint8clampedarray.prototype.set one method is to get into a js-ctypes array, and then set it into the imagedata, as...
...And 6 more matches
Working with data
(value); if the size of the specified type isn't undefined, the specified value is converted to the given type. if the conversion isn't possible, typeerror is thrown. the resulting data is then copied into a new cdata object. if the original value is already a cdata object, the original object is simply duplicated directly into the new one. ...
... 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. ...
...script number objects, 64-bit integers cannot all be represented accurately by this type. for that reason, 64-bit and pointer-sized c values of numeric types don't get automatically converted to javascript numbers. instead, they're converted to javascript objects that you can manipulate using the methods provided by the int64 and uint64 objects. note: these 64-bit integer types are intentionally low on features, so that when javascript adds a "big number" type, we can easily upgrade to support that properly. creating 64-bit integer objects to create a new 64-bit number object, use the ctypes.int64.int64() method to create a new 64-bit signed integer, or the ctypes.uint64.uint64() method to create a new unsigned 64-bit integer. for example: var num1 = ctypes.uint64(5000); var num2 = ctypes...
...And 6 more matches
AbstractRange - Web APIs
ou will not directly instantiate an object of type abstractrange. instead, you will use the range or staticrange interfaces. to understand the difference between those two interfaces, and how to choose which is appropriate for your needs. ...
...offers no methods. usage notes range types all ranges of content within a document are described using instances of interfaces based on abstractrange. there are two such interfaces: range the range interface has been around for a long time and has only recently been redefined to be based upon abstractrange as the need arose to define other forms of range data. range provides methods that allow you to alter the range's endpoints, as well as methods to compare ranges, detect intersections beween ranges, and so forth. staticrange 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 a...
...e start and end positions will generally be easier to make perform well. rather than having to negotiate the dom figuring out what your global offset refers to, the user agent (browser) can instead go directly to the node indicated by the starting position and start from there, working its way forward until it reaches the given offset into the ending node. ...
...And 6 more matches
Background Tasks API - Web APIs
good citizen of the web and help to prevent stalls in the execution of the event loop. in the past, there's been no way to do this reliably other than by writing code that's as efficient as possible and by offloading as much work as possible to workers. window.requestidlecallback() makes it possible to become actively engaged in helping to ensure that the browser's event loop runs smoothly, by allowing the browser to tell your code how much time it can safely use without causing the system to lag. if you stay within the limit given, you can make the user's experience much better. getting the most out of idle callbacks because idle callbacks are intended to give your code a way to cooperate with the event loop to ensure that the system is utilized to its full potential without over-tasking ...
...table amount of time. for example, anything which might affect layout should be avoided. you should also avoid resolving or rejecting promises, since that would invoke the handler for that promise's resolution or rejection as soon as your callback returns. use timeouts when you need to, but only when you need to. using timeouts can ensure that your code runs in a timely manner, but it can also allow you to cause lag or animation stutters by mandating that the browser call you when there's not enough time left for you to run without disrupting performance. falling back to settimeout because the background tasks api is fairly new, your code may need to be able to work on browsers that don't yet support it. you can do so with a simple shim that uses settimeout() as a fallback option. this is...
...ck 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 we're ...
...And 6 more matches
Drawing shapes with canvas - Web APIs
filled rectangle. strokerect(x, y, width, height) draws a rectangular outline. clearrect(x, y, width, height) clears the specified rectangular area, making it fully transparent. each of these three functions takes the same parameters. x and y specify the position on the canvas (relative to the origin) of the top-left corner of the rectangle. width and height provide the rectangle's size. below is the draw() function from the previous page, but now it is making use of these three functions. rectangular shape example <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> function draw() { var canvas = document.getelementbyid('canvas'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); ctx.fillrect(25, 25, 10...
...ample <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> function draw() { var canvas = document.getelementbyid('canvas'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); ctx.fillrect(25, 25, 100, 100); 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 st...
...ifting a pen or pencil from one spot on a piece of paper and placing it on the next. moveto(x, y) moves the pen to the coordinates specified by x and y. when the canvas is initialized or beginpath() is called, you typically will want to use the moveto() function to place the starting point somewhere else. we could also use moveto() to draw unconnected paths. take a look at the smiley face below. to try this for yourself, you can use the code snippet below. just paste it into the draw() function we saw earlier. <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> function draw() { var canvas = document.getelementbyid('canvas'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc...
...And 6 more matches
Introduction to the DOM - Web APIs
which can be modified with a scripting language such as javascript. the w3c dom and whatwg dom standards are implemented in most modern browsers. many browsers extend the standard, so care must be exercised when using them on the web where documents may be accessed by various browsers with different doms. for example, the standard dom specifies that the getelementsbytagname method in the code below must return a list of all the <p> elements in the document: const paragraphs = document.getelementsbytagname("p"); // paragraphs[0] is the first <p> element // paragraphs[1] is the second <p> element, etc. alert(paragraphs[0].nodename); all of the properties, methods, and events available for manipulating and creating web pages are organized into objects (for example, the document object that ...
...when you create a script–whether it's inline in a <script> element or included in the web page by means of a script loading instruction–you can immediately begin using the api for the document or window elements to manipulate the document itself or to get at the children of that document, which are the various elements in the web page. ...
...r window elements to manipulate the document itself or to get at the children of that document, which are the various elements in the web page. your dom programming may be something as simple as the following, which displays an alert message by using the alert() function from the window object, or it may use more sophisticated dom methods to actually create new content, as in the longer example below. this following javascript will display an alert when the document is loaded (and when the whole dom is available for use): <body onload="window.alert('welcome to my home page!');"> another example. this function creates a new h1 element, adds text to that element, and then adds the h1 to the tree for this document: <html> <head> <script> // run this function when the document i...
...And 6 more matches
FileSystemEntrySync - Web APIs
true if the filesystementrysync is a file. name readonly domstring the name of the entry, excluding the path leading to it. methods getmetadata() look up metadata about this entry. [ todo: specify what kind of metadata ] metadata getmetada () raises (fileexception); parameter none returns metadata exceptions this method can raise a fileexception with the following codes: exception description not_found_err the entry does not exist. invalid_state_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...
... 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 a directory that is not empty. filesystementrysync moveto ( in directoryentrysync parent, optional domstr...
...ysync parent, optional domstring newname ) raises (fileexception); parameters parent the directory to which to move the entry. newname the new name of the entry. if you do not specify a name, the browser preserves the entry's current name. returns filesystementrysync an object that represents an entry in the file system. ...
...And 6 more matches
IDBObjectStoreSync - Web APIs
vide a key for each modification operation. mode readonly unsigned short the mode for isolating access to the data in this object store. for possible values, see constants. name readonly domstring the name of this object store. constants mode constants constant value description read_only 1 modification operations are not allowed on this object store. read_write 0 modification operations are allowed on this object store. snapshot_read 2 any read operations must access a snapshot view of the data, which cannot change once it is created. methods add() stores the given value into this object store, optionally with the specified key. if a record already exists with the given key, an ex...
... the data, which cannot change once it is created. methods add() stores the given value into this object store, optionally with the specified key. if a record already exists with the given key, an exception is raised. any add( in any value, in optional any key ) raises (idbdatabaseexception); parameters returns exceptions this method can raise a idbdatabaseexception with the following codes: value the value to store into the index. key a key to use for identifying the record. any the key for the stored record. constraint_err if a record exists in this index with a key corresponding to the key parameter or the index is auto-populated, or if no record exists with a key corresponding to the value parameter in the index's referenced object store. data_err if this ob...
...ing algorithm. createindex() creates and returns a new index with the given name in the connected database. idbindexsync createindex ( in domstring name, in domstring keypath, in optional boolean unique ); parameters name the name of a new index. keypath the key path used by the new index. unique if true, keys in the index must be unique; if false, duplicate keys are allowed. returns idbindexsync an object to access the newly created index. get() retrieves and returns the value from this object store for the record that corresponds to the given key. any get ( in any key ) raises (idbdatabaseexception); parameters key the key that identifies the record to be retrieved. returns any the value retrieved from the object store. exceptions this ...
...And 6 more matches
Basic concepts - Web APIs
tions 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 main indexeddb api article and its subpages, which document the types of objects used by indexeddb. ...
...ment the types of objects used by indexeddb. for more information on how the browser handles storing your data in the background, read browser storage limits and eviction criteria. overview of indexeddb indexeddb lets you store and retrieve objects that are indexed with a "key." all changes that you make to the database happen within transactions. like most web storage solutions, indexeddb follows a same-origin policy. so while you can access stored data within a domain, you cannot access data across different domains. indexeddb is an asynchronous api that can be used in most contexts, including web workers. it used to include a synchronous version also, for use in web workers, but this was removed from the spec due to lack of interest by the web community. indexeddb used to have a comp...
...he w3c deprecated it on november 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 indexed...
...And 6 more matches
Intersection Observer API - Web APIs
er is free to optimize the management of intersections as it sees fit. ...
... let observer = new intersectionobserver(callback, options); a threshold of 1.0 means that when 100% of the target is visible within the element specified by the root option, the callback is invoked. intersection observer options the options object passed into the intersectionobserver() constructor let you control the circumstances under which the observer's callback is invoked. it has the following fields: root the element that is used as the viewport for checking visibility of the target. must be the ancestor of the target. defaults to the browser viewport if not specified or if null. rootmargin margin around the root. can have values similar to the css margin property, e.g. "10px 20px 30px 40px" (top, right, bottom, left). the values can be percentages. this set of values serves ...
... 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 getboundingclientrect() on it). the root intersection rectangle can be adjusted further by setting the root margin, rootmargin, when creating the intersectionobserver. the values in rootmargin define of...
...And 6 more matches
Using the MediaStream Recording API - Web APIs
sy way to record from the user's input devices and instantly use the result in web apps. both audio and video may be recorded, separately or together. this article aims to provide a basic guide on how to use the mediarecorder interface, which provides this api. a sample application: web dictaphone to demonstrate basic usage of the mediarecorder api, we have built a web-based dictaphone. it allows you to record snippets of audio and then play them back. it even gives you a visualization of your device's sound input, using the web audio api. we'll concentrate on the recording and playback functionality for this article. you can see this demo running live, or grab the source code on github. css goodies the html is pretty simple in this app, so we won't go through it here; there are a cou...
...your device's sound input, using the web audio api. we'll concentrate on the recording and playback functionality for this article. you can see this demo running live, or grab the source code on github. css goodies the html is pretty simple in this app, so we won't go through it here; there are a couple of slightly more interesting bits of css worth mentioning, however, so we'll discuss them below. if you are not interested in css and want to get straight to the javascript, skip to 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 ...
...straight to the javascript, skip to 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...
...And 6 more matches
Using the Notifications API - Web APIs
...
... 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). ...
... checking current permission status you can check to see if you already have permission by checking the value of the notification.permission read only property. ...
...And 6 more matches
Pointer events - Web APIs
active because it can produce additional events when the pen is lifted 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...
...nter 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 capture pointer capture allows the events for a pointer to be retargeted to a particular element other than the normal hit test result of the pointer's location. pointer event a dom event fired for a pointer. interfaces the primary interface is the pointerevent interface which has a constructor plus several event types and associated global event handlers. the standard also includes some extensions to the element and na...
...o be retargeted to a particular element other than the normal hit test result of the pointer's location. pointer event a dom event fired for a pointer. interfaces the primary interface is the pointerevent interface which has a constructor plus several event types and associated global event handlers. the standard also includes some extensions to the element and navigator interfaces. the following sub-sections contain short descriptions of each interface and property. pointerevent interface the pointerevent interface extends the mouseevent interface and has the following properties. (all of the following properties 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...
...And 6 more matches
SVGTransformList - Web APIs
numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgtransform newitem) svgtransform clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before...
...rent items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgtransform returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: ...
...o a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgtransform returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in svgtransform newitem, in unsigned long index) svgtransform inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list before it is inserted into...
...And 6 more matches
Using the Screen Capture API - Web APIs
ync function startcapture(displaymediaoptions) { let capturestream = null; try { capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { console.error("error: " + err); } return capturestream; } you can write this code either using an asynchronous function and the await operator, as shown above, or using the promise directly, as seen below. starting screen capture: promise style function startcapture(displaymediaoptions) { let capturestream = null; return navigator.mediadevices.getdisplaymedia(displaymediaoptions) .catch(err => { console.error("error:" + err); return null; }); } either way, the user agent responds by presenting a user interface that prompts the user to choose the screen area to share. both of these imple...
...navigator.mediadevices.getdisplaymedia(displaymediaoptions) .catch(err => { console.error("error:" + err); return null; }); } either way, the user agent responds by presenting a user interface that prompts the user to choose the screen area to share. both of these implementations of startcapture() return the mediastream containing the captured display imagery. see options and constraints, below, for more on both how to specify the type of surface you want as well as other ways to adjust the resulting stream. example of a window allowing the user to select a display surface to capture you can then use the captured stream, capturestream, for anything that accepts a stream as input. the examples below show a few ways to make use of the stream. visible vs logical display surfaces fo...
...fscreen. how these are handled by the screen capture api varies. generally, the browser will provide an image which obscures the hidden portion of the logical display surface in some way, such as by blurring or replacing with a color or pattern. this is done for security reasons, as the content that cannot be seen by the user may contain data which they do not want to share. a user agent might allow the capture of the entire content of an obscured window after gaining permission from the user to do so. in this case, the user agent may include the obscured content, either by getting the current contents of the hidden portion of the window or by presenting the most-recently-visible contents if the current contents are not available. options and constraints the constraints object passed into ...
...And 6 more matches
Geometry and reference spaces in WebXR - Web APIs
es. the most efficient way, of course, is to design your objects and code to use the same coordinate system as webgl does. the webgl coordinates and lengths are transformed automatically at render time to the size of the viewport in which the scene is being rendered. angles angles are specified using radians. to convert degrees to radians, simply multiply the value in degrees by π/180. the following code snippet shows two simple functions, degreestoradians() and radianstodegrees(), which convert back and forth between the two units for measuring angles. const radians_per_degree = math.pi / 180.0; let degreestoradians = (deg) => deg * radians_per_degree; let radianstodegrees = (rad) => rad / radians_per_degree; times and durations note that for security reasons, domhighrestimestamp us...
... axes meet. this is the native origin of the space, corresponding to a specific physical location in the user's environment. each space has its own native origin, which is tracked by the xr device's tracking system. this may be different from the effective origin, which is the origin point for the space's local coordinate system. the directionality of the coordinate system can be seen in the following diagram: an xrrigidtransform called the origin offset is used to transform points from the space's own effective coordinate system to the xr device's native coordinate system. the origin offset is initially simply an identity transform, since typically the two origins are aligned when the space is first established. however, as changes in alignment accumulate over time the origin offset may...
...om left to right away from the origin, with the x coordinate of +1.0 being located at the right edge of the world. negative values of x extend toward the left from the origin, reaching a value of -1.0 at the left edge of the space. the y-axis is positive extending upward from the origin toward the top of the screen, reaching +1.0 at the top of the world space. values of y less than 0 are found below the origin, extending toward the bottom of the screen and reaching -1.0 at the bottom of the world's space. the z-axis extends from the origin outward from the screen, reaching +1.0 at the closest point to the user in that direction. negative values of z extend away from the user further into the screen, with the farthest away point in the world having a z of -1.0. every object is, at the simp...
...And 6 more matches
Rendering and the WebXR frame animation callback - Web APIs
ender the scene—as it should appear at the specified time—into the webgl backbuffer. when 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 me...
...alled up to 60 times per second, and your goal is to do what you can to ensure that it doesn't get called less often than that. you achieve this by doing as much as is practicable off the main thread and by keeping your frame rendering callback as efficient as possible. the division of time into 60 hz blocks with each block being used at least in part to render the scene is shown in the diagram below. this is important because as the computer becomes increasingly busy, it may not be able to accurately call your callback every frame and may have to skip frames. this is called dropping frames. this happens when the amount of time it takes to render a frame exceeds the time available between frames, whether because rendering was delayed or because rendering itself took more time than was avai...
...s of the affected display area simply don't change for that pass through the frame loop. for that reason, the occasional dropped frame isn't usually particularly noticeable, but if it starts to happen a lot—especially if several frames are dropped in a very short span of time—it can become jarring or even leave your display unusable. fortunately, you can easily compute how much time you're allowed to use between frames as 1/refreshrate seconds. that is, by dividing 1 by the display's refresh rate. the resulting value is the amount of time available for each frame to be rendered in order to not drop the frame. for example, a 60 hz display has 1/60th of a second to render a single frame, or 0.0166667 seconds. and if the device's refresh rate is 120 hz, you only have 0.00883333 seconds to r...
...And 6 more matches
Operable - Accessibility
.1.3 keyboard — all functionality (aaa) this is a further step beyond criterion 2.1.1. to achieve aaa conformance, all functionality should be accessible using keyboard controls — with no exceptions. see ui controls and building keyboard accessibility back in 2.1.4 character key shortcuts (a) added in 2.1 if a single character key shortcut exists, then at least one of the following is true: single character key shortcuts can be turned off, remapped or are only active when the relevant user interface component is in focus. understanding character key shortcuts note: also see the wcag description for guideline 2.1 keyboard accessible: make all functionality available from a keyboard. guideline 2.2 — enough time: provide users enough time to read and use cont...
...ity 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 and would be invalidated if it were turned off. 2.2.2 pausing, stopping, hiding (a) for moving/blinking content that starts automatically, lasts lo...
...lert. 2.2.5 re-authenticating (aaa) if an authentication session expires during usage of a web app, the user can re-authenticate and continue their usage without losing any data. 2.2.6 timeouts (aaa) added in 2.1 if there is a timeout (caused by user inactivity) warn users at the start of a process so they will not be surprised that a timeout exists (or only allow the timeout to occur after 20 hours of inactivity. understanding timeouts note: also see the wcag description for guideline 2.2 enough time: provide users enough time to read and use content. guideline 2.3 — seizures and physical reactions: do not design content in a way that is known to cause seizures or physical reactions this refers to content that, if not changed, could c...
...And 6 more matches
Text labels and names - Accessibility
use alt attribute to label area elements that have the href attribute in image maps, give each <area> element an alt attribute containing a name that describes what resources the areas links to. ...
...og, or other website feature should be given a descriptive name or label to allow users of assistive technologies to understand what its purpose is and to be able to understand and operate it correctly. there are a number of different types of problems in this category, found in different contexts, and each has its own solution. the different problems and solutions are discussed in the sections below. use alt attribute to label area elements that have the href attribute in image maps, give each <area> element an alt attribute containing a name that describes what resources the areas links to. ...
...n the sections below. use alt attribute to label area elements that have the href attribute in image maps, give each <area> element an alt attribute containing a name that describes what resources the areas links to. failure to do so makes an image map hard to use for users of assistive technology — they need alternative text to be able to understand the purpose of an image. examples the following example show a simple image map (taken from h24: providing text alternatives for the area elements of image maps): <img src="welcome.gif" usemap="#map1" alt="areas in the library. select an area for more information on that area." /> <map id="map1" name="map1"> <area shape="rect" coords="0,0,30,30" href="reference.html" alt="reference" /> <area shape="rect" coords="34,34,100,100" ...
...And 6 more matches
Box-shadow generator - CSS: Cascading Style Sheets
roup:before, .group:after { content: ""; display: table; } .group:after { clear:both; } .group { zoom: 1; /* for ie 6/7 (trigger haslayout) */ } /* grid column setup * ========================================================================== */ .col { display: block; float:left; margin: 1% 0 1% 1.6%; } .col:first-child { margin-left: 0; } /* all browsers except ie6 and lower */ /* * ui slider */ .slidergroup { height: 20px; margin: 10px 0; font-family: "segoe ui", arial, helvetica, sans-serif; -moz-user-select: none; user-select: none; } .slidergroup * { float: left; height: 100%; line-height: 100%; } /* slider */ .ui-slider { height: 10px; width: 200px; margin: 4px 10px; display: block; border: 1px solid #999; border-radius: 3px; background: ...
...r-select: none; user-select: none; } .slidergroup * { float: left; height: 100%; line-height: 100%; } /* slider */ .ui-slider { height: 10px; width: 200px; margin: 4px 10px; display: block; border: 1px solid #999; border-radius: 3px; background: #eee; } .ui-slider:hover { cursor: pointer; } .ui-slider-name { width: 90px; padding: 0 10px 0 0; text-align: right; text-transform: lowercase; } .ui-slider-pointer { width: 13px; height: 13px; background-color: #eee; border: 1px solid #2c9fc9; border-radius: 3px; position: relative; top: -3px; left: 0%; } .ui-slider-btn-set { width: 25px; background-color: #2c9fc9; border-radius: 3px; color: #fff; font-weight: bold; text-align: center; } .ui-slider-btn-set:hover { background-color: #379b4a; cursor: pointer; } ...
...tica, sans-serif; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; } #container { width: 100%; padding: 2px; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } /* container with shadows stacks */ #stack_container { height: 400px; overflow: hidden; position: relative; border: 1px solid #ccc; border-radius: 3px; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } #stack_container .container { height: 100%; width: 100%; position: absolute; left: 100%; transition-property: left; transition-duration: 0.5s; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: borde...
...And 6 more matches
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
g new rows if flex-direction is row and new columns if flex-direction is column. in this guide i will explain how this works, what it is designed for and what situations really require css grid layout rather than flexbox. making things wrap the initial value of the flex-wrap property is nowrap. this means that if you have a set of flex items that are too wide for their container, they will overflow it. if you want to cause them to wrap once they become too wide you must add the flex-wrap property with a value of wrap, or use the shorthand flex-flow with values of row wrap or column wrap. items will then wrap in the container. in the next example i have ten items all with a flex-basis of 160px and the ability to grow and shrink. once the first row gets to a point where there is not enough s...
...ner 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. ...
...les 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 deals with space distribution across the main axis. if there is only one item, and that item is allowed to grow, it will fill the axis just as if you had a single item flex container. if you want layout in two dimensions then you probably want grid layout. we can compare our wrapped row example above with the css grid version of that layout to see the difference. ...
...And 6 more matches
Basic Concepts of grid layout - CSS: Cascading Style Sheets
ayout and the new terminology that is part of the css grid layout level 1 specification. 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. css grid layout has the following features: fixed and flexible track sizes you can create a grid with fixed track sizes – using pixels for example. this sets the grid to the specified pixel which fits to the layout you desire. you can also create a grid using flexible sizes with percentages or with the new fr unit designed for this purpose. item placement you can place items into a precise location on the grid using line...
...h the css grid layout this tool will give you a better idea of what is happening with your grids visually. if we want to start making this more grid-like we need to add column tracks. grid tracks we define rows and columns on our grid with the grid-template-columns and grid-template-rows properties. these define grid tracks. a grid track is the space between any two lines on the grid. in the below image you can see a track highlighted – this is the first row track in our grid. i can add to our earlier example by adding the grid-template-columns property, then defining the size of the column tracks. i have now created a grid with three 200-pixel-wide column tracks. the child items will be laid out on this grid one in each grid cell. <div class="wrapper"> <div>one</div> <div>two<...
...is next example i have created a grid with an initial 20-pixel track, then a repeating section of 6 1fr tracks then a final 20-pixel track. .wrapper { display: grid; grid-template-columns: 20px repeat(6, 1fr) 20px; } repeat notation takes the track listing, and uses it to create a repeating pattern of tracks. in this next example, my grid will consist of 10 tracks, a 1fr track, and then followed by a 2fr track. this pattern will be repeated five times. .wrapper { display: grid; grid-template-columns: repeat(5, 1fr 2fr); } the implicit and explicit grid when creating our example grid we specifically defined our column tracks with the grid-template-columns property, but the grid also created rows on its own. these rows are part of the implicit grid. whereas the explicit grid cons...
...And 6 more matches
WebKit CSS extensions - CSS: Cascading Style Sheets
d properties on the standards track -webkit-appearance -webkit-font-size-delta -webkit-mask-composite -webkit-mask-position-x -webkit-mask-position-y -webkit-mask-repeat-x -webkit-mask-repeat-y formerly proprietary properties that are now standard note: to maximize the compatibility of your css, you should use the unprefixed standard properties instead of the prefixed ones listed below. a -webkit-align-content -webkit-align-items -webkit-align-self -webkit-animation -webkit-animation-delay -webkit-animation-direction -webkit-animation-duration -webkit-animation-fill-mode -webkit-animation-iteration-count -webkit-animation-name -webkit-animation-play-state -webkit-animation-timing-function b -webkit-backface-visibility -webkit-background-clip -webkit-back...
...coration-break -webkit-box-shadow -webkit-box-sizing c -webkit-clip-path -webkit-column-count -webkit-column-fill -webkit-column-gap -webkit-column-rule -webkit-column-rule-color -webkit-column-rule-style -webkit-column-rule-width -webkit-column-span -webkit-column-width -webkit-columns f -webkit-filter -webkit-flex -webkit-flex-basis -webkit-flex-direction -webkit-flex-flow -webkit-flex-grow -webkit-flex-shrink -webkit-flex-wrap -webkit-font-feature-settings -webkit-font-kerning -webkit-font-variant-ligatures g-j -webkit-grid -webkit-grid-area -webkit-grid-auto-columns -webkit-grid-auto-flow -webkit-grid-auto-rows -webkit-grid-column -webkit-grid-column-end -webkit-grid-column-gap -webkit-grid-column-start -webkit-grid-gap -webkit-grid-row -web...
...many of these are supported with no prefix as well: see f...
...And 6 more matches
conic-gradient() - CSS: Cascading Style Sheets
preceded by the from keyterm, and taking an angle as its value, defines the gradient rotation in clockwise direction. <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). <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...
...is). <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 color stops. note: rendering of color stops in css gradients follows the same rules as color stops in svg gradients. description as with any gradient, a conic gradient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. its concrete size will match the size of the element it applies to, or size of the <image> is set to something other than the element size. to create a conic gradient that repeats so as to fill a ...
...lor 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 position can be explicitly defined by using an <angle>. ...
...And 6 more matches
font-weight - CSS: Cascading Style Sheets
lighter; font-weight: bolder; /* numeric keyword values */ font-weight: 100; font-weight: 200; font-weight: 300; font-weight: 400;// normal font-weight: 500; font-weight: 600; font-weight: 700;// bold font-weight: 800; font-weight: 900; /* global values */ font-weight: inherit; font-weight: initial; font-weight: unset; the font-weight property is specified using any one of the values listed below. values normal normal font weight. same as 400. bold bold font weight. same as 700. lighter one relative font weight lighter than the parent element. note that only four font weights are considered for relative weight calculation; see the meaning of relative weights section below. bolder one relative font weight heavier than the parent element. note that only four font weights are cons...
... 700. lighter one relative font weight lighter than the parent element. note that only four font weights are considered for relative weight calculation; see the meaning of relative weights section below. bolder one relative font weight heavier than the parent element. note that only four font weights are considered for relative weight calculation; see the meaning of relative weights section below. <number> a <number> value between 1 and 1000, inclusive. higher numbers represent weights that are bolder than (or as bold as) lower numbers. certain commonly used values correspond to common weight names, as described in the common weight name mapping section below. in earlier versions of the font-weight specification, the property accepts only keyword values and the numeric values 100, 200...
... values, although fine-grained 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 ...
...And 6 more matches
grid - CSS: Cascading Style Sheets
Web › CSS › grid
https://github.com/mdn/interactive-examples and send us a pull request. note: you can only specify the explicit or the implicit grid properties in a single grid declaration. the sub-properties you don’t specify are set to their initial value, as normal for shorthands. also, the gutter properties are not reset by this shorthand. ...
...a pull request. note: you can only specify the explicit or the implicit grid properties in a single grid declaration. the sub-properties you don’t specify are set to their initial value, as normal for shorthands. also, the gutter properties are not reset by this shorthand. ...
... grid-auto-rows grid-template-areas grid-template-columns grid-template-rows syntax /* <'grid-template'> values */ grid: none; grid: "a" 100px "b" 1fr; grid: [linename1] "a" 100px [linename2]; grid: "a" 200px "b" min-content; grid: "a" minmax(100px, max-content) "b" 20%; grid: 100px / 200px; grid: minmax(400px, min-content) / repeat(auto-fill, 50px); /* <'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>? values */ grid: 200px / auto-flow; grid: 30% / auto-flow dense; grid: repeat(3, [line1 line2 line3] 200px) / auto-flow 300px; grid: [line1] minmax(20em, max-content) / auto-flow dense 40%; /* [ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'> values */ grid: auto-flow / 200px; grid: auto-flow dense / 30%; grid: auto-flow 300px / repeat(3...
...And 6 more matches
resize - CSS: Cascading Style Sheets
Web › CSS › resize
te to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax /* keyword values */ resize: none; resize: both; resize: horizontal; resize: vertical; resize: block; resize: inline; /* global values */ resize: inherit; resize: initial; resize: unset; the resize property is specified as a single keyword value from the list below. ...
... /* keyword values */ resize: none; resize: both; resize: horizontal; resize: vertical; resize: block; resize: inline; /* global values */ resize: inherit; resize: initial; resize: unset; the resize property is specified as a single keyword value from the list below. values none the element offers no user-controllable method for resizing it. both the element displays a mechanism for allowing the user to resize it, which may be resized both horizontally and vertically. ...
... */ resize: inherit; resize: initial; resize: unset; the resize property is specified as a single keyword value from the list below. values none the element offers no user-controllable method for resizing it. both the element displays a mechanism for allowing the user to resize it, which may be resized both horizontally and vertically. horizontal the element displays a mechanism for allowing the user to resize it in the horizontal direction. vertical the element displays a mechanism for allowing the user to resize it in the vertical direction. block the element displays a mechanism for allowing the user to resize it in the block direction (either horizontally or vertically, depending on the writing-mode and direction value). inline the element displays a mechanism for al...
...And 6 more matches
Audio and video manipulation - Developer guides
iquadfilternode, for example. ...
..."anonymous"> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type="video/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <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"> filter.type = "lowshelf"; filter.frequency.value = 1000; filter.gain.value = 25;</textarea> var context = new audiocontext(), audiosource = context.createmediaelementsource(document.getelementbyid("my-video")), filter = context.createbiquadfilter(); audiosource.connect(filter); filter.connect(context.destination); var textarea = document.getelementbyid('code'); var reset = document.getelementbyid...
... code; setfilter(); }); edit.addeventlistener('click', function() { textarea.focus(); }) textarea.addeventlistener('input', setfilter); window.addeventlistener('load', setfilter); note: unless you have cors enabled, to avoid security issues your video should be on the same domain as your code. ...
...And 6 more matches
<input type="range"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › range
the string representation of the selected numeric value; use valueasnumber to get the value as a number. events change and input supported common attributes autocomplete, list, max, min, and step idl attributes list, value, and valueasnumber methods stepdown() and stepup() validation there is no pattern validation available; however, the following forms of automatic validation are performed: if the value is set to something which can't be converted into a valid floating-point number, validation fails because the input is suffering from a bad input. 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 a...
...s 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. ...
...eelem.min) ? ...
...And 6 more matches
<input type="tel"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › tel
end, 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 (""). ...
...pecified around the pattern text. if the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. tip: use the title attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. you should also include other explanatory text nearby. see pattern validation below for details and an example. placeholder the placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. it should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. the text must not include carriage returns or line feeds. if the control's content has one directionality...
...ut may be narrower or wider than the specified number of characters, depending on the characters and the font (font settings in use). this does not set a limit on how many characters the user can enter into the field. it only specifies approximately how many can be seen at a time. to set an upper limit on the length of the input data, use the maxlength attribute. non-standard attributes the following non-standard attributes are available to telephone number input fields. as a general rule, you should avoid using them unless it can't be helped. attribute description autocorrect whether or not to allow autocorrect while editing this input field. safari only. mozactionhint a string indicating the type of action that will be taken when the user presses ...
...And 6 more matches
<input type="time"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › time
alue; }, false); when a form including a time input is submitted, the value is encoded before being included in the form's data. the form's data entry for a time input will always be in the form name=hh%3amm, or name=hh%3amm%3ass if seconds are included (see using the step attribute). ...
...alue can, however, still be changed by javascript code directly 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 a...
...e, so that safari users (and users of other non-supporting browsers) can still easily enter time values. we'll look at basic and more complex uses of <input type="time">, then offer advice on mitigating the browser support issue later on (see handling browser support). basic uses of time the simplest use of <input type="time"> involves a basic <input> and <label> element combination, as seen below: <form> <label for="appt-time">choose an appointment time: </label> <input id="appt-time" type="time" name="appt-time"> </form> controlling input size <input type="time"> doesn't support form sizing attributes such as size, since times are always about the same number of characters long. you'll have to resort to css for sizing needs. using the step attribute you can use the step attrib...
...And 6 more matches
<input type="week"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › week
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 control's user interface varies from browser to browser; cross-browser support is currently a bit limited, with only chrome/opera and microsoft edge supporting it at this time. in non-supporting browsers, the control degrades gracefully to function identically to <input type="text">. ...
... display it as week 01, 2017, but the submitted value will always look like week=2017-w01. ...
...if the value entered into the element exceeds this, the element fails constraint validation. ...
...And 6 more matches
HTML elements reference - HTML: Hypertext Markup Language
Web › HTML › Element
<title> the html title element (<title>) defines the document's title that is shown in a browser's title bar or a page's tab. sectioning root element description <body> the html <body> element represents the content of an html document. there can be only one <body> element in a document. content sectioning content sectioning elements allow you to organize the document content into logical pieces. use the sectioning elements to create a broad outline for your page content, including header and footer navigation, and heading elements to identify sections of content. element description <address> the html <address> element indicates that the enclosed html provides contact information for a person or ...
...ader> the html <header> element represents introductory content, typically a group of introductory or navigational aids. it may contain some heading elements but also a logo, a search form, an author name, and other elements. <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 fun...
.... a url for the source of the quotation may be given using the cite attribute, while a text representation of the source can be given using the <cite> element. <dd> the html <dd> element provides the description, definition, or value for the preceding term (<dt>) in a description list (<dl>). <div> the html content division element (<div>) is the generic container for flow content. it has no effect on the content or layout until styled using css. <dl> the html <dl> element represents a description list. the element encloses a list of groups of terms (specified using the <dt> element) and descriptions (provided by <dd> elements). common uses for this element are to implement a glossary or to display metadata (a list of key-value pairs). <dt>...
...And 6 more matches
Inline elements - HTML: Hypertext Markup Language
in this article, we'll examine html inline-level elements and how they differ from block-level elements. ...
...in this article, we'll examine html inline-level elements and how they differ from block-level elements. ...
...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 example which demonstrates an inline element: <div>the following span is an <span class="highlight">inline element</span>; its background has been colored to display both the beginning and end of the inline element's influence.</div> in this example, the <div> block-level element contains some text. within that text is a <span> element, which is an inline element. because the <span> element ...
...And 6 more matches
CORS errors - HTTP
Web › HTTP › CORS › Errors
cross-origin resource sharing (cors) is a standard that allows a server to relax the same-origin policy. this is used to explicitly allow some cross-origin requests while rejecting others. for example, if a site offers an embeddable service, it may be necessary to relax certain restrictions. setting up such a cors configuration isn't necessarily easy and may present some challenges. in these pages, we'll look into some common cors error messages and how to resolve them. if the cors configuration isn't setup correctly, the browser console will present an error like "cross-origin request blocked: the same origin policy disallows reading the remote resource at $somesite" indicating that the request was blocked due to violating the cors security rules. this might not necessarily be a set-up mis...
...however, if the endpoint is meant to be available, some debugging is needed to succeed. ...
...guration, you need to find out which request is at fault and why. these steps may help you do so: navigate to the web site or web app in question and open the developer tools. now try to reproduce the failing transaction and check the console if you are seeing a cors violation error message. it will probably look like this: the text of the error message will be something similar to the following: cross-origin request blocked: the same origin policy disallows reading the remote resource at https://some-url-here. (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...
...And 6 more matches
Feature Policy - HTTP
feature policy allows web developers to selectively enable, disable, and modify the behavior of certain features and apis in the browser. it is similar to content security policy but controls features instead of security behavior. the feature-policy header has now been renamed to permissions-policy in the spec, and this article will eventually be updated to reflect that change. in a nutshell feature policy provides a mechanism to explicitly declare what functionality is used (or not used), throughout your website. this allows you to lock in best practices, even as the codebase evolves over time — as well as to more safely compose third-party content — by limiting which features are available. with feature policy, you opt-in to a set of "policies" for the browser to enforce on speci...
...licies" for the browser to enforce on specific features used throughout a website. these policies restrict what apis the site can access or modify the browser's default behavior for certain features. examples of what you can do with feature policy: change the default behavior of autoplay on mobile and third party videos. restrict a site from using sensitive apis like camera or microphone. ...
... do with feature policy: change the default behavior of autoplay on mobile and third party videos. restrict a site from using sensitive apis like camera or microphone. allow iframes to use the fullscreen api. block the use of outdated apis like synchronous xhr and document.write(). ensure images are sized properly and are not too big for the viewport. concepts and usage feature policy allows you to control which origins can use which features, both in the top-level page and in embedded frames. essentially, you write a policy, which is an allowed list of origins for each feature. for every feature controlled by feature policy, the feature is only enabled in the current document or frame if its origin matches the allowed list of origins. for each policy-controlled feature, the browse...
...And 6 more matches
CSP: form-action - HTTP
the target of a form submissions from a given context. whether form-action should block redirects after a form submission is debated and browser implementations of this aspect are inconsistent (e.g. firefox 57 doesn't block the redirects whereas chrome 63 does). csp version 2 directive type navigation directive default-src fallback no. not setting this allows anything. syntax one or more sources can be set for the form-action policy: content-security-policy: form-action <source>; content-security-policy: form-action <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading...
...: url scheme. mail.example.com:443: matches all attempts to access port 443 on mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a scheme such as http: or https:. the colon is required. unlike other values below, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. f...
...es shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' ...
...And 6 more matches
CSP: img-src - HTTP
the http content-security-policy img-src directive specifies valid sources of images and favicons. csp version 1 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the img-src policy: content-security-policy: img-src <source>; content-security-policy: img-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as the port number, indicating that all legal por...
...: url scheme. mail.example.com:443: matches all attempts to access port 443 on mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a scheme such as http: or https:. the colon is required. unlike other values below, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. f...
...es shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' ...
...And 6 more matches
CSP: navigate-to - HTTP
the http content-security-policy (csp) navigate-to directive restricts the urls to which a document can initiate navigations by any means including <form> (if form-action is not specified), <a>, window.location, window.open, etc. this is an enforcement on what navigations this document initiates not on what this document is allowed to navigate to. note: if the form-action directive is present, the navigate-to directive will not act on navigations that are form submissions. csp version 3 directive type navigation directive default-src fallback no. not setting this allows anything. syntax one or more sources can be set for the navigate-to policy: content-security-policy: navigate-to <source>; content-security-policy: navigate-to <source> <source...
...tions that are form submissions. csp version 3 directive type navigation directive default-src fallback no. not setting this allows anything. syntax one or more sources can be set for the navigate-to policy: content-security-policy: navigate-to <source>; content-security-policy: navigate-to <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as the port number, indicating that all legal ports are valid for the source. examples: http://*.example.com: matches all attempts to load from any s...
...: url scheme. mail.example.com:443: matches all attempts to access port 443 on mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a scheme such as http: or https:. the colon is required. unlike other values below, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. f...
...And 6 more matches
CSP: prefetch-src - HTTP
the http content-security-policy (csp) prefetch-src directive specifies valid resources that may be prefetched or prerendered. csp version 3 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the prefetch-src policy: content-security-policy: prefetch-src <source>; content-security-policy: prefetch-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as the ...
...: url scheme. mail.example.com:443: matches all attempts to access port 443 on mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a scheme such as http: or https:. the colon is required. unlike other values below, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. f...
...es shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' ...
...And 6 more matches
CSP: sandbox - HTTP
f plugins and scripts, and enforcing a same-origin policy. csp version 1.1 / 2 directive type document directive this directive is not supported in the <meta> element or by the content-security-policy-report-only header field. ...
...s, and enforcing a same-origin policy. csp version 1.1 / 2 directive type document directive this directive is not supported in the <meta> element or by the content-security-policy-report-only header field. ...
... csp version 1.1 / 2 directive type document directive this directive is not supported in the <meta> element or by the content-security-policy-report-only header field. syntax content-security-policy: sandbox; content-security-policy: sandbox <value>; where <value> can optionally be one of the following values: allow-downloads-without-user-activation allows for downloads to occur without a gesture from the user. ...
...And 6 more matches
CSP: script-src-attr - HTTP
inline script event handlers like onclick, but not urls loaded directly into <script> elements. csp version 3 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the script-src directive, and if both of them are absent, fallback to default-src directive. ...
...the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as the port number, indicating that all legal ports are valid for the source. ...
...: url scheme. mail.example.com:443: matches all attempts to access port 443 on mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a scheme such as http: or https:. the colon is required. unlike other values below, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. f...
...And 6 more matches
CSP: script-src-elem - HTTP
lid sources for javascript <script> elements, but not inline script event handlers like onclick. csp version 3 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the script-src directive, and if both of them are absent, fallback to default-src directive. ...
...the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as the port number, indicating that all legal ports are valid for the source. ...
...: url scheme. mail.example.com:443: matches all attempts to access port 443 on mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a scheme such as http: or https:. the colon is required. unlike other values below, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. f...
...And 6 more matches
Feature-Policy: display-capture - HTTP
the http feature-policy header display-capture directive controls whether or not the document is permitted to use screen capture api, i.e.,getdisplaymedia() to capture the screen's contents. if display-capture is disabled in a document, the document will not be able to initiate screen capture via getdisplaymedia(). ...
... the http feature-policy header display-capture directive controls whether or not the document is permitted to use screen capture api, i.e.,getdisplaymedia() to capture the screen's contents. if display-capture is disabled in a document, the document will not be able to initiate screen capture via getdisplaymedia(). ...
... the http feature-policy header display-capture directive controls whether or not the document is permitted to use screen capture api, i.e.,getdisplaymedia() to capture the screen's contents. if display-capture is disabled in a document, the document will not be able to initiate screen capture via getdisplaymedia(). ...
...And 6 more matches
OPTIONS - HTTP
Web › HTTP › Methods › OPTIONS
the http options method requests permitted communication options for a given url or server. a client can specify a url with this method, or an asterisk (*) to refer to the entire server. ...
... for a given url or server. a client can specify a url with this method, or an asterisk (*) to refer to the entire server. ...
...in this example, we will request permission fo...
...And 6 more matches
HTTP Public Key Pinning (HPKP) - HTTP
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][; report-uri="reporturi"] pin-sha256 the quoted string is the base64 encoded subject public key information (spki) fingerprint. it is possible to specify multiple pins for different public keys. some browsers might allow other hashing algorithms than sha-256 in the future. see below on how to extract this information out of a certificate or key file. max-age the time, in seconds, that the browser should remember that this site is only to be accessed using one of the defined keys. includesubdomains optional if this optional parameter is specified, this rule applies to all of the site's subdomains as well. rep...
... one of the defined keys. includesubdomains optional if this optional parameter is specified, this rule applies to all of the site's subdomains as well. report-uri optional if this optional parameter is specified, pin validation failures are reported to the given url. note: the current specification requires including a second pin for a backup key which isn't yet used in production. ...
...l. note: the current specification requires including a second pin for a backup key which isn't yet used in production. this allows for changing the server's public key without breaking accessibility for clients that have already noted the pins. this is important for example when the former key gets compromised. extracting the base64 encoded public key information note: while the example below shows how to set a pin on a server certificate, it is recommended to place the pin on the intermediate certificate of the ca that issued the server certificate, to ease certificates renewals and rotations. ...
...And 6 more matches
encodeURIComponent() - JavaScript
.com/mdn/interactive-examples and send us a pull request. syntax encodeuricomponent(str); parameters str string. a component of a uri. return value a new string representing the provided string encoded as a uri component. description encodeuricomponent() escapes all characters except: not escaped: a-z a-z 0-9 - _ . ...
...this will encode ...
...this will encode "&" symbols that may inad...
...And 6 more matches
parseInt() - JavaScript
string [, radix]) parameters string the value to parse. if this argument is not a string, then it is converted to one using the tostring abstract operation. leading whitespace in this argument is ignored. radix optional an integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. be careful—this does not default to 10! the description below explains in more detail what happens when radix is not provided. return value an integer parsed from the given string. or nan when the radix is smaller than 2 or bigger than 36, or the first non-whitespace character cannot be converted to a number. description the parseint function converts its first argument to a string, parses that string, then returns an integer or nan. if not nan,...
...0, letters of the english alphabet indicate numerals greater than 9. for example, for hexadecimal numbers (base 16), a through f are used. if parseint encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseint truncates numbers to integer values. leading and trailing spaces are allowed. because some numbers use the e character in their string representation (e.g. 6.022e23 for 6.022 × 1023), using parseint to truncate numbers will produce unexpected results when used on very large or very small numbers. parseint should not be used as a substitute for math.floor(). parseint understands exactly two signs: + for positive, and - for negative (since ecmascript 1). it is done as ...
...sing parseint to truncate numbers will produce unexpected results when used on very large or very small numbers. parseint should not be used as a substitute for math.floor(). parseint understands exactly two signs: + for positive, and - for negative (since ecmascript 1). it is done as an initial step in the parsing after whitespace is removed. if no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. if radix is undefined, 0, or unspecified, javascript assumes the following: if the input string begins with "0x" or "0x" (a zero, followed by lowercase or uppercase x), radix is assumed to be 16 and the rest of the string is parsed as a hexidecimal number. if the input string begins with "0" (a zer...
...And 6 more matches
this - JavaScript
ndow); // true a = 37; console.log(window.a); // 37 this.b = "mdn"; console.log(window.b) // "mdn" console.log(b) // "mdn" note: you can always easily get the global object using the global globalthis property, regardless of the current context in which your code is running. function context inside a function, the value of this depends on how the function is called. since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser. function f1() { return this; } // in a browser: f1() === window; // true // in node: f1() === globalthis; // true in strict mode, however, if the value of this is not set when entering an execution context, it remains as undefined, as sho...
...ot in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser. function f1() { return this; } // in a browser: f1() === window; // true // in node: f1() === globalthis; // true in strict mode, however, if the value of this is not set when entering an execution context, it remains as undefined, as shown in the following example: function f2() { 'use strict'; // see strict mode return this; } f2() === undefined; // true in the second example, this should be undefined, because f2 was called directly and not as a method or property of an object (e.g. window.f2()). this feature wasn't implemented in some browsers when they first started to support strict mode. as a result, they incorrectly returned the wi...
...mple, this should be undefined, because f2 was called directly and not as a method or property of an object (e.g. window.f2()). this feature wasn't implemented in some browsers when they first started to support strict mode. as a result, they incorrectly returned the window object. to set the value of this to a particular value when calling a function, use call(), or apply() as in the examples below. class context the behavior of this in classes and functions is similar, since classes are functions under the hood. but there are some differences and caveats. within a class constructor, this is a regular object. all non-static methods within the class are added to the prototype of this: class example { constructor() { const proto = object.getprototypeof(this); console.log(object.
...And 6 more matches
Mobile first - Progressive web apps (PWAs)
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 as an option, especially if you are experienci...
...ered.) 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 as an option, especially if you are experiencing slow or laggy performance when your application is running on mobile. control mechanisms control mechanisms are another large constraint on mobile devices. anyone who has ever tried to enter data into a form on a mobile device, or even just navigated around a complex site, knows this well. therefore we should try to simplify things on mobile, keeping each view cut down to a single, simple purpose wh...
...tom of the page? you could then also provide a link to get back up to the top of the article. conditional resource loading to actually implement responsive/adaptive designs, you will need to enlist a certain amount of conditional resource loading, again so that different devices can receive an optimal experience without having to shoulder the burden of many resources that they don't need. see below for more details. a simple example to demonstrate the concepts, i wanted to cover in this article, i created a very simple app containing a nav menu, heading and single column of text. you can see my mobile first example running live, or grab the code to play with it on github. to make my simple example i created a sample app structure from a mozilla mortar template. i installed the volo automa...
...And 6 more matches
stroke-linejoin - SVG: Scalable Vector Graphics
the stroke-linejoin attribute is a presentation attribute defining the shape to be used at the corners of paths when they are stroked. note: as a presentation attribute stroke-linejoin can be used as a css property. ...
...back to "miter" if not supported. --> <path d="m3,11 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5" stroke="black" fill="none" stroke-linejoin="miter-clip" /> <!-- bottom right path: effect of the "arcs" value with fallback to "miter" if not supported. ...
... the arcs value indicates that an arcs corner is to be used to join path segments. the arcs shape is formed by extending the outer edges of the stroke at the join point with arcs that have the same curvature as the outer edges at the join point. example html,body,svg { height:100% } <svg viewbox="0 0 6 6" xmlns="http://www.w3.org/2000/svg"> <!-- effect of the "arcs" value --> ...
...And 6 more matches
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
svg 2 is the next major version of the svg standard, which is a complete rework of the svg 1.2 draft. version 2 contains a lot of changes regarding the last stable version svg 1.1. those changes are listed below including their support status within mozilla applications. general change notes length attribute and indexed property for list interfaces implementation status unknown <script> element in content model of all elements implementation status unknown initialize(), appenditem(), replaceitem(), and insertitembefore() on list objects making a copy of any list item being inserted that is already in another list implementation status unknown crossorigin attribute for <image> and <script> elements not implemented ye...
...enditem(), replaceitem(), and insertitembefore() on list objects making a copy of any list item being inserted that is already in another list implementation status unknown crossorigin attribute for <image> and <script> elements not implemented yet (at least for <image>; bug 1240357) rendering model change notes svg root and <foreignobject> not overflow:hidden in ua style sheet implementation status unknown allow overflow: auto; to clip and show scroll bars implementation status unknown allow overflow: scroll; to show scroll bars on <svg> elements implementation status unknown basic data types and interfaces change notes dommatrix or dommatrixreadonly instead of svgmatrix implementat...
... not implemented (bug 778654) svgelement.tabindex implemented (bug 778654) document.activeelement implementation status unknown globaleventhandlers on svgelement implementation status unknown options dictionary attribute for svggraphicselement.getbbox() implemented behind the preference svg.new-getbbox.enabled (bug 999964, bug 1019326) allow leading and trailing whitespace in <length>, <angle>, <number> and <integer> implementation status unknown form feed (u+000c) in whitespace implementation status unknown svgelement.xmlbase, svgelement.xmllang and svgelement.xmlspace removed implementation status unknown svgviewspec removed implementation status unknown svgelement.style removed im...
...And 6 more matches
Same-origin policy - Web security
tentially malicious documents, reducing possible attack vectors. definition of an origin two urls have the same origin if the protocol, port (if specified), and host are the same for both. you may see this referenced as the "scheme/host/port tuple", or just "tuple". ...
...owser. changing origin a page may change its own origin, with some limitations. a script can set the value of document.domain to its current 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 comp...
... number is checked separately by the browser. any call to document.domain, including document.domain = document.domain, causes the port number to be overwritten with null. therefore, one cannot make company.com:8080 talk to company.com by only setting document.domain = "company.com" in the first. it has to be set in both so their port numbers are both null. note: when using document.domain to allow a subdomain to access its parent securely, you need to set document.domain to the same value in both the parent domain and the subdomain. this is necessary even if doing so is simply setting the parent domain back to its original value. failure to do this may result in permission errors. cross-origin network access the same-origin policy controls interactions between two different origins, suc...
...And 6 more matches
WebAssembly Concepts - WebAssembly
ind how webassembly works including its goals, the problems it solves, and how it runs inside the web browser's rendering engine. what is webassembly? webassembly is a new type of code that can be run in modern web browsers and provides new features and major gains in performance. it is not primarily intended to be written by hand, rather it is designed to be an effective compilation target for low-level source languages like c, c++, rust, etc. this has huge implications for the web platform — it provides a way to run code written in multiple languages on the web at near-native speed, with client apps running on the web that previously couldn’t have done so. what’s more, you don’t even have to know how to create webassembly code to take advantage of it. webassembly modules can be ...
... be imported into a web (or node.js) app, exposing webassembly functions for use via javascript. javascript frameworks could make use of webassembly to confer massive performance advantages and new features while still making functionality easily available to web developers. ...
...ty easily available to web developers. webassembly goals webassembly is being created as an open standard inside the w3c webassembly community group with the following goals: be fast, efficient, and portable — webassembly code can be executed at near-native speed across different platforms by taking advantage of common hardware capabilities. be readable and debuggable — webassembly is a low-level assembly language, but it does have a human-readable text format (the specification for which is still being finalized) that allows code to be written, viewed, and debugged by hand. keep secure — webassembly is specified to be run in a safe, sandboxed execution environment. like other web code, it will enforce the browser's same-origin and permissions policies. don't break the web — w...
...And 6 more matches
cfx - Archive of obsolete content
grate from cfx to jpm see this guide. enables you to test, run, and package add-ons. cfx is is no longer supported as of firefox 44 and no longer accepted for add-on submission, jpm should now be used instead. cfx usage is: cfx [options] command [command-specific options] "options" are global options applicable to the tool itself or to all commands (for example --help). cfx supports the following global options: -h, --help - show a help message and exit -v, --verbose - enable lots of output "command-specific options" are documented alongside the commands. there are four supported cfx commands: cfx init create a skeleton add-on as a starting point for your own add-on. cfx run launch an instance of firefox with your add-on installed. c...
...s an xpi file, which is the install file format for firefox add-ons. there are also a number of internal commands, which are more likely to be useful to sdk developers than to add-on developers. cfx init create a new directory called "my-addon", change into it, and run cfx init. this command will create an skeleton add-on, as a starting point for your own add-on development, with the following file structure: my-addon data docs main.md lib main.js package.json readme.md tests test-main.js cfx run this command is used to run the add-on. called with no options it looks for a file called package.json in the current directory, loads the corresponding add-on, and runs it under the version of firef...
...inary, --binary=binary use the host application binary specified in binary. binary may be specified as a full path or as a path relative to the current directory. --binary-args=cmdargs pass extra arguments to the binary being executed (for example, firefox). for example, to pass the -jsconsole argument to firefox, which will launch the javascript error console, try the following: cfx run --binary-args -jsconsole to pass multiple arguments, or arguments containing spaces, quote them: cfx run --binary-args '-url "www.mozilla.org" -jsconsole' --extra-packages=extra_packages extra packages to include, specified as a comma-separated list of package names. -g config, --use-config=config pass a set of options by referencing a name...
...And 5 more matches
Localization - Archive of obsolete content
ation of strings appearing in: your main add-on's javascript code html files packaged with your add-on the title, description and homepage fields of your add-on's metadata the title and description fields of your add-on's preferences. it doesn't, yet, support localization of css or content scripts, or the add-on's title and description that appear in the add-ons manager. see limitations below. localized strings translated strings are kept in a directory called "locale" under your main add-on directory, one file for each locale. the files: use the .properties format are named "xx-yy.properties", where "xx-yy" is the name of the locale in question contain one entry for each string you want to localize, consisting of an identifier for the string and its translation in that locale,...
... string is inserted as text, so you can't insert html using a statement like: # does not work. html tags are inserted as text. ...
...wo tomatoes пять помидоров // five tomatoes the sdk uses the unicode cldr data to describe the different plural forms used by different languages. unicode cldr plural forms the unicode cldr project defines a scheme for describing a particular language's plural rules. ...
...And 5 more matches
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
« previousnext » adding a new toolbar adding new toolbars to firefox is easy, but adding them the wrong way is very easy as well. toolbars in firefox are very customizable. some users don't like extra toolbars, or they want to rearrange toolbar buttons to their liking, possibly merging multiple toolbars in the process. firefox allows all of this by default, and if you don't pay attention to the details we describe here, your toolbar may not be as easy to customize as the rest. the first thing you need to do is add your buttons to the toolbar palette. the toolbarpalette is a collection of all toolbar buttons and toolbar items in firefox, including those added by extensions. to add your buttons, all you need to do is overlay the palette in your main browser overlay. <...
...ur buttons, all you need to do is overlay the palette in your main browser overlay. <overlay id="xulschoolhello-browser-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <toolbarpalette id="browsertoolbarpalette"> <toolbarbutton id="xulschoolhello-hello-world-button" class="toolbarbutton-1 chromeclass-toolbar-additional" label="&xulschoolhello.helloworld.label;" tooltiptext="&xulschoolhello.helloworld.tooltip;" oncommand="xulschoolchrome.browseroverlay.dosomething(event);" /> <!-- more buttons here. --> </toolbarpalette> <!-- more overlay stuff. --> </overlay> one detail that is easy to overlook is the fact that the toolbarpalette element is outside of the window element. if you put the toolbarpalette element inside the ...
...</toolbox> </window> (note for mac os x: <window id="main-window"> 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 cu...
...And 5 more matches
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
ml, from their scripts. for security reasons, and to prevent errors, care needs to be taken to avoid evaluating arbitrary text as html. failure to do so can lead to execution or remote scripts, and in the worst cases to privilege escalation which can leave a user's pc open to remote attack. building dom trees in most cases, dom trees should be built exclusively with dom creation methods. the following methods will all safely create a dom tree without risk of remote execution. json templating jsontodom.namespaces = { html: "http://www.w3.org/1999/xhtml", xul: "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" }; jsontodom.defaultnamespace = jsontodom.namespaces.html; function jsontodom(jsontemplate, doc, nodes) { function namespace(name) { var reelemnamepar...
...f, text: text }) .click(function (event) { alert(event.target.href) })) .append($("<span>").text("foo"))); innerhtml with html escaping this method is a last resort which should be used only as a temporary measure in established code bases. ...
...de bases. safely generating event listeners and scripts it is occasionally necessary to generate event listeners and script fragments from dynamic content. great care must be taken in these situations. under no circumstances should code resembling 'callback("' + str + '")' appear anywhere in your add-on. closures by far the best way to create dynamic event listeners is to use closures. the following two code fragments are roughly equivalent: function clickify(elem, address) { elem.addeventlistener("click", function (event) { openwindow(address) }, false); } function clickify(elem, address) { elem.onclick = function (event) { openwindow(address) }; } multiple attributes sometimes there is a need for event listeners to appear as attributes in the dom. in these cases, multiple a...
...And 5 more matches
Setting Up a Development Environment - Archive of obsolete content
an equivalent system using batch, ant or whatever you prefer. ultimately you can just compress the contents of the src directory using any zip or archive tool and get a similar result. build system let's start by downloading the project used to build the second version of hello world, from the exercise in the last section. hello world 2 project. unzip the file anywhere you want. inside the helloworld2 directory, you'll see two directories: bin and src. the bin directory should be empty. this is where all the resulting build files will be created, and where you'll find the extension xpi file once you get it to build. open the project file (helloworld2.komodoproject) from the src directory in komodo edit. in the projects tab you should be able to see the directory structure inside the src ...
...es in makefile. these define the extension name, the extension id (as specified in install.rdf) and the name of the profile directory where the extension will be installed during development and testing. more about this further ahead. let's try and build the xpi from the command line first. open the command line program in your system and navigate to the src directory in your project. run the following command: make that's it. if everything went well, you should see an output similar to this: creating xpi file. adding: install.rdf (deflated 50%) adding: chrome.manifest (deflated 50%) adding: content/browseroverlay.js (deflated 42%) adding: content/browseroverlay.xul (deflated 69%) adding: skin/browseroverlay.css (stored 0%) adding: locale/browseroverlay.dtd (deflated 52%...
... bin directory, you should see the xulschoolhello2.xpi file. if you run make again, you'll only see the last line of the build process. that is because make can tell that the file in the bin directory is up to date, and nothing needs to be done. making changes on source files will make make run the necessary steps to build the xpi again. you can clean up the bin directory by just running the following command (again, from the src directory): make clean you can also run these commands from komodo. click on tools > run command.... in the "run" textbox you should type this: bash -c "make" or replace "make" with "make clean" for the clean command. the "bash -c" part forces komodo to use bash, which for some reason can't be set properly as the default command shell. it isn't necess...
...And 5 more matches
Creating regular expressions for a microsummary generator - Archive of obsolete content
ay.com", the file path is "/ws/ebayisapi.dll", and the query parameters are "?viewitem&item=280018439106". matching an ebay url to match this url with a regular expression, we need to put characters into the regular expression that match the characters in the url. most of the time, we can match a character in the url by putting the same character into the regular expression. for example, the following regular expression matches--and looks exactly like--the beginning of the url: http:// but some characters are special in regular expressions. for example, a period (.) matches any character, and a period followed by an asterisk (.*) matches any combination of characters. when such characters appear in a url, and we want to match them in a regular expression, we have to escape them in the e...
... pages: http://cgi.ebay.com/ws/ebayisapi.dll?viewitem&item=130017517168 http://cgi.ebay.com/ws/ebayisapi.dll?viewitem&item=290019763032 http://cgi.ebay.com/ws/ebayisapi.dll?viewitem&item=170019463424 based on these examples, it looks like the unique part is the item number at the end of the urls, and everything else is common to all urls. so we remove the item number, leaving us with the following regular expression: ^http://cgi\.ebay\.com/ws/ebayisapi\.dll\?viewitem&item= accommodating variations in query parameters we now have a regular expression that matches all four example urls. it'll probably match the urls for other auction item pages, too. but to make it more robust, we should accommodate the possibility of variation in the query parameters. a named query parameter is a s...
...meter is a string of the form <name>=<value>, where <name> and <value> are arbitrary strings. in our url, "item=280018439106" is the only such parameter. but urls can contain multiple named parameters separated by ampersands (&), and the parameters can appear in any order, so even though the "item" parameter seems to be necessary, it might not appear right next to "viewitem". ...
...And 5 more matches
Drag and Drop JavaScript Wrapper - Archive of obsolete content
tored in the global package, in the file chrome://global/content/nsdraganddrop.js. you can include this file in your xul file with the script tag in the same way you would include your own scripts. the library also depends on another script library, which you should also include, usually at the top of your xul file. you can look at the contents of these files to see how drag and drop is done at a lower level. note that you can only use these libraries from within xul loaded via a chrome url. <script src="chrome://global/content/nsdraganddrop.js" /> <script src="chrome://global/content/nstransferable.js" /> this drag and drop library creates an object stored in the variable nsdraganddrop. the object contains a series of functions, one for each event handler (except for dragenter where it has ...
...ent/nstransferable.js" /> this drag and drop library creates an object stored in the variable nsdraganddrop. the object contains a series of functions, one for each event handler (except for dragenter where it has nothing special to do). each of the functions takes two parameters, the first is the event object and the second is an observer object that you create. more on that in a moment. the following is an example of calling the nsdraganddrop object. <button label="drag me" ondraggesture="nsdraganddrop.startdrag(event,buttonobserver);" /> the function startdrag will be called when a drag starts on the button. the first parameter is the event object, available in all event handlers. the second parameter to this function is the observer, which we'll create soon. in this case we only do anyt...
...r);" /> the function startdrag will be called when a drag starts on the button. the first parameter is the event object, available in all event handlers. the second parameter to this function is the observer, which we'll create soon. in this case we only do anything special when the button drag is started. ...
...And 5 more matches
Repackaging Firefox - Archive of obsolete content
n, this process is simple and easy to maintain. important legal considerations before you get started, it is very important to know and abide by the legal requirements for distributing firefox. you must have written authorization from mozilla to distribute a modified version of firefox. to do this, please contact trademarks@mozilla.com. getting started now, on to the technical details. the following diagram represents an overview of the process and the pieces involved: you will need the following to get started: a macintosh computer (even for repackaging windows or linux only); it may be either powerpc or intel based. the repackager tool. currently that page mentions only firefox 1.5.x, but it supports firefox 2. the pristine firefox 2 installer files (windows .exe, mac .dmg, or l...
... extension" (sometimes abbreviated as "dex"), because it is used to create a new "distribution" of firefox, with different branding, etc. using an extension makes it far easier to keep track of your changes easily when the time comes to upgrade to new versions of firefox, and also ensures, when set-up correctly, that users are able to safely receive firefox updates from mozilla. more about this below. while the aim of this article is not to fully document how to make an extension (for that, try this section of the mozilla developer center), here is a basic tutorial to get you started, and some tips specific for creating a dex. if you already have an extension that you want to bundle with firefox, and don't want to bundle an extra extension solely to set a few defaults, you can do everything...
... to set a few defaults, you can do everything you need to do in your existing extension. however, it's still recommended that you look through this tutorial, as it contains tips specific for creating extensions of this type, and there are a few options that you will need to set to ensure a smooth upgrade path for users. at the very least, don't skip the "important extension preferences" section below. ...
...And 5 more matches
Anonymous Content - Archive of obsolete content
d element during binding attachment. an element declared in a bound document using a single tag can then be constructed out of multiple child elements, and this implementation is hidden from the bound document. for example, the html file upload control appears in most browsers as a composite widget consisting of a text field and a button. a sample xbl binding for the file widget might look as follows: <binding id="fileupload"> <content> <html:input type="text"/> <html:input type="button"/> </content> </binding> because this content is not visible to its parent element, it is said to be anonymous content. scoping and access using the dom when a binding is attached and certain conditions are met, the children of the binding's content element are cloned. elements and attributes...
...encountered with a selector whose node set matches the element when doing a depth-first walk of the content template. note that children elements are never cloned when content is generated from a template. handling dom changes insertion points continuing to be used as elements are inserted or removed from the dom. whenever an element is inserted or appended, all insertion points are checked following all the same rules that applied when first placing explicit children during anonymous content generation. if no insertion point is found for the newly-inserted child, then the binding is no longer a fit for the bound element, and all anonymous content will be destroyed. whenever an element is removed, it simply disappears from its insertion point along with all anonymous content that was gene...
...ved, then any explicit children found underneath the insertion point are relocated to any other insertion points that match. again, if all the children cannot be relocated, then the anonymous content is destroyed. ...
...And 5 more matches
Creating XPI Installer Modules - Archive of obsolete content
racts with xpinstall. a xpi file typically contains the resources to be installed (in this case the barley.jar we want to have installed in the mozilla/bin/chrome/ directory) and an install script that guides the installation process. under the chrome/ directory, you'll notice that in addition to the package subdirectories, there are now also a handful of jar files, or java archives (see figure below). jar is a file format based on the zip file format and is used for aggregating multiple files into a single file. these archives are redundant with the subdirectories: mozilla now installs both the compressed and uncompressed versions of the ui, though you can change this when you build mozilla yourself. chrome/ us/ us.jar chatzilla/ chatzilla.jar chrome.rdf chromelist.txt classic/...
...ackaging scheme of mozilla and offers a tutorial for creating a new package that can then be redistributed, installed, and made available to users. the xpi packaging scheme a complete description of the new packaging scheme is beyond the scope of this article. the reader is referred to jar packaging, which describes the design, goals, and options available for jar packaging in some depth. what follows is a very brief overview of the design and a description of what mozilla expects in installable packages. resources are collected in jar archives whose contents are specified in contents.rdf files at their own top level. the contents.rdf file explains the structure and contents of the archive to mozilla's chrome registry; as long as the explanation is accurate, the contents can be arranged in al...
...chrome other than the default, which is the main browser window. for this option to work, the designated chrome must have been installed and registered properly with mozilla. the chrome:// url pointer corresponds 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...
...And 5 more matches
Learn XPI Installer Scripting by Example - Archive of obsolete content
press, and automate software installations and software updates. a xpi is a pkzip-compressed archive (like zip and jar files) with a special script at the highest level that manages the installation. that installer script , usually named install.js, is the subject of this article. ...
...ed in the archive itself, though it's possible to rearrange things arbitrarily upon installation--to create new directories, to install files in system folders and other areas. overview of the install script xpi install scripts are written in javascript using xpinstall engine syntax defined in the xpinstall api reference. ...
...initinstall(). the initinstall() method on the install object creates a new installation for the specified software and version. in the browser.xpi installation, this function appears at line 20: var err = initinstall("netscape seamonkey", "browser", "6.0.0.2000110807"); if you call a method on the install object before initinstall(), you will get an error. the initinstall method takes the following parameters: the display name of the package, the name of the package as it appears in the client registry, and the version, which can be expressed as a number or as an installversion object. in the example above, "netscape seamonkey" is the display name, "browser" is the registry name, and the version is "6.0.0.2000110807." see initinstall in the xpinstall api reference for more information on...
...And 5 more matches
Introduction to XUL - Archive of obsolete content
applications, for instance, will have preconceived notions of what to do when they receive an "open file" command. an "open" button is simply a button. it will send its command to the application for processing, generally using some simple javascript for linkage. we are at first primarily concerned with the obvious ui components: toolbars, menus and dialogs. ...
...l language will allow someone with a text editor, given a package of components which can work together, the ability to put together an application by specifying something like this (for an application on an os using menubars across the top of its applications' windows): main window containing menubar area at top across width of window containing menubar (and its contents) toolbar area below menubar across width of window containing main toolbar (and its contents) application-specific content area below toolbar area structure of a xul file our language of choice is xml, flavoured with css stylistic information. having said that, the details of a particular application of xml; say, the syntax for specifying a toolbar, are left to separate documents describing those particular...
...ent and a separate document describing xul windows. the task of writing a xul window description is basically the same as the task of writing an html content description, with these exceptions: the syntax is xml (not that different from html 4), and there are some elements unique to xul. these elements are widgets and certain infrastructure associated with the behaviour of the window, explained below. most of the details of writing a xul document are identical to those for writing an xml document, a description of which we will leave to other excellent xml documentation which we assume must exist but have never seen. this document will concentrate on xul-specific features. a word on case and namespaces, and filetypes xml is of course case sensitive. xul is equally so. our current code tend...
...And 5 more matches
OpenClose - Archive of obsolete content
tmenu').open = true;"/> <menu id="editmenu" label="edit"> <menupopup> <menuitem label="cut"/> <menuitem label="copy"/> <menuitem label="paste"/> </menupopup> </menu> this technique may be used for both menupopups that use the menu tag, the button tag and the toolbarbutton tag. for menupopups attached to other elements using the popup or context attributes, see opening a popup below. as with other ways of opening a menu, the popupshowing event will be fired to provide an opportunity to customize the commands that appear on the menu. there are several situations when opening a menu is not allowed. these are: if the menu is already open, or already in the process of being opened. naturally, attempting to open a menu that is already open doesn't have any effect. if the me...
...nu is set to false, the submenu will close, yet the parent file menu will remain open. on the other hand, if the open property on the file menu is set to false, both menus will close. this technique may be used for both menupopups that use the menu tag, the button tag and the toolbarbutton tag. for menupopups attached to other elements using the popup or context attributes, see closing a popup below. when a menu is closed, the popuphiding event is fired at the menupopup. attaching an event listener which listens for the popuphiding event can be used to remove any commands that were adding during the popupshowing event. menus and popups are also closed when the document or window they are contained within is closed, or if the menupopup element is removed from the document. these are situati...
...ogramatically. to do this, use the popup's openpopup method. this method may be used for any type of popup, either a menupopup, a panel, or a tooltip, including ones that can be opened via other means, for instance, a popup attached via the context attribute. the openpopup method takes six arguments which are used to specify how and where the popup should be positioned. these will be described below. ...
...And 5 more matches
Localization - Archive of obsolete content
xul and xml provide entities which are a convenient way of allowing localization. entities many applications are built such that translating the interface into a different language is as simple as possible. usually, a table of strings is created for each language. instead of hard-coding text directly into an application, each piece of text is only a reference into the string table. xml provides entities which can be used for a similar purpose. you should already be familiar with entities if you have written html. the codes &lt; and &gt; are examples of entities which can be used to place less than and greater than signs into the text. xml has a syntax which allows you to declare custom entities. you can use these so that the entity is replaced with its value, which can be a string ...
... <button label="&findlabel;"/> the text that will appear on the label will be the value that the entity &findlabel; has. ...
... files as utf-8 for non-ascii characters. that is, you should save them in utf-8 format (without bom). for more information, see mozilla language packs. once you have created a dtd file for your xul, you will need to add a line to the xul file which indicates that you want to use the dtd file. otherwise, errors will occur as it won't be able to find the entities. to do this, add a line of the following form somewhere near the top of the xul file: <!doctype window system "chrome://findfile/locale/findfile.dtd"> this line specifies that the url indicated is to be used as a dtd for the file. in this case, we have declared that we want to use the findfile.dtd dtd file. this line is typically placed just before the window element. you also need to add the locale to the chrome.manifest file, f...
...And 5 more matches
Popup Menus - Archive of obsolete content
the main difference is the way in which they appear. ...
...e of the attribute must be set to the id of the menupopup that you want to have appear. this is why you must put the id on the popup. that way it's easy to have multiple menupopups in one file. in the example above, we want to make the popup a context menu. that means that we need to use the context attribute and add it to the element which we want to have the popup associated with. the sample below shows how we might do this: example 1 : source view <popupset> <menupopup id="clipmenu"> <menuitem label="cut"/> <menuitem label="copy"/> <menuitem label="paste"/> </menupopup> </popupset> <box context="clipmenu"> <label value="context click for menu"/> </box> here, the menupopup has been associated with a box. whenever you context-click (right-click) anywhere inside the ...
...ps here. there are two ways to create a tooltip. the simplest way, which is much more common, is to add a tooltiptext attribute to an element for which you want to assign a tooltip. the second method is to use a tooltip element containing the content of a tooltip. this requires you to have a separate block of content for each tooltip or to have a script which sets the content. however, it does allow you to use any content besides text in a tooltip. example 2 : source view <button label="save" tooltiptext="click here to save your stuff"/> <popupset> <tooltip id="moretip" orient="vertical" style="background-color: #33dd00;"> <description value="click here to see more information"/> <description value="really!" style="color: red;"/> </tooltip> </popupset> <button label="more" to...
...And 5 more matches
XPCOM Interfaces - Archive of obsolete content
eferred to using the string '@mozilla.org/file/local;1'. this string is called a contract id. the syntax of a contract id is: @<internetdomain>/module[/submodule[...]];<version>[?<name>=<value>[&<name>=<value>[...]]] other components can be referred to in a similar way. the contract id of the component can be used to get the component. you can get a component using javascript code like that below: var afile = components.classes["@mozilla.org/file/local;1"].createinstance(); the file component is retrieved and stored in the afile variable. components in the example above refers to a general object that provides some component related functions. here, we get a component class from the classes property. the classes property is an array of all of the available components. to get a differen...
...he createinstance() function. you should check the return value of createinstance() to ensure that it is not null, which would indicate that the component does not exist. however, at this point, we only have a reference to the file component itself. in order to call the functions of it we need to get one of its interfaces, in this case nsilocalfile. a second line of code needs to be added as follows: var afile = components.classes["@mozilla.org/file/local;1"].createinstance(); if (afile) afile.queryinterface(components.interfaces.nsilocalfile); the function queryinterface() is a function provided by all components which can be used to get a specific interface of that component. this function takes one parameter, the interface that you want to get. the interfaces property of the component...
...hat afile will be a reference to the part of the component that implements the nsilocalfile interface. the two javascript lines above can be used to get any interface of any component. just replace the component name with the name of the component you want to use and change the interface name. you can also use any variable names of course. for example, to get a sound interface, you can do the following: var sound = components.classes["@mozilla.org/sound;1"].createinstance(); if (sound) sound.queryinterface(components.interfaces.nsisound); xpcom interfaces can inherit from other interfaces. the interfaces that inherit from others have their own functions and the functions of all the interfaces that they inherit from. all interfaces inherit from a top-level interface called nsisupports. it ...
...And 5 more matches
XUL Structure - Archive of obsolete content
ion or standalone xulrunner application. content from remote sources (e.g. http://localhost/~username/ ), regardless of whether they are html or xul or another document type, are limited in the type of operations they can perform, for security reasons. for this reason, mozilla provides a method of installing content locally and registering the installed files as part of its chrome system. this allows a special url form, called a chrome:// url, to be used. by accessing a file using a chrome url, the files receive elevated privileges to access local files, access preferences and bookmarks and perform other privileged operations. obviously, web pages do not get these privileges, unless they are signed with a digital certificate and the user has granted permission to perform these operations. t...
...ures to the browser. the extensions are small packages of xul files, javascript, style sheets and images packed together into a single file. these packaged files can be created by using a zip utility. when the user downloads the zipped file, the packaged files will be installed onto the user's machine. the extension will hook into the browser using a xul specific feature called an overlay which allows the xul from the extension to mesh with the xul in the browser. to the user, it may seem like the extension has modified the browser, but in reality, the code is all separate, and the extension may be easily uninstalled. registered packages are not required to use overlays, of course. if they don't, you won't be able to access them via the main browser interface, but you can still access them vi...
...s that there are certain things that content of web pages cannot do, such as read the user's bookmarks. this distinction is not based on the kind of content being displayed; only on the type of url used. both html and xul placed on a web site have no extra permissions; however both html and xul loaded through a chrome url have enhanced permissions. remote xul was disabled in firefox 8, so the following is of historic interest only. if you are going to use xul on a web site, you can just put the xul file on the web site as you would an html file, and then load its url in a browser http://localhost/xul.php. ensure that your web server is configured to send xul files with the content type of application/vnd.mozilla.xul+xml (eg with php header('content-type: application/vnd.mozilla.xul+xml');).
...And 5 more matches
scrollbox - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a box that has additional functions that can be used to scroll the content. note that a scrollbox doesn't cause scrollbars to be displayed. it is intended to be used when an application wants to be able to adjust the scroll position itself. if you just want scrollbars to appear, add style='overflow: auto;'. this may also be used with any other container element. examples the following shows the xul for a bunch of labels. they come out in a box. if their container doesn't give enough room to hold them (geometrically) what happens depends on the enclosing elements; often the content is just clipped off on the bottom or right (depending on what's too big to fit). <vbox> <label value="01 four...
... <vbox f...
...gh room for it, scroll bars will sprout out of nowhere and allow the user to scroll around the big content in the small view space. for the most part, the horizontal and vertical scrollbars will independently handle too-tall and too-wide cases, but each scroll bar takes up additional width and so the appearance of one scroll bar can trigger the other one if it's close to the edge anyway. use overflow:scroll if you want the scroll bars on all the time. ...
...And 5 more matches
window - Archive of obsolete content
ented box. as it is a box, all box attributes can be used. by default, the window will have a platform-specific frame around it. to set an icon for the window, create a platform-specific icon file <windowid>.ico and/or <windowid>.xpm and place or install these files into the <mozilla-directory>/chrome/icons/default/ directory. the <windowid> is the value of the id attribute on the window. this allows you to have a different icon for each window. without including the css file at "chrome://global/skin/", the window will not be stylized and will be invisible and glitchy when opened as a dialog. note: starting in gecko 1.9.2, you can detect when a window is activated or deactivated by watching for the "activate" and "deactivate" events. see window activation events. more information is ava...
... activetitlebarcolor type: color string specify background color of the window's titlebar when it is active (foreground). moreover this hides separator between titlebar and window contents. this only affects mac os x. chromemargin type: margin string controls the amount of chrome that should be visible on each side of the window. the s...
...ul document, which is intended to be loaded in a tab, to disable the find bar for the tab with this document. this is used to prevent the find bar from being displayed when it's not supported by the content (such as in the add-ons manager tab). drawintitlebar type: boolean if this attribute is true, the top of the window's content area will begin at the top edge of the title bar, instead of below the title bar. this allows the window to draw in the title bar. this is supported only from window elements, and is ignored on platforms that don't support drawing into the title bar. fullscreenbutton type: boolean set this attribute to true to display a button 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 ...
...And 5 more matches
Gecko Compatibility Handbook - Archive of obsolete content
at have updated to support standards. set up browsers for testing the various gecko-based browsers do not always contain netscape in the user-agent string. thus it's critical to verify that you are properly detecting browsers such as aol for macos. you can either download the various browsers. or, if you are using user-agent detection, you can install an extension in firefox or mozilla which allows you to "spoof" the user-agent strings of the various gecko browsers. here's how: launch mozilla or firefox. the benefit of using these browsers is that if you're only detecting netscape or netscape6 you'll see the issues right away. install the user agent switcher extension. after restarting your browser, add the the user-agent strings that you want to test to the list (tools | user agent s...
...of using these browsers is that if you're only detecting netscape or netscape6 you'll see the issues right away. install the user agent switcher extension. after restarting your browser, add the the user-agent strings that you want to test to the list (tools | user agent switcher | options | options... | user agents | add...). once you filled the dialog box (it should look like the screenshot below), click ok and close theoptions dialog. you can now start using the user-agent string you've just created by clicking tools | user agent switcher |the name you have chosen. you can verify the string got changed by looking under help | about. you can find the user agent strings of many gecko-based browsers here. if possible, also download the actual clients (netscape, aol, compuserve) for t...
...og. you can now start using the user-agent string you've just created by clicking tools | user agent switcher |the name you have chosen. you can verify the string got changed by looking under help | about. you can find the user agent strings of many gecko-based browsers here. if possible, also download the actual clients (netscape, aol, compuserve) for testing. review your results the following scenarios all relate to browser detection. for more solutions to common problems please continue reading this handbook. problem: site supports standards but does not look right try picking the internet explorer 6 user-agent string. if this works, set up your detection to serve ie 6 content to visitors with gecko in their user-agent strings. ie 6.x is actually more similar to gecko browsers t...
...And 5 more matches
Mozilla release FAQ - Archive of obsolete content
used by people who will be working with mozilla, either in an organizational fashion, suggesting features, or coding. visit netscape's website for help on that software. i went and made a suggestion and people were rude to me. why? if you posted it to the mailing list/newsgroups, remember that on usenet, people are not always polite to each other. some people are just rude, and some people have a low tolerance for uninformed people. if you're new to the mozilla newsgroups, you probably should be reading the newsgroup for a few days regularly before you post anything. reading this faq might help as well. i did all that, and people were still rude to me. why? if you're proposing reworking something (like http, html, etc) you're expected to have a pretty good knowlege of it first. for example, i...
...ad the build instructions for your platform. these instructions are included in the source tree, and are also available on the mozilla website: detailed build instructions: unix/x win32 mac if your version of make chokes on the makefiles (on unix), you might not be using gnu make. grab the latest version of gnu make from the gnu ftp site. ...
... recommend the following: if you are using unix, use bash-family shells for the build because of the better control over redirection (in case you want to log errors and messages) if you are using win32, using the default shell cmd.exe (as opposed to 4dos or 4nt) will probably yield better results. regarding compilation options, it would be good not to compile with optimization, because it's much slower to build, and on windows platforms, there's a bug in some versions of vc++ that makes mozilla crash in many common circumstances if compiled with optimization on. ...
...And 5 more matches
E4X for templating - Archive of obsolete content
strs.formatstringfromname(msg,args,args.length); } return strs.getstringfromname(msg); } for example, <toolbarbutton label={$s('mytoolbar.label')}/> conditionals function _if (cond, h, _else) { if (cond && cond != undefined) { // we need undefined condition for e4x return h(cond); } else if (_else) { return _else(cond); } return ''; // empty string allows conditions in attribute as well as element content } for example: {_if(elems.length(), function () <description>{elems[0]}</description>, function _else () <label>no data</label> )} note that the simple xmllist() constructor (<></>) may be useful to still be able to use an expression closure (i.e., without needing return statements and braces): {_if(elems.length(), function () <> ...
... /* the first two arguments are optional: (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) { ...
...ctions can also be easily serialized inline (and then perhaps converted to the dom) as needed: var list = <>{_if(elems.length(), function () <> <markup/> <markup/> </>)}</>.toxmlstring(); iterating functions such as the following foreach (which can work with arrays, objects, or e4x objects) are quite convenient in iterating over complex structures such as e4x would not normally allow. /* the first two arguments are optional: (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...
...And 5 more matches
Processing XML with E4X - Archive of obsolete content
/html> working with attributes xml literal syntax has a significant advantage over the xml constructor when you need to create markup dynamically. with e4x it is easy to embed dynamic values in markup. variables and expressions can be used to create attribute values by simply wrapping them with braces ({}) and omitting quotation marks that would normally go around an attribute value, as the following example illustrates: var a = 2; var b = <foo bar={a}>"hi"</foo>; upon execution the variable is evaluated and quotes are automatically added where appropriate. the preceding example would result in an xml object which looks like this: <foo bar="2">"hi"</foo>. in attribute substitution, quotation marks are escaped as &quot; while apostrophes are handled normally. var b = 'he said "don\'t...
... interpolate variables amidst other literal (or variable) attribute content, however (e.g., bar="a{var1}{var2}"). one must instead either calculate the variable with a javascript expression (e.g., bar={'a'+var1+var2}), define a new variable before the element literal which includes the full interpolation and then include that variable or retrieve the attribute after the literal to alter it (see below). while one can interpolate attribute names as well as attribute values: var a = 'att'; var b = <b {a}='value'/>; alert(b); // gives: <b att="value"/> ...one cannot interpolate a whole expression at once (e.g., <b {a}>.) after executing the above example, the variable languages references an xml object corresponding to the <languages> node in the xml document. this node has one attribute, ty...
...ength()); // 4 while the . operator accesses direct children of the given node, the .. operator accesses all children no matter how deeply nested: alert(person..*.length()); // 11 the length() method here returns 11 because both elements and text nodes are included in the resulting xmllist. ...
...And 5 more matches
XForms Input Element - Archive of obsolete content
e xforms processor as to which type of widget(s) to use to represent this control accesskey - used to specify the keyboard shortcut for focusing this control single-node binding special inputmode - not supported for this control incremental - supported. the default value is 'false'. ...
... the default value is 'false'. mozilla extensions labelposition - only for boolean types: show the label before or after the checkbox (see below) type restrictions the input element can be bound to a node containing simple content of any data type except xsd:base64binary, xsd:hexbinray or any data type derived from these. representations the xforms input element can be represented by the following widgets for the spcified data types (or types derived from these data types): text field - the default widget when no type is specified or the data is of type xsd:string (xhtml/xul) checkbox - used for xsd:boolean instance data. (xhtml/xul) datepicker - used to represent data of type xsd:date (xhtml/xul) calendar - used to represent data of type xsd:date when appearance attribute also has the...
...characteristics a text field is presented to the user when there is no type given for the bound node or a type is specified that is not handled by one of ...
...And 5 more matches
Using the Right Markup to Invoke Plugins - Archive of obsolete content
this is, in fact, the unique identifier of macromedia's flash plugin, and developers are expected to know such unique identifiers in order to invoke the component of their choice. the codebase attribute used above points to a location that houses the cab file containing the activex control...
...e this won't work in mozilla-based browsers such as netscape 7. furthermore, ie's use of the codebase attribute as an obtainment mechanism itself is not strictly correct according to the html 4.01 specification, which says that the codebase attribute should be used to qualify urns referenced by the data, archive, and classid attributes. future netscape browsers based on mozilla source code will allow the use of a special param element to specify where to get plugins that are not present, but this feature is not available in netscape 7. this feature is discussed in mozilla bug 167601. ie doesn't display nested object elements correctly according to the html 4.01 specification. according to the specification, you can nest elements and browsers should stop if they can display the outermost e...
...scussed in mozilla bug 167601. ie doesn't display nested object elements correctly according to the html 4.01 specification. according to the specification, you can nest elements and browsers should stop if they can display the outermost element, or else keep going inwards till they can find something to display. ie displays everything as if they are in series, and not nested. ...
...And 5 more matches
Audio for Web games - Game development
of differences between desktop and mobile browsers that may have caused browser vendors to make choices that can make web audio difficult for game developers to work with. let's look at these now. autoplay browser autoplay policy now affects desktop and mobile browsers. there is further information about it here from the google developers site. it is worth noting that autoplay with sound is allowed if: the user has interacted with the domain. on mobile 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 usua...
...nt to play a part of it; for this reason it is useful to include a moment of silence at the end of your audio sample. jumping to, playing, and then pausing that silence will mean we can now use javascript to play that file at arbitrary points. you can find out more about best practises with the autoplay policy here. note: playing part of your file at zero volume could also work if the browser allows you to change volume (see below). also note that playing and immediately pausing your audio does not guarantee that a small piece of audio won't be played. note: adding a web app to your mobile's homescreen may change its capabilities. in the case of autoplay on ios, this appears to be the case currently. if possible, you should try your code on several devices and platforms to see how it wor...
... }, false); } myaudio.addeventlistener('timeupdate', function() { if (this.currenttime > stoptime) { this.pause(); } }, false); note: you can try out our audio sprite player live on 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 ...
...And 5 more matches
Efficient animation for web games - Game development
it is worth documenting some of these things, as there is evidence to suggest (in popular and widely-used ui libraries, for example) that they aren’t necessarily common knowledge. ...
...it is worth documenting some of these things, as there is evidence to suggest (in popular and widely-used ui libraries, for example) that they aren’t necessarily common knowledge. first off, let us discuss some basic ideas. ...
... to move something from off-screen so that it is fully visible on-screen, the browser knows that the related content will end up completely visible to the user and can then pre-render that content. when you animate position with javascript, the browser cannot easily make that same assumption, and so you might end up causing it to draw only the newly-exposed region of content, which may introduce slow-down. there are signals at the beginning and end of animations that allow you to attach javascript callbacks and form a rudimentary form of synchronisation (though there are no guarantees on how promptly these callbacks will happen). speaking of the assumptions that the browser can make, you should avoid causing it to have to re-layout during animations. in this vein, it is worth trying to stick...
...And 5 more matches
2D maze game with device orientation - Game development
rectory: img: all the images that we will use in the game. src: the javascript files with all the source code of the game defined inside. audio: the sound files used in the game. setting up the canvas we will be rendering our game on canvas, but we won't do it manually — this will be taken care of by the framework. ...
...src: the javascript files with all the source code of the game defined inside. audio: the sound files used in the game. setting up the canvas we will be rendering our game on canvas, but we won't do it manually — 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. ...
...ht='480'></canvas> the important thing to remember is that the framework is setting up helpful methods to speed up a lot of things like image manipulation or assets management, which would be a lot harder to do manually. note: you can read the building monster wants candy article for the in-depth introduction to the basic phaser-specific functions and methods. back to game states: the line below is adding a new state called boot to the game: game.state.add('boot', ball.boot); the first value is the name of the state and the second one is the object we want to assign to it. the start method is starting the given state and making it active. let's see what the states are actually. managing game states the states in phaser are separate parts of the game logic; in our case we’re loading...
...And 5 more matches
Mobile accessibility - Learn web development
etect usage of mobile devices and serve them a separate mobile domain). these days, mobile devices can usually handle fully-featured websites, and the main platforms even have screenreaders built in to enable visually impaired users to use them successfully. modern mobile browsers tend to have good support for wai-aria, too. to make a website accessible and usable on mobile, you just need to follow general good web design and accessibility 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 m...
... what phone model and android version you have, and then look up where the talkback menu is. it tends to differ widely between android versions and even between different phone models. some phone manufacturers (e.g. samsung) don't even have talkback in newer phones, and instead opted for their own screen reader. when you've found the talkback menu, press the slider switch to turn talkback on. follow any additional on-screen prompts that you are presented with. when talkback is turned on, your android device's basic controls will be a bit different. for example: single-tapping an app will select it, and the device will read out what the app is. swiping left and right will move between apps, or buttons/controls if you are in a control bar. the device will read out each option. double-tap...
... turned on, unlocking the phone is a bit different. you can do a two-finger swipe up from the bottom of the lock screen. if you've set a passcode or pattern for unlocking your device, you will then be taken to the relevant entry screen to enter it. you can also explore by touch to find the unlock button at the bottom middle of the screen, and then double-tap. global and local menus talkback allows you to access global and local context menus, wherever you have navigated to on the device. the former provides global options relating to the device as a whole, and the latter provides options relating just to the current app/screen you are in. to get to these menus: access the global menu by quickly swiping down, and then right. access the local menu by quickly swiping up, and then right.
...And 5 more matches
Organizing your CSS - Learn web development
t 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 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: ...
...omment it can be broken onto multiple lines. */ a good tip is to add a block of comments between logical sections in your stylesheet too, to help locate different sections quickly when scanning through, or even give you something to search for to jump right into that part of the css. if you use a string which won't appear in the code you can jump from section to section by searching for it — below we have used ||. /* || general styles */ ... /* || typography */ ... /* || header and main navigation */ ... you don't need to comment every single thing in your css, as much of it will be self-explanatory. what you should comment are the things where you made a particular decision for a reason. you may have used a css property in a specific way to get around older browser incompatibili...
...self-explanatory. what you should comment are the things where you made a particular decision for a reason. you may have used a css property in a specific way to get around older browser incompatibilities, for example: .box { background-color: red; /* fallback for older browsers that don't support gradients */ background-image: linear-gradient(to right, #ff0000, #aa0000); } perhaps you followed a tutorial to achieve something, and the css is a little non-obvious. in that case you could add the url of the tutorial to the comments. you will thank yourself when you come back to this project in a year or so, and can vaguely remember there was a great tutorial about that thing, but where is it? create logical sections in your stylesheet it is a good idea to have all of the common styling...
...And 5 more matches
Basic native form controls - Learn web development
all the single line text field types on github at single-line-text-fields.html (see it live also). here is a basic single line text field example: <input type="text" id="comment" name="comment" value="i'm a text field"> single line text fields have only one true constraint: if you type text with line breaks, the browser removes those line breaks before sending the data to the server. the following screenshot shows default, focused and disabled text input types in firefox 71 and safari on macos and in chrome 79 and edge 18 on windows 10. note: html5 enhanced the basic original single line text field by adding special values for the type attribute that enforce specific validation constraints and other features, for example specific to entering urls or numbers. we'll cover those in the...
...bove for structural examples. check box a check box is created using the <input> element with a type attribute set to the value checkbox. <input type="checkbox" id="carrots" name="carrots" value="carrots" checked> including the checked attribute makes the checkbox checked automatically when the page loads. clicking the checkbox or its associated label toggles the checkbox on and off. the following screenshots show default, focused and disabled checkboxes in firefox 71 and safari 13 on macos and chrome 79 and edge 18 on windows 10: note: any checkboxes and radio buttons with the checked attribute on load match the :default pseudo class, even if they are no longer checked. any that are currently checked match the :checked pseudoclass. due to the on-off nature of checkboxes, the chec...
... actual buttons the radio button isn't actually a button, despite its name; let's move on and look at actual buttons! there are three input types that produce buttons: submit...
...And 5 more matches
Your first form - Learn web development
prerequisites: basic computer literacy, and a basic understanding of html. objective: to gain familiarity with what web forms are, what they are used for, how to think about designing them, and the basic html elements you'll need for simple cases. what are web forms? web forms are one of the main points of interaction between a user and a web site or application. forms allow users to enter data, which is generally sent to a web server for processing and storage (see sending form data later in the module), or used on the client-side to immediately update the interface in some way (for example, add another item to a list, or show or hide a ui feature). a web form's html is made up of one or more form controls (sometimes called widgets), plus some additional elements t...
...portant to remember that the bigger your form, the more you risk frustrating people and losing users. keep it simple and stay focused: ask only for the data you absolutely need. designing forms is an important step when you are building a site or application. it's beyond the scope of this article to cover the user experience of forms, but if you want to dig into that topic you should read the following articles: smashing magazine has some good articles about forms ux, including an older but still relevant extensive guide to web form usability article. uxmatters is also a very thoughtful resource with good advice from basic best practices to complex concerns such as multi-page forms. in this article, we'll build a simple contact form. let's make a rough sketch. our form will contain ...
... this article, we'll build a simple contact form. let's make a rough sketch. our form will contain three text fields and one button. we are asking the user for their name, their e-mail and the message they want to send. hitting the button will send their data to a web server. active learning: implementing our form html ok, let's have a go at creating the html for our form. we will use the following html elements: <form>, <label>, <input>, <textarea>, and <button>. before you go any further, make a local copy of our simple html template — you'll enter your form html into here. the <form> element all forms start with a <form> element, like this: <form action="/my-handling-form-page" method="post"> </form> this element formally defines a form. it's a container element like a <sectio...
...And 5 more matches
Advanced text formatting - Learn web development
to have a single term with multiple descriptions, for example: <dl> <dt>aside</dt> <dd>in drama, where a character shares a comment only with the audience for humorous or dramatic effect. this is usually a feeling, thought, or piece of additional background information.</dd> <dd>in writing, a section of content that is related to the current topic, but doesn't fit directly into the main flow of content so is presented nearby (often in a box off to the side.)</dd> </dl> active learning: marking up a set of definitions it's time to try your hand at description 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 res...
...otations; which element you use depends on whether you are marking up a block or inline quotation. blockquotes if a section of block level content (be it a paragraph, multiple paragraphs, a list, etc.) is quoted from somewhere else, you should wrap it inside a <blockquote> element to signify this, and include a url pointing to the source of the quote inside a cite attribute. ...
...lude a url pointing to the source of the quote inside a cite attribute. ...
...And 5 more matches
Introducing asynchronous JavaScript - Learn web development
e different asynchronous techniques you'll encounter, showing how they can help us solve such problems. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to gain familiarity with what asynchronous javascript is, how it differs from synchronous javascript, and what use cases it has. synchronous javascript to allow us to understand what asynchronous javascript is, we ought to start off by making sure we understand what synchronous javascript is. this section recaps some of the information we saw in the previous article. a lot of the functionality we have looked at in previous learning area modules is synchronous — you run some code, and the result is returned as soon as the browser can do so. let's look ...
...e from an external device, such as fetching a file from the network, accessing a database and returning data from it, accessing a video stream from a web cam, or broadcasting the display to a vr headset. why is this difficult to get to work using synchronous code? let's look at a quick example. when you fetch an image from a server, you can't return the result immediately. that means that the following (pseudocode) wouldn't work: let response = fetch('myimage.png'); let blob = response.blob(); // display your image blob in the ui somehow that's because you don't know how long the image will take to download, so when you come to run the second line it will throw an error (possibly intermittently, possibly every time) because the response is not yet available. instead, you need your code to ...
...me to run the second line it will throw an error (possibly intermittently, possibly every time) because the response is not yet available. instead, you need your code to wait until the response is returned before it tries to do anything else to it. there are two main types of asynchronous code style you'll come across in javascript code, old-style callbacks and newer promise-style code. in the below sections we'll review each of these in turn. async callbacks async callbacks are functions that are specified as arguments when calling a function which will start executing code in the background. when the background code finishes running, it calls the callback function to let you know the work is done, or to let you know that something of interest has happened. using callbacks is slightly old...
...And 5 more matches
Function return values - Learn web development
previous overview: building blocks next there's one last essential concept about functions for us to discuss — return values. some functions don't return a significant value, but others do. it's important to understand what their values are, how to use them in your code, and how to make functions return useful values. we'll cover all of these below. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps, functions — reusable blocks of code. objective: to understand function return values, and how to make use of them. what are return values? return values are just what they sound like — the values that a function returns when it has completed. you've already met return values a number of t...
... calls are made to the random() function, to generate a random value for the current circle's x-coordinate, y-coordinate, and radius, respectively. the random() function takes one parameter — a whole number — and it returns a whole random number between 0 and that number. ...
...lows: function random(number) { const result = math.floor(math.random() * number); return result; } but the first version is quicker to write, and more compact. we are returning the result of the calculation math.floor(math.random() * number) each time the function is called. this return value appears at the point the function was called, and the code continues. so when you execute the following: ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); if the three random() calls returned the values 500, 200, and 35, respectively, the line would actually be run as if it were this: ctx.arc(500, 200, 35, 0, 2 * math.pi); the function calls on the line are run first, and their return values substituted for the function calls, before the line itself is then executed. activ...
...And 5 more matches
JavaScript object basics - Learn web development
tains very little — a <script> element for us to write our source code into. we'll use this as a basis for exploring basic object syntax. while working with this example you should have your developer tools javascript console open and ready to type in some commands. as with many things in javascript, creating an object often begins with defining and initializing a variable. try entering the following line below the javascript code that's already in your file, then saving and refreshing: const person = {}; now open your browser's javascript console, enter person into it, and press enter/return. you should get a result similar to one of the below lines: [object object] object { } { } congratulations, you've just created your first object. job done! but this is an empty object, so we can...
...{ name: ['bob', 'smith'], age: 32, gender: 'male', interests: ['music', 'skiing'], bio: function() { alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. ...
......
...And 5 more matches
Object prototypes - Learn web development
es available just on the object() constructor itself. note: this seems strange — how can you have a method defined on a constructor, which is itself a function? well, a function is also a type of object. see the function() constructor reference if you don't believe us. ...
...erence if you don't believe us. you can check out existing prototype properties for yourself — go back to our previous example and try entering the following into the javascript console: person.prototype the output won't show you very much because we haven't defined anything on our custom constructor's prototype! by default, a constructor's prototype always starts empty. now try the following: object.prototype you'll see a large number of methods defined on object's prototype property, which are then available on objects that inherit from object, as shown earlier. you'll see other examples of prototype chain inheritance all over javascript — try looking for the methods and properties defined on the prototype of the string, date, number, and array global objects, for exampl...
... on we showed how the object.create() method can be used to create a new object instance. for example, try this in your previous example's javascript console: let person2 = object.create(person1); what create() actually does is to create a new object from a specified prototype object. here, person2 is being created using person1 as a prototype object. you can check this by entering the following in the console: person2.__proto__ this will return the person1 object. the constructor property every constructor function has a prototype property whose value is an object containing a constructor property. this constructor property points to the original constructor function. as you will see in the next section, properties defined on the person.prototype property (or in general on a...
...And 5 more matches
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. ...
... image formats, their impact on performance, and how to reduce the impact of images on overall page load time. this is a high-level introduction to optimizing multimedia delivery on the web, covering general principles and techniques. for a more in-depth guide, see https://images.guide. why optimize your multimedia? for the average website, 51% of its bandwidth comes from imagery, followed by video at 25%, so it's safe to say it's important to address and optimize your multi-media content. you need to be considerate of data usage. many people are on capped data plans or even pay-as-you-go where they are literally paying by the megabyte. this isn't an emerging market problem either. as of 2018, 24% of the united kingdom still use pay-as-you-go. you also need to be considerate of...
...-you-go. you also need to be considerate of memory as many mobile devices have limited ram. it's important to remember that when images are downloaded, they need to be stored in memory. optimizing image delivery despite being the largest consumer of bandwidth, images load asynchronously so the visitor can see the page as they download and therefore, their impact on perceived performance is far lower than many expect. however, images are mostly used for content, so it's important that a visitor can see them as soon as possible for a good experience. loading strategy one of the biggest improvements to most websites is lazy-loading images beneath-the-fold, rather than downloading them all on initial page load regardless of whether a visitor scrolls to see them or not. many javascript librar...
...And 5 more matches
Website security - Learn web development
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 cookie, they can log into a site as though they were the user and do anything the user can, such as access their ...
...s <script>, <object>, <embed>, and <link>. the process of modifying user data so that it can't be used to run scripts or otherwise affect the execution of server code is known as input sanitization. many web frameworks automatically sanitize user input from html forms by default. sql injection sql injection vulnerabilities enable malicious users to execute arbitrary sql code on a database, allowing data to be accessed, modified, or deleted irrespective of the user's permissions. a successful injection attack might spoof identities, create new identities with administration rights, access all data on the server, or destroy/modify the data to make it unusable. sql injection types include error-based sql injection, sql injection based on boolean errors, and time-based sql injection. thi...
...ew identities with administration rights, access all data on the server, or destroy/modify the data to make it unusable. sql injection types include error-based sql injection, sql injection based on boolean errors, and time-based sql injection. this vulnerability is present if user input that is passed to an underlying sql statement can change the meaning of the statement. ...
...And 5 more matches
Routing in Ember - Learn web development
y not doing any filtering in the page that we've been working with, but we will need to reorganize it a bit to handle a different view for the "active" and "completed" todos. an ember application has a default "application" route, which is tied to the app/templates/application.hbs template. ...
...completed" todos. an ember application 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". ...
...g 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 class router extends emberrouter { location = config.locationtype; rooturl = config.rooturl; } router.map(function() { this.route('completed'); this.route('active'); }); the highlighted lines were added when the 2nd and 3rd commands above were run. router.js behaves...
...And 5 more matches
Beginning our React todo list - Learn web development
this article will walk you through putting the basic app component structure and styling in place, ready for individual component definition and interactivity, which we'll add later. 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. ...
...nguages, 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 can read a list of tasks. add a task using the mouse or keyboard. mark any task as completed, using the mouse or keyboard. delete any task, using the mouse or keyboard. edit any task, using the mouse or keyboard. view a specific subset of tasks: all tasks, only the active task, or only the completed tasks. we'll tackle these stories one-by-one. pre-project hou...
... only the completed tasks. 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 c...
...And 5 more matches
Embedding API for Accessibility
accessibility community. mozilla needs to move in the direction of accessibility. here is the w3c's definition of accessibility for a user agent like mozilla. in part, being accessible means supporting a built-in accessibility apis for a platform, such as microsoft active accessibility or atk for linux and unix desktops. there are many other pieces, such as preferences to allow the user to change foreground and background colors, and font sizes. mozilla already supports some of these options. this document lays out what we already have, and what we'll need later, in the embedding api to support accessibility. text zoom on a per-window basis the nsidomwindow::gettextzoom(float *zoomfactor) and nsidomwindow::settextzoom(float zoomfactor) methods can be used to set a w...
...here are a number of prefs related to accessibility. for the most part, an automatic reframe is performed when one of these prefs is changed. a reframe fixes the appearance of the page to match the new prefs, without reloading the document over the network. ...
...e prefs in embedding, use something like the following code: #include "nsipref.h"; nsresult rv; nscomptr<nsipref> prefs(do_getservice(ns_pref_contractid, &rv)); prefs->setboolpref("bool.pref.name", pr_true /* or pr_false */); prefs->setintpref("int.pref.name", newvalue); prefs->setcharpref("string.pref.name", newcharstarvalue); to manually add a pref to your settings, add a line like the following to your prefs.js: user_pref("accessibility.browsewithcaret", true); accessibility prefs reference the following is a description of what accessibility prefs give us (or will give us), for accessibility: functionality implementation works as of images setintpref("network.image.imagebeha...
...And 5 more matches
Debugging on Windows
this document explains how to debug mozilla-derived applications such as firefox, thunderbird, and seamonkey on windows using the visual c++ ide. if vc++ and your mozilla application hang shortly after you launch the application under the debugger, see problems loading debug symbols. ...
...be able to follow child processes as they are created. firefox, in general, and even in non-e10s mode, does not start the main process directly, it starts it via a launcher process. this means that visual studio will only attach to the first process it finds, and will not hit any break-point (and even notifies you that it cannot find their location). microsoft child process debugging power tool allows automatically attaching to child processes, such as web content process, gpu process, etc. enable it by going its configuration menu in "debug > other debugging targets > child process debugging settings", and ticking the box. if you have followed the steps in building firefox for windows and have a local debug build, you can execute ./mach run --debug from the same command line. it would open ...
...ing firefox for windows and have a local debug build, you can execute ./mach run --debug from the same command line. it would open visual studio with firefox's run options configured. you can click "start" button to run firefox then, already attached in the debugger. alternatively, if you have generated the visual studio solution, via ./mach build-backend -b visualstudio, opening this solution allows you to run firefox.exe directly in the debugger. making it the startup project, by right clicking on it (it appears bold when it's the case) can be useful. breakpoints are kept across runs, this can be a good way to debug startup issues. run the program until you hit an assertion. you will get a dialog box asking if you would like to debug. hit "cancel". the msdev ide will launch and load the f...
...And 5 more matches
Creating Custom Events That Can Pass Data
(i.e., something other than the standard mouse/keyboard events) and, depending on the data passed along with this event, you want firefox to react differently. note that starting with version 6, firefox supports dom level 3 customevent, which lets you dispatch custom events with arbitrary data from javascript. (see bug 427537) requirements in order to do this you must be able to do all of the following: download mozilla source code build mozilla creating custom firefox extensions with the mozilla build system. this is the foundation for everything we'll do. what's in a name despite whatever you may have been taught in your english class, there's a lot in a name when it's an event name. as of gecko 1.8, if your event names do not start with "nsdom" and their interfaces do not start with "ns...
...but that's it. the trunk you needed to download (or check out) the trunk source because you will have to modify it in order to implement your event. be aware that this means your stuff won't work with everyone else's version of firefox unless you get your patches into the trunk. at the time of writing the author is not aware of a way to do this that doesn't involve modifications to trunk. what follows a list of the files you'll need to modify, as well as a discussion of each change. mozilla/dom/base/nsdomclassinfoclasses.h the change you make here is really rather small but it is incredibly important. if you peruse nsdomclassinfoclasses.h you'll see of list of macros of the form domci_class(foo). you'll want to add an entry to it which looks like this: domci_class({truncated name}) here's th...
...ent)). mozilla/dom/src/base/nsdomclassinfo.cpp mozilla contains many convenience macros to make changes like the one you're making easier. your modification of this file is basically just two macro calls. try to make sure of two things: keep your stuff at the back. you know never know what depends on that enum you modified keep your stuff organized. same reason as above. you need to make the following two modifications: around line 1000: ns_define_classinfo_data({truncated name}, nsdomgenericsh, dom_default_scriptable_flags) around line 2900: dom_classinfo_map_begin({truncated name}, nsidom{truncatedname}) dom_classinfo_map_entry(nsidom{truncated name}) dom_classinfo_event_map_entries dom_classinfo_map_end remember, {truncated name} is the same as above. mozilla/content/events/src...
...And 5 more matches
Storage access policy: Block cookies from trackers
ion 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. ...
... block? the storage access policy blocks resources identified as trackers from accessing their cookies and other site storage when they are loaded in a third-party context. this prevents those resources from retrieving tracking identifiers stored in cookies or site storage and using them to identify users across visits to multiple first parties. specifically, firefox does this by imposing the following restrictions: cookies: block cookie request headers and ignore set-cookie response headers. return an empty string for calls to document.cookie and ignore requests to set cookies via document.cookie. dom storage: localstorage: window.localstorage: read and write attempts throw a securityerror exception. prior to firefox 70: window.localstorage is null. thus, attempts to read and wri...
...ovide the same level of storage access, we recommend third parties switch to using the storage access api in order to guarantee their access to storage. automatic storage access upon interaction in order to improve web compatibility, firefox currently includes some heuristics to grant storage access automatically to third parties that receive user interaction. these heuristics are intended to allow some third-party integrations that are common on the web to continue to function. they are intended to be temporary and will be removed in a future version of firefox. they should not be relied upon for current and future web development. third-party storage access may be granted to resources that have been classified as tracking resources when a user gesture triggers a pop-up window that has op...
...And 5 more matches
Using the Browser API
Mozilla › Gecko › Chrome › API › Browser API › Using
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the html browser api is an extension of the html <iframe> element that allows web apps to implement browsers or browser-like applications. it was originally used in firefox os to implement browser applications before that project was cancelled; since firefox 47 it is available to desktop chrome code and used in places like the firefox devtools. it consists of two major parts: custom <iframe> attributes: by adding a mozbrowser attribute to the <iframe> element we can make it appear like a top-leve...
...isten for changes to the embedded content's state, interited by the htmliframeelement interface. note: an iframe enhanced by the browser api is commonly referred to as a "browser iframe". we'll be using this term throughout the current article, and other parts of the documentation. demo to demonstrate basic usage of this api, we have created a simple browser api demo that provides buttons allowing you to (re)load web pages, stop loading, move forward and back in history, and zoom in and out of the page. to run the demo, the best approach is to clone the github repo locally (or just download it directly if you don't do github), open webide, open the repo as a packaged app, then run it either on a simulator or a real device if you have one. in any case, you should at least download th...
...d and back in history, and zoom in and out of the page. to run the demo, the best approach is to clone the github repo locally (or just download it directly if you don't do github), open webide, open the repo as a packaged app, then run it either on a simulator or a real device if you have one. in any case, you should at least download the repo and refer to the code as you read the sections below. the html an <iframe> is turned into a browser iframe by setting the mozbrowser attribute on it: <iframe src="http://mozilla.org" mozbrowser> in addition, the <iframe> can be loaded in its own child process — separate to the page embedding this frame — by including the remote attribute. <iframe src="http://hostname.tld" mozbrowser remote> warning: this last attribute is necessary for s...
...And 5 more matches
Script security
, 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 take over the user's computer. legacy sdk extensions also run with chrome p...
...wever, javascript is a highly dynamic, malleable language, and without help it's difficult to write system-privileged code that interacts safely with untrusted web content. from the point of view of chrome code, the script security model in gecko is intended to provide that help to make writing secure, system-privileged javascript a realistic expectation. security policy gecko implements the following security policy: objects that are same-origin are able to access each other freely. for example, the objects associated with a document served from https://example.org/ can access each other, and they can also access objects served from https://example.org/foo. objects that are cross-origin get highly restricted access to each other, according to the same-origin policy. for example, code s...
...ttps://example.org/ can access each other, and they can also access objects served from https://example.org/foo. objects that are cross-origin get highly restricted access to each other, according to the same-origin policy. for example, code served from https://example.org/ trying to access objects from https://somewhere-else.org/ will have restricted access. objects in a privileged scope are allowed complete access to objects in a less privileged scope, but by default they see a restricted view of such objects, designed to prevent them from being tricked by the untrusted code. an example of this scope is chrome-privileged javascript accessing web content. objects in a less privileged scope don't get any access to objects in a more privileged scope, unless the more privileged scope explici...
...And 5 more matches
Sqlite.jsm
sqlite.jsm will create, manage, and destroy statement instances for you. you don't need to worry about caching created statement instances, destroying them when you are done, etc. this translates to fewer lines of code to talk to sqlite. all operations are asynchronous. use of synchronous storage apis is discouraged because they block the main thread. all the functionality in sqlite.jsm is asynchronous. ...
...ite.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. sqlite.jsm feels like a pure javascript module. the complexities of xpcom are mostly hidden from view. javascript programmers should feel right at home...
...ectory. if the path does not exist, a new sqlite database will be created. the value typically ends with .sqlite. 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...
...And 5 more matches
Localizing extension descriptions
this article provides details on how to go about localizing the descriptions of mozilla add-ons, as well as for other metadata about your add-on. because a new method for doing so was implemented in gecko 1.9 (firefox 3), there are two sets of instructions below. localizing in gecko 1.9 gecko 1.9 includes a new, more robust method for localizing add-on descriptions and other metadata. all of the different descriptions now appear in the install.rdf file using em:localized properties. ...
...structions below. localizing in gecko 1.9 gecko 1.9 includes a new, more robust method for localizing add-on descriptions and other metadata. all of the different descriptions now appear in the install.rdf file using em:localized properties. each has at least one em:locale property marking the locale that the information should be used for and then all the various strings for the locale. ...
... if we have inexact matches then use the one ...
...And 5 more matches
Localizing with Mercurial
in mozilla, we use the the mercurial version control system (hg) to manage our source code and localizations. mercurial allows localizers to work locally (on their machines) and then push (an hg term) changes to a remote repository, which usually is hosted on the mozilla servers (hg.mozilla.org). localizing current versions of firefox, thunderbird and seamonkey includes working with mercurial. if the documentation is incomplete or you have questions, please drop by the #l10n or #hg channels on irc.mozilla.org. the mercurial faq are also worth a read, should you run into trouble. ...
...remote repository, which usually is hosted on the mozilla servers (hg.mozilla.org). localizing current versions of firefox, thunderbird and seamonkey includes working with mercurial. if the documentation is incomplete or you have questions, please drop by the #l10n or #hg channels on irc.mozilla.org. the mercurial faq are also worth a read, should you run into trouble. for the eager and quick, below you'll find instructions on installing and configuring mercurial, instructions on receiving an hg account commit priviledges, as well as a few tasks you can complete without account priviledges. installing mercurial follow the instructions below to install mercurial on your system. once you've installed mercurial, we'll walk through the steps to configure it. mercurial on linux you can easily...
...choose the appropriate command for your distribution and make sure to run as root. ...
...And 5 more matches
NSS Certificate Download Specification
in: this is a single pkcs#7 signeddata object. the only significant field in the signeddata object is the certificates field, which may contain multiple certificates to be imported together. the contents of the version, digestalgorithms, contentinfo, crls, and signerinfos fields are ignored. ...
...te sequence: this is another pkcs#7 object format, and like the signeddata format, it allows multiple certificates to be imported together. this format is simpler than the pkcs#7 signeddata object format. it consists of a pkcs#7 contentinfo structure, wrapping a sequence of certificates. the contenttype field oid must be netscape-cert-sequence (see object identifiers). the content field is the following asn.1 structure: certificatesequence ::= sequence of certificate see the section below on certificate chains for more information about how multiple certificates are handled. text formats any of the above binary formats can also be imported in text form. ...
... field oid must be netscape-cert-sequence (see object identifiers). the content field is the following asn.1 structure: certificatesequence ::= sequence of certificate see the section below on certificate chains for more information about how multiple certificates are handled. text formats any of the above binary formats can also be imported in text form. the text form begins with the following line: -----begin certificate----- following this line should be the certificate data, which can be in any of the binary formats described above. this data must be base64 encoded as described by rfc 1113. ...
...And 5 more matches
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...
...directories: include - nss header files lib - nss shared libraries bin - nss tools and test programs you also need to download the nspr 4.7.1 binary distributions to get the nspr 4.7.1 header files and shared libraries, which nss 3.12 requires. nspr 4.7.1 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.7.1/. ...
...ithmid (see cryptohi.h) new macros for camellia support (see blapit.h): nss_camellia nss_camellia_cbc camellia_block_size new macros for rsa (see blapit.h): rsa_max_modulus_bits rsa_max_exponent_bits new macros in certt.h: x.509 v3 ku_encipher_only cert_max_serial_number_bytes cert_max_dn_bytes pkix cert_rev_m_do_not_test_using_this_method cert_rev_m_test_using_this_method cert_rev_m_allow_network_fetching cert_rev_m_forbid_network_fetching cert_rev_m_allow_implicit_default_source cert_rev_m_ignore_implicit_default_source cert_rev_m_skip_test_on_missing_source cert_rev_m_require_info_on_missing_source cert_rev_m_ignore_missing_fresh_info cert_rev_m_fail_on_missing_fresh_info cert_rev_m_stop_testing_on_fresh_info cert_rev_m_continue_testing_on_fresh_info cert_rev_mi_test_each_method...
...And 5 more matches
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. ...
... 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. ...
...plantation on gpl/lgpl compatibility, see security/nss/copying in the source code. export and des cipher suites are disabled by default. non-ecc aes and triple des cipher suites are enabled by default. nss 3.14 source tarballs can be downloaded from https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/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 ...
...And 5 more matches
NSS 3.35 release notes
equires 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. for the sslsignaturescheme enum, the enumerated values ssl_sig_rsa_pss_sha* are deprecated in response to a change in tls 1.3. please use the equivalent ssl_sig_rsa_pss_rsae_sha* for rsaencryption keys, or ssl_sig_rsa_pss_pss_sha* for pss keys. note that this release does not include support f...
...ha* are deprecated in response to a change in tls 1.3. please use the equivalent ssl_sig_rsa_pss_rsae_sha* for rsaencryption keys, or ssl_sig_rsa_pss_pss_sha* for pss keys. note that this release does not include support for the latter. notable changes in nss 3.35 previously, nss used the dbm file format by default. starting with version 3.35, nss uses the sql file format by default. below, are explanations that could be helpful for environments that need to adopt to the new default. if nss is initialized, in read-write mode with a database directory provided, it uses database files to store certificates, key, trust, and other information. nss supports two different database file formats: dbm: the legacy file format, based on berkeley db, using filenames cert8.db, k...
...oject page: https://fedoraproject.org/wiki/changes/nssdefaultfileformatsql 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. ...
...And 5 more matches
NSS functions
hould no longer be used. updated - function has new arguments such as new flag or addition to structure. ssl functions the public functions listed here are used to configure sockets for communication via the ssl and tls protocols. in addition to the functions listed here, applications that support ssl use some of the certificate functions, crypto functions, and utility functions described below on this page. other sources of information: the nss_reference documents the functions most commonly used by applications to support ssl. the nss home page links to additional ssl documentation. if documentation is available for a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (mxr) link for e...
...each function name is linked to its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to...
...each function name is linked to its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. ...
...And 5 more matches
certutil
nss databases (cert8.db and key3.db) into the newer sqlite databases (cert9.db and key4.db). --upgrade-merge upgrade an old database and merge it into a new database. this is used to migrate legacy nss databases (cert8.db and key3.db) into the newer sqlite databases (cert9.db and key4.db). arguments option arguments modify an action and are lowercase. -a use ascii format or allow the use of ascii format for input or output. this formatting follows rfc 1113. for certificate requests, ascii output defaults to standard output unless redirected. -b validity-time specify a time at which a certificate is required to be valid. use when checking certificate validity wit...
... specifying seconds (ss) is optional. when specifying an explicit time, use a z at the end of the term, yymmddhhmmssz, to close it. when specifying an offset time, use yymmddhhmmss+hhmm or yymmddhhmmss-hhmm for adding or subtracting time, respectively. ...
...icate 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 string "internal". an internal slots is a virtual slot maintained in software, rather than a hardware device. internal slot 2 is ...
...And 5 more matches
NSS tools : signtool
ve] description the signing tool, signtool, creates digital signatures and uses a java archive (jar) file to associate the signatures with files in a directory. electronic software distribution over any network involves potential security problems. to help address some of these problems, you can associate digital signatures with the files in a jar archive. digital signatures allow ssl-enabled clients to perform two important operations: * confirm the identity of the individual, company, or other entity whose digital signature is associated with the files * check whether the files have been tampered with since being signed if you have a signing certificate, you can use netscape signing tool to digitally sign files and package them as a jar file. an object-...
... confirm the identity of the individual, company, or other entity whose digital signature is associated with the files * check whether the files have been tampered with since being signed if you have a signing certificate, you can use netscape signing tool to digitally sign files and package them as a jar file. an object-signing 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 additio...
...file. for more information about the syntax used with this file, see "tips and techniques". -i scriptname specifies the name of an installer script for smartupdate. this script installs files from the jar archive in the local system after smartupdate has validated the digital signature. for more details, see the description of -m that follows. the -i option provides a straightforward way to provide this information if you don't need to specify any metadata other than an installer script. -j directory specifies a special javascript directory. this option causes the specified directory to be signed and tags its entries as inline javascript. this special type of entry does not ...
...And 5 more matches
JS::CompileOptions
e 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. version jsversion javascript version used to compile the script. ...
...t 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 that script errors should be sanitized ("muted") wh...
...filename of the file which introduces the file. const char16_t *sourcemapurl() const returns the url of the source map. methods of js::owningcompileoptions method description jsobject *element() const returns the dom element to which this source code belongs, if any, or null if it belongs to no dom element. source belongs to a dom element in the following cases: source belongs to a <script> element if it is the element's text content (that is, it is written out as the body of the <script> element in the markup text), or is the source document referenced by its src attribute. source belongs to a dom element if it is an event handler content attribute (that is, if it is written out in the markup text as an attribute value). s...
...And 5 more matches
SpiderMonkey 1.8.5
f spidermonkey 1.8.5. you can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/js185-1.0.0.tar.gz (md5 checksum: a4574365938222adca0a6bd33329cb32). spidermonkey 1.8.5 is the javascript engine that shipped in firefox 4.0. it is much faster than spidermonkey 1.8, implements es-5 (ecma 262, 5th edition), and contains many new language and api features, described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. or, file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. —22 march 2011 platform support spidermonkey 1.8.5 is supported on all the platforms where firefox 4 runs. spidermonkey 1.8.5 includes a just-in-time compiler (jit) (several, actually) tha...
...rmonkey 1.8.5 includes a just-in-time compiler (jit) (several, actually) that compiles javascript to machine code, for a significant speed increase. it is supported only on x86, x86_64 and arm architectures. on other platforms, the jit is simply disabled; javascript code runs in an interpreter, as in previous versions. it's the same language, just not as fast. migrating to spidermonkey 1.8 the following features in earlier versions of spidermonkey have been dropped. support for extended class methods (in particular, jsequalityop) has been removed. multithreaded js programs that race against the same objects are now explicitly not supported. multithreaded programs are allowed, but each thread must operate on objects in a separate compartment, isolated from the other threads. the old build ...
...same names and do the same things. applications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. here is a list of the most significant changes. previous versions of spidermonkey supported two types of native functions: jsnative and jsfastnative. all support for the slow native function type has been removed, and the fast signature has been renamed to jsnative. embeddings that defined jsnatives in previous versions must update all those functions to the new signature. getters and setters of type jspropertyop took an id parameter of type jsval. the type of the parameter has been changed to jsid. many getters and setters simply ignore the id anyway; if the value i...
...And 5 more matches
SpiderMonkey 1.8.7
f spidermonkey 1.8.5. you can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/js185-1.0.0.tar.gz (md5 checksum: a4574365938222adca0a6bd33329cb32). spidermonkey 1.8.5 is the javascript engine that shipped in firefox 4.0. it is much faster than spidermonkey 1.8, implements es-5 (ecma 262, 5th edition), and contains many new language and api features, described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. or, file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. —22 march 2011 platform support spidermonkey 1.8.7 is supported on all the platforms where firefox 10 runs. spidermonkey 1.8.7 includes type inference, which boosts the speed of the jäger...
...t has been removed. the jit is supported only on x86, x86_64 and arm architectures. on other platforms, the jit is simply disabled; javascript code runs in an interpreter, as in previous versions. it's the same language, just not as fast. migrating to spidermonkey 1.8.7 this covers migrating from version 1.8.5. see the 1.8.5 release notes for information on migrating from earlier versions. the following features in earlier versions of spidermonkey have been dropped. xxx is there anything here? spidermonkey 1.8.7 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types, functions, and callback signatures have changed, though most of them still have the same names and do the same things. applications will need significant changes, but most of those ...
...changed, though most of them still have the same names and do the same things. applications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. here is a list of the most significant changes. xxx is there anything here? these and other changes are explained in detail below. new javascript language features xxx needs updating 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 between es5 and and es3, the version of ecmascript supported by spidermonkey versions 1.5 through 1.8. these are discussed in annex e of the es5 specification.
...And 5 more matches
Animated PNG graphics
Mozilla › Tech › APNG
ha components are all set to zero. for purposes of chunk descriptions, an unsigned int shall be a 32-bit unsigned integer in network byte order limited to the range 0 to (2^32)-1; an unsigned short shall be a 16-bit unsigned integer in network byte order with the range 0 to (2^16)-1; and a byte shall be an 8-bit unsigned integer with the range 0 to (2^8)-1. error handling apng is designed to allow incremental display of frames before the entire image has been read. this implies that some errors may not be detected until partway through the animation. it is strongly recommended that when any error is encountered decoders should discard all subsequent frames, stop the animation, and revert to displaying the default image. a decoder which detects an error before the animation has started shou...
...y the default image. an error message may be displayed to the user if appropriate. structure an apng stream is a normal png stream as defined in the png specification, with three additional chunk types describing the animation and providing additional frame data. to be recognized as an apng, an 'actl' chunk must appear in the stream before any 'idat' chunks. the 'actl' structure is described below. conceptually, at the beginning of each play the output buffer must be completely initialized to a fully transparent black rectangle, with width and height dimensions from the 'ihdr' chunk. the default image may be included as the first frame of the animation by the presence of a single 'fctl' chunk before 'idat'. otherwise, the default image is not part of the animation. subsequent frames are...
...ation by the presence of a single 'fctl' chunk before 'idat'. otherwise, the default image is not part of the animation. subsequent frames are encoded in 'fdat' chunks, which have the same structure as 'idat' chunks, except preceded by a sequence number. information for each frame about placement and rendering is stored in 'fctl' chunks. the full layout of 'fdat' and 'fctl' chunks is described below. the boundaries of the entire animation are specified by the width and height parameters of the png 'ihdr' chunk, regardless of whether the default image is part of the animation. the default image should be appropriately padded with fully transparent pixels if extra space will be needed for later frames. each frame is identical for each play, therefore it is safe for applications to cache the ...
...And 5 more matches
Using XPCOM Components
onent behind the scenes. the cookie manager dialog shows user interface[cookie-manager-ui] that is presented to the user in mozilla for working with the cookiemanager component. the cookie manager dialog this dialog is written in xul and javascript, and uses a part of xpcom called xpconnect to seamlessly connect to the cookiemanager component (see connecting to components from the interface below). xul is just one way to expose the functionality of the cookiemanager component-but it's a particularly useful one in the mozilla world. the functionality of the cookiemanager component is available through the nsicookiemanager interface, which is comprised of the public methods in the table below. the nsicookiemanager interface removeall remove all cookies from the cookie list. ...
... c<deletedcookies.length; c++) { cmgr.remove(deletedcookies[c].host, deletedcookies[c].name, deletedcookies[c].path); } deletedcookies.length = 0; } connecting to components from the interface the mozilla user interface uses javascript that has been given access to xpcom components in the application core with a technology called xpconnect. xpconnect allows interface methods defined via xpidl to be called from javascript, as part of javascript objects that represent instances of components like the cookiemanager. xpconnect is what binds the application code to the user interface of the mozilla browser, to other gecko-based xul, and to javascript environments like xpcshell, which is a command-line javascript interpreter and xpcom tool is built with...
...ll-defined. scriptability, this ability to get and use xpcom components from javascript and other languages for which xpconnect bindings have been created, is a core feature of xpcom. the webbrowserfind component components are used all over - in high-level browser-like functionality such as nswebbrowserfind, which provides find() and findnext() methods for finding content in web pages, and in low-level tasks such as the manipulation of data. though not every api in mozilla is or should be "xpcomified", much if not all of the typical functionality that browsers provide is available in components that can be reused via browser extensions and/or gecko embedders. in addition to the cookiemanager component, for example, the webbrowserfind component is another part of a large set of web browsi...
...And 5 more matches
nsIMemory
locate 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 allocated (because of an out-of-memory condition), null ...
...n 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: this method was deprecated in gecko 2.0. if you need to monitor low memory conditions, you should watch for the low memory notifications "memory-pressure" notifications instead. boolean islowmemory(); parameters none. re...
...otherwise false. note: from gecko 2.0 always returns false. see bug 592308. realloc() reallocates a block of memory to a new size. voidptr realloc( in voidptr ptr, in size_t newsize ); parameters ptr the address of the memory block to reallocate. this may be null, in which case realloc behaves like alloc(). ...
...And 5 more matches
Performance
mozstorage uses sqlite as the database backend. it has generally good performance for a small embedded database. however, many things cause various database operations to be slow. transactions there is overhead associated with each transaction. when you execute a sql statement in isolation, an implicit transaction is created around that statement. when transactions are committed, sqlite does journaling which requires syncing data to disk. this operation is extremely slow. therefore, if you are doing many transactions in a row, you will get significant performance improvements by surrounding them in a transaction. the asynchronous writes discussed below removes most of the immediate penalty of a commit, so you will not notice the problem as much. however, there is still overhead, and u...
...queries careful reordering of the sql statement, or creating the proper indices, can often improve performance. ...
...queries careful reordering of the sql statement, or creating the proper indices, can often improve performance. ...
...And 5 more matches
XUL Overlays
Mozilla › Tech › XUL › Overlays
nuitem name="super stream player"/> <menupopup name="ss favorites"> <menuitem name="wave" src="mavericks.ssp"/> <menuitem name="soccer" src="brazil_soccer.ssp"/> </menupopup> <titledbutton id="ssp" crop="right" flex="1" value="&ssbutton.label;" onclick="firessp()"/> overlays and id attributes bases and overlays are merged when they share the same id attribute. ...
...="1" value="&ssbutton.label;" onclick="firessp()"/> overlays and id attributes bases and overlays are merged when they share the same id attribute. thus, given the following base: ... <menu id="file-menu"> <menupopup id="menu_filepopup"> <menuitem name="new"/> <menuitem name="open"/> <menuitem name="save"/> <menuitem name="close"/> </menupopup> </menu> ... and given the following overlay: <?xml version="1.0"?> <overlay id="singleitemex" xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <menupopup id="menu_filepopup"> <menu id="file_menu"> <menuitem name="super stream player"/> </menu> </menupopup> </overlay> the result will be: ... <menu id="file-menu"> <menupopup id="menu_filepo...
...end to make it available every time the base file is loaded. since one of the main purposes of overlays is to provide ui for additions or components to the basic package, explicit loading can be somewhat problematic when the overlay defines optional ui elements. loading overlays explicitly a processing instruction is used to load overlay files explicitly into the master document. ...
...And 5 more matches
Address Book examples
rd form, then you can delete it in the same way as per deleting a contact. if you have it in its nsiabdirectory form, then you can delete it like this: var abmanager = components.classes["@mozilla.org/abmanager;1"] .createinstance(components.interfaces.nsiabmanager); abmanager.deleteaddressbook(maillist.uri); how do i display properties dialogs to the user? in the following examples: selectedab is the uri of an address book to default the dialog to saving the card in. this may be blank if not required. aburi and card are the uri of the address book and the card contained within that address book. new contact dialog window.opendialog("chrome://messenger/content/addressbook/abnewcarddialog.xul", "", "chrome,resizable=no,ti...
...og("chrome://messenger/content/addressbook/abeditlistdialog.xul", "", "chrome,resizable=no,titlebar,modal,centerscreen", {abcard:abcard, listuri:listuri}); new address book dialog unlike the edit address book dialog, the new address book dialog does not currently have the facility to get the chrome uri based on the address book type. the following options are available. for local (mork) address books: window.opendialog( "chrome://messenger/content/addressbook/abaddressbooknamedialog.xul", "", "chrome,modal=yes,resizable=no,centerscreen", null); for ldap address books: window.opendialog("chrome://messenger/content/addressbook/pref-directory-add.xul", "", "chrome,modal=yes,resizable=no,cent...
... user interface. how do i extend the address book user interface? there are several hooks in the address book code exposed to add-on developers to help extend the behavior of the address book. load and save listeners edit dialogs for both contacts and mailing lists expose functions for registering load and save listeners. for example, in order to register a load listener for a contact, the following should take place within the scope of the contact editor dialog: /* an example load listener for a contact * acard the nsiabcard being loaded * adocument a reference to the contact editor document */ function foo(acard, adocument) { // do something useful, like disabling // input fields that cards for this // address book type do not support. } registerloadlistener(foo); save lis...
...And 5 more matches
Autoconfiguration in Thunderbird
end their mail as securely as possible. see also: for instructions for users, see automatic account configuration on the thunderbird knowledge base. ...
... it was added because we cannot assume that all big isps (including microsoft) will set up a configuration server for thunderbird. ...
...ail accounts. it was added because we cannot assume that all big isps (including microsoft) will set up a configuration server for thunderbird. configuration server at isp isps have the option to provide their configuration information themselves directly to users, 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...
...And 5 more matches
Debugger.Memory - Firefox Developer Tools
ations have occurred. it can compute a census of items belonging to the debuggee, categorizing items in various ways, and yielding item counts. ifdbg is a debugger instance, then the methods and accessor properties of dbg.memory control howdbg observes its debuggees’ memory use. the dbg.memory object is an instance of debugger.memory; its inherited accesors and methods are described below. allocation site tracking the javascript engine marks each new object with the call stack at which it was allocated, if: the object is allocated in the scope of a global object that is a debuggee of some debugger instancedbg; and dbg.memory.trackingallocationsites is set to true. a bernoulli trial succeeds, with probability equal to the maximum of d.memory.allocationsamplingpr...
...ging to a particular debugger‘s debuggees. it produces a count of those items, broken down by various criteria. ifdbg is a debugger instance, you can call dbg.memory.takecensus to conduct a census of its debuggees’ possessions. accessor properties of the debugger.memory.prototype object ifdbg is a debugger instance, then <i>dbg</i>.memory is a debugger.memory instance, which inherits the following accessor properties from its prototype: trackingallocationsites a boolean value indicating whether this debugger.memory instance is capturing the javascript execution stack when each object is allocated. this accessor property has both a getter and setter: assigning to it enables or disables the allocation site tracking. reading the accessor produces true if the debugger is capturing sta...
... note that in the presence of multiple debugger instances observing the same allocations within a global’s scope, the maximum allocationsamplingprobability of all the debuggers is used. maxallocationsloglength the maximum number of allocation sites to accumulate in the allocations log at a time. this accessor can be both fetched and stored to. its default value is 5000. allocationslogoverflowed returns true if there have been more than [maxallocationsloglength][#max-alloc-log] allocations since the last time [drainallocationslog][#drain-alloc-log] was called and some data has been lost. returns false otherwise. debugger.memory handler functions similar to debugger’s handler functions, debugger.memory inherits accessor properties that store handler functions for spidermonkey to c...
...And 5 more matches
Debugger.Object - Firefox Developer Tools
his “viewing compartment” is chosen to match the way the debugger came across the referent. as a consequence, a single debugger instance may actually have several debugger.object instances: one for each compartment from which the referent is viewed. if more than one debugger instance is debugging the same code, each debugger gets a separate debugger.object instance for a given object. this allows the code using each debugger instance to place whatever properties it likes on its own debugger.object instances, without worrying about interfering with other debuggers. while most debugger.object instances are created by spidermonkey in the process of exposing debuggee’s behavior and state to the debugger, the debugger can use debugger.object.prototype.makedebuggeevalue to create debugger.o...
...mpartments, allocated as if by particular debuggee globals. debugger.object instances protect their referents from the garbage collector; as long as the debugger.object instance 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. 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 (...
...d) proxy, return a debugger.object instance referring to the ecmascript [[proxyhandler]] of the referent. if the referent is a revoked (scripted) proxy, return null. if the referent is not a (scripted) proxy, return undefined. promisestate if the referent is a promise, return a string indicating whether the promise is pending, or has been fulfilled or rejected. this string takes one of the following values: "pending", if the promise is pending. "fulfilled", if the promise has been fulfilled. "rejected", if the promise has been rejected. if the referent is not a promise, throw a typeerror. promisevalue return a debuggee value representing the value the promise has been fulfilled with. if the referent is not a promise, or the promise has not been fu...
...And 5 more matches
Debugger.Object - Firefox Developer Tools
t. 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 several debugger.object instances: one for each compartment from which the referent is viewed. if more than one debugger instance is debugging the same code, each debugger gets a separate debugger.object instance for a given object. this allows the code using each debugger instance to place whatever properties it likes on its own debugger.object instances, without worrying about interfering with other debuggers. while most debugger.object instances are created by spidermonkey in the process of exposing debuggee's behavior and state to the debugger, the debugger can use debugger.object.prototype.makedebuggeevalue to create debugger.obj...
...mpartments, allocated as if by particular debuggee globals. debugger.object instances protect their referents from the garbage collector; as long as the debugger.object instance 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. ...
... provide further details, as appropriate for the type. for example, in firefox, a metadata object for a javascript module's global object might look like this: { "type":"jsm", "uri":"resource:://gre/modules/xpcomutils.jsm" } firefox provides [debuggerhostannotationsforfirefox annotations] for its host objects. function properties of the debugger.object prototype the functions described below may only be called with a this value referring to a debugger.object instance; they may not be used as methods of other kinds of objects. the descriptions use "referent" to mean "the referent of this debugger.object instance". unless otherwise specified, these methods are not invocation functions; if a call would cause debuggee code to run (say, because it gets or sets an accessor property whose ...
...And 5 more matches
Network request details - Firefox Developer Tools
uest. network request details clicking on a row displays a new pane in the right-hand side of the 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. ...
... this includes: information about the request status: the response status code for the request; click the "?" icon to go to the reference page for the status code. version: the version of http used. transferred: the amount of data transferred for the request. referrer policy: the value of the referrer-policy header. ...
...equest. the domain is added to the blocking sidebar. resend the request. the resend button opens a menu with two items: resend: simply resends the request. edit and resend: enables an editing mode, where you can modify the method, url, request headers, or request body of the request. click send to send the modified request, or cancel to cancel editing. request information the following information is shown only when the section is expanded: scheme: the scheme used in the url host: the server involved in the request filename: the full path to the file requested address: the ip address of the host the following information is shown in both the collapsed and the expanded states: status: the http response code for the request. version: the http version used transfer...
...And 5 more matches
Network request list - Firefox Developer Tools
tus of that request. see security icons. file: the basename of the file requested. (starting in firefox 80) on the right edge of the file column, a turtle icon appears if the server waiting time exceeds a threshhold (default: 500 ms). a tooltip explains the problem. you can configure the threshhold in the configuration editor (about:config) by modifying the devtools.netmonitor.audits.slow setting. url: the url of the file requested. protocol: the network protocol used to transfer the data, this column is hidden by default. scheme: the scheme (https/http/ftp/...) of the path requested. this column is hidden by default. remote ip: the ip address of the server answering the request. this column is hidden by default. type: content-type of the response. cookies: the n...
...ytes that were actually transferred to load the resource, or a message about why the resource was not transferred. a number value is less than size if the resource was compressed. if the resource was fetched from a service worker cache, then this cell displays "service worker". cached resources may be fetched from the cache and the network simultaneously, which may improve load time for slow caches. starting with firefox 68, the transferred column lists either "cached (raced)" or "[size] (raced)" depending on the faster source. this feature is called race cache with network (rcwn). if the resource was blocked, the message indicates why it was blocked. for example, "csp", "malware", "cors missing allow origin", "blocked by [name of extension]". size: the size of the transferr...
...xing your query with the "-" operator. for example, the query "-google.com" will show all requests that don'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. prepending a minus (-) negates the filter. you can combine different filters together by separating them with a space. keyword meaning examples status-code shows resources that have the specific http status code. status-code:304 method shows resources that have were ...
...And 5 more matches
Edit fonts - Firefox Developer Tools
ction of the font editor shows the fonts used by the currently inspected element, grouped by font family. fonts are considered "used" when there is text content in the inspected element that has the font applied to it. empty elements will not have any fonts used and will display the message "no fonts were found for the current element." fonts will be included in this section for one of the following reasons: they are listed in the element's font-family css declaration value. they are applied to the element as part of the browser's default styling (times new roman for most browsers), and no author-defined font has been supplied. they are used by a descendant of the inspected element, for example, when it is a container for other elements which have text content with fonts applied. th...
...w roman for most browsers), and no author-defined font has been supplied. they are used by a descendant of the inspected element, for example, when it is a container for other elements which have text content with fonts applied. they are system fallback fonts used when nothing from the font-family css declaration has been applied. fonts editor firefox 63 adds the font editor — a new area below "fonts used" with additional controls for editing the fonts’ characteristics. for standard (static) fonts, you will be able to change the settings listed below size the font-size for the inspected element. this can be set using em, rem, %, px, vh, or vw units. you can select values using the slider or enter a numeric value directly into the text box. note: if you want to use a differe...
... if the font is 20 pixels high and the line-height is 1.5em, when you change the unit of measure from em to px, the value will become 30px. weight the font-weight for the inspected element. you can select values using the slider or enter a numeric value directly into the text box. for non-variable fonts the slider ranges from 100 to 900 in increments of 100. note: for variable fonts (see below) that define a wght variation axis, this range is custom. italic the font-style for the inspected element. this 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...
...And 5 more matches
CanvasRenderingContext2D - Web APIs
the canvas tutorial has more explanation, examples, and resources, as well. ...
..., 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. ...
... canvasrenderingcontext2d.linewidth width of lines. default 1.0. canvasrenderingcontext2d.linecap type of endings on the end of lines. possible values: butt (default), round, square. canvasrenderingcontext2d.linejoin defines the type of corners where two lines meet. ...
...And 5 more matches
Element.classList - Web APIs
Web › API › Element › classList
sslist.replace("foo", "bar"); versions of firefox before 26 do not implement the use of several arguments in the add/remove/toggle methods. see https://bugzilla.mozilla.org/show_bug.cgi?id=814014 polyfill the legacy onpropertychange event can be used to create a living classlist mockup thanks to a element.prototype.classname property that fires the specified event once it is changed. the following polyfill for both classlist and domtokenlist ensures full compliance (coverage) for all standard methods and properties of element.prototype.classlist for ie10-ie11 browsers plus nearly compliant behavior for ie 6-9. check it out: // 1. string.prototype.trim polyfill if (!"".trim) string.prototype.trim = function(){ return this.replace(/^[\s]+|[\s]+$/g, ''); }; (function(window){"use st...
...list': " + "the token provided ('"+v[wsindex]+"') contains html space characters, which are not valid in tokens."); } // 2. ...
...e not valid in tokens."); } // 2. ...
...And 5 more matches
Using files from web applications - Web APIs
hrome code, you can; however, note there are some additional features to be aware of. see using the dom file api in chrome code for details. accessing selected file(s) consider this html: <input type="file" id="input" multiple> the file api makes it possible to access a filelist containing file objects representing the files selected by the user. the multiple attribute on the input element allows the user to select multiple files. accessing the first selected file using a classical dom selector: const selectedfile = document.getelementbyid('input').files[0]; accessing selected file(s) on a change event it is also possible (but not mandatory) to access the filelist through the change event. you need to use eventtarget.addeventlistener() to add the change event listener, like this: co...
...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. ...
...andles the click event can look like this: const fileselect = document.getelementbyid("fileselect"), fileelem = document.getelementbyid("fileelem"); fileselect.addeventlistener("click", function (e) { if (fileelem) { fileelem.click(); } }, false); you can style the new button for opening the file picker as you wish. using a label element to trigger a hidden file input element to allow opening the file picker without using javascript (the click() method), a <label> element can be used. note that in this case the input element must not be hidden using display: none (nor visibility: hidden), otherwise the label would not be keyboard-accessible. use the visually-hidden technique instead. consider this html: <input type="file" id="fileelem" multiple accept="image/*" class="visual...
...And 5 more matches
Introduction to the File and Directory Entries API - Web APIs
ctory entries api, see the 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 ...
...file systems. for examples of features you can create with this app, see the sample use cases section. the file and directory entries api and other storage apis the file and directory entries api is an alternative to other storage apis like indexeddb, websql (which has been deprecated since november18, 2010), and appcache. the api is a better choice for apps that deal with blobs for the following reasons: the file and directory entries api offers client-side storage for use cases that are not addressed by databases. if you want to have large mutable chunks of data, the file and directory entries api is a much more efficient storage solution than a database. while firefox supports blob storage for indexeddb, chrome currently does not (chrome is still implementing support for blob st...
...re efficient storage solution than a database. while firefox supports blob storage for indexeddb, chrome currently does not (chrome is still implementing support for blob storage in indexeddb). if you are targeting chrome for your app and you want to store blobs, the file and directory entries api and app cache are your only choices. ...
...And 5 more matches
Fullscreen API - Web APIs
ire screen, removing all browser user interface elements and other applications from the screen until full-screen mode is shut off. see the article guide to the fullscreen api for details on how to use the api. note: support for this api varies somewhat across browsers, with many requiring vendor prefixes and/or not implementing the latest specification. see the browser compatibility section below for details on support for this api. you may wish to consider using a library such as fscreen for vendor agnostic access to the fullscreen api. interfaces the fullscreen api has no interfaces of its own. instead, it augments several other interfaces to add the methods, properties, and event handlers needed to provide full-screen functionality. these are listed in the following sections. metho...
...uch as fscreen for vendor agnostic access to the fullscreen api. interfaces the fullscreen api has no interfaces of its own. instead, it augments several other interfaces to add the methods, properties, and event handlers needed to provide full-screen functionality. these are listed in the following sections. methods the fullscreen api adds methods to the document and element interfaces to allow turning off and on full-screen mode. methods on the document interface document.exitfullscreen() requests that the user agent switch from full-screen mode back to windowed mode. returns a promise which is resolved once full-screen mode has been completely shut off. methods on the element interface element.requestfullscreen() asks the user agent to place the specified element (and, by e...
...ells 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 fullscreenenabled property tells you whether or not it is possible to engage full-screen mode. this is false if full-screen mode is not available for any reason (such as the "fullscreen" feature not being allowed, or full-screen mode not being supported). event handlers the fullscreen api defines two events which can be used to detect when full-screen mode is turned on and off, as well as when errors occur during the process of changing between full-screen and windowed modes. event handlers for these events are available on the document and element interfaces. note: these event handler properties a...
...And 5 more matches
HTMLImageElement.srcset - Web APIs
cset = 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 separating the url and the corresponding condition descriptor, are ignored; this includes both leading and trailing space, as well as space before or after each comma. if the condition descriptor is not provided (in o...
...vides only a url), the candidate is used as the fallback if none of the other candidates match. otherwise, the condition descriptor may take one of two forms: to indicate that the image resource specified by the image candidate string should be used when the image is being rendered with a particular width in pixels, provide a width descriptor comprised the number giving that width in pixels followed by the lower case letter "w". for example, to provide an image resource to be used when the renderer needs a 450 pixel wide image, use the width descriptor string 450w. the specified width must be a positive, non-zero, integer, and must match the intrinsic width of the referenced image. alternatively, you can use a pixel density descriptor, which specifies the condition in which the correspond...
...string 450w. the specified width must be a positive, non-zero, integer, and must match the intrinsic width of the referenced image. alternatively, you can use a pixel density descriptor, which specifies the condition in which the corresponding image resource should be used as the display's pixel density. ...
...And 5 more matches
HTMLInputElement - Web APIs
the htmlinputelement interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements. ...
... width string: returns / sets the document's width attribute, which defines the width of the image displayed for the button, if the value of type is image. properties that apply only to elements of type file accept string: returns / sets the element's accept attribute, containing comma-separated list of file types accepted by the server when type is file. allowdirs boolean: part of the non-standard directory upload api; indicates whether or not to allow directories and files both to be selected in the file list. implemented only in firefox and is hidden behind a preference. files returns/accepts a filelist object, which contains a list of file objects representing the files selected for upload. webkitdirectory boolean: ret...
...tton type. selectionstart unsigned long: returns / sets the beginning index of the selected text. when nothing is selected, this returns the position of the text input cursor (caret) inside of the <input> element. selectionend unsigned long: returns / sets the end index of the selected text. when there's no selection, this returns the offset of the character immediately following the current text input cursor position. selectiondirection string: returns / sets the direction in which selection occurred. possible values are: forward if selection was performed in the start-to-end direction of the current locale backward for the opposite direction none if the direction is unknown size unsigned long: returns / sets the element's size attribu...
...And 5 more matches
HTML Drag and Drop API - Web APIs
html drag and drop interfaces enable applications to use drag-and-drop features in browsers. the user may select draggable elements with a mouse, drag those elements to a droppable element, and drop them by releasing the mouse button. a translucent representation of the draggable elements follows the pointer during the drag operation. for web sites, extensions, and xul applications, you can customize which elements can become draggable, the type of feedback the draggable elements produce, and the droppable elements. this overview of html drag and drop includes a description of the interfaces, basic steps to add drag-and-drop support to an application, and an interoperability summary of the interfaces. drag events html drag-and-drop uses the dom event model and drag events inherited from ...
...ple items. additionally, see the datatransfer reference page for all of the gecko-specific properties and gecko-specific methods. the basics this section is a summary of the basic steps to add drag-and-drop functionality to an application. ...
...n is free to include any number of data items in a drag operation. each data item is a string of a particular type — typically a mime type such as text/html. each drag event has a datatransfer property that holds the event's data. this property (which is a datatransfer object) also has methods to manage drag data. the setdata() method is used to add an item to the drag data, as shown in the following example. function dragstart_handler(ev) { // add different types of drag data ev.datatransfer.setdata("text/plain", ev.target.innertext); ev.datatransfer.setdata("text/html", ev.target.outerhtml); ev.datatransfer.setdata("text/uri-list", ev.target.ownerdocument.location.href); } for a list of common data types used in drag-and-drop (such as text, html, links, and files), see recom...
...And 5 more matches
RTCDataChannel - Web APIs
eceives a datachannel event (which has type rtcdatachannelevent) to let it know the data channel has been added to the connection. propertiesalso inherits properties from: eventtargetbinarytype the property binarytype on the rtcdatachannel interface is a domstring which specifies the type of javascript object which should be used to represent binary data received on the rtcdatachannel. ...
...ved on the rtcdatachannel. values allowed by the websocket.binarytype property are also permitted here: "blob" if blob objects are being used or "arraybuffer" if arraybuffer objects are being used. ...
...et.binarytype property are also permitted here: "blob" if blob objects are being used or "arraybuffer" if arraybuffer objects are being used. the default is "blob".bufferedamount read only the read-only rtcdatachannel property bufferedamount returns the number of bytes of data currently queued to be sent over the data channel.bufferedamountlowthreshold the rtcdatachannel property bufferedamountlowthreshold is used to specify the number of bytes of buffered outgoing data that is considered "low." the default value is 0.id read only the read-only rtcdatachannel property id returns an id number (between 0 and 65,534) which uniquely identifies the rtcdatachannel.label read only the read-only rtcdatachannel property label returns a domstring containing a name describing the data channel. th...
...And 5 more matches
Touch events - Web APIs
a multi-touch interaction starts when a finger (or stylus) first touches the contact surface. other fingers may subsequently touch the surface and optionally move across the touch surface. the interaction ends when the fingers are removed from the surface. ...
.... interfaces touchevent represents an event that occurs when the state of touches on the surface changes. touch represents a single point of contact between the user and the touch surface. touchlist represents a group of touches; this is used when the user has, for example, multiple fingers on the surface at the same time. example this example tracks multiple touchpoints at a time, allowing the user to draw in a <canvas> with more than one finger at a time. it will only work on a browser that supports touch events. note: the text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus or other contact method. create a canvas <canvas id="canvas" width="600" height="600" style="border:solid black 1px;"> your browser ...
... the contact with the surface, but it could, of course, also be a stylus or other contact method. create a canvas <canvas id="canvas" width="600" height="600" style="border:solid black 1px;"> your browser does not support canvas element. </canvas> <br> log: <pre id="log" style="border: 1px solid #ccc;"></pre> setting up the event handlers when the page loads, the startup() function shown below will be called. function startup() { var el = document.getelementbyid("canvas"); el.addeventlistener("touchstart", handlestart, false); el.addeventlistener("touchend", handleend, false); el.addeventlistener("touchcancel", handlecancel, false); el.addeventlistener("touchmove", handlemove, false); } document.addeventlistener("domcontentloaded", startup); this simply sets up all the eve...
...And 5 more matches
Writing WebSocket servers - Web APIs
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. ...
...ockets may be required. the scope of this guide is to present the minimum knowledge you need to write a websocket server. note: read the latest official websockets specification, rfc 6455. sections 1 and 4-7 are especially interesting to server implementors. section 10 discusses security and you should definitely peruse it before exposing your server. a websocket server is explained on a very low level here. websocket servers are often separate and specialized servers (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 exam...
...common headers like user-agent, referer, cookie, or authentication headers might be there as well. do whatever you want with those; they don't directly pertain to the websocket. it's also safe to ignore them. in many common setups, a reverse proxy has already dealt with them. tip: all browsers send an origin header. you can use this header for security (checking for same origin, automatically allowing or denying, etc.) and send a 403 forbidden if you don't like what you see. however, be warned that non-browser agents can send a faked origin. most applications reject requests without this header. if any header is not understood or has an incorrect value, the server should send a 400 ("bad request")} response and immediately close the socket. as usual, it may also give the reason why the ha...
...And 5 more matches
Background audio processing using AudioWorklet - Web APIs
this article, we'll look at these steps in more detail, with examples (including working examples you can try out on your own). the example code found on this page is derived from this working example which is available on glitch. the example creates an oscillator node and adds white noise to it using an audioworkletnode before playing the resulting sound out. slider controls are available to allow controlling the gain of both the oscillator and the audio worklet's output. glitch project page see the code try it live creating an audio worklet processor fundamentally, an audio worklet processor (which we'll refer to usually as either an "audio processor" or simply as a "processor" because otherwise this article will be about twice as long) is implemented using a javascript module that...
...tally, an audio worklet processor (which we'll refer to usually as either an "audio processor" or simply as a "processor" because otherwise this article will be about twice as long) is implemented using 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 proc...
... room for in the output list. the same check is performed when determining how many channels to process in the current input; we only process as many as there are room for in the destination output. this avoids errors due to overrunning these arrays. mixing inputs many nodes perform mixing operations, where the inputs are combined in some way into a single output. this is demonstrated in the following example. process(inputlist, outputlist, parameters) { const sourcelimit = math.min(inputlist.length, outputlist.length); for (let inputnum = 0; inputnum < sourcelimit; inputnum++) { let input = inputlist[inputnum]; let output = outputlist[0]; let channelcount = math.min(input.length, output.length); for (let channelnum = 0; channelnum < channelcount; channelnum++) { ...
...And 5 more matches
Web Authentication API - Web APIs
thenticating, and second-factor authentication with websites. this resolves significant security problems related to phishing, data breaches, and attacks against sms texts or other second-factor authentication methods while at the same time significantly increasing ease of use (since users don't have to manage dozens of increasingly complicated passwords). many websites already have pages that allow users to register new accounts or sign in to an existing account, and the web authentication api acts as a replacement or supplement to those on those existing webpages. similar to the other forms of the credential management api, the web authentication api has two basic methods that correspond to register and login: navigator.credentials.create() - when used with the publickey option, creates...
... is needed; when authenticating using web authentication, the password is replaced with a key pair that is stored in an authenticator. the authenticator may be embedded into an operating system, such as windows hello, or may be a physical token, such as a usb or bluetooth security key. registration a typical registration process has six steps, as illustrated in figure 1 and described further below. this is a simplification of the data required for the registration process that is only intended to provide an overview. the full set of required fields, optional fields, and their meanings for creating a registration request can be found in the publickeycredentialcreationoptions dictionary. likewise, the full set of response fields can be found in the publickeycredential interface (where public...
...faults, which become the authenticatorresponse.clientdatajson. one of the most important parameters is the origin, which is recorded as part of the clientdata so that the origin can be verified by the server later. the parameters to the create() call are passed to the authenticator, along with a sha-256 hash of the 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 new key pair and attestation - before doing anything, the authenticator will typically ask for some form of user verification. this could be entering a pin, using a fingerprint, doing an iris scan, etc. to prove that the user is present and conse...
...And 5 more matches
Using the aria-labelledby attribute - Accessibility
s very similar to aria-describedby: a label provides essential information about an object, while a description provides extended information that the user might need. in addition to form elements, you can use the aria-labelledby attribute to associate static text with widgets, groups of elements, panes, regions that have a heading, definitions, and other types of objects. the examples section below provides more information on how to use the attribute this way. to improve compatibility with user agents that do not support aria, you can use aria-labelledby with the <label> element (using the for attribute). this attribute can be used with any typical html form element; it is not limited to elements that have an aria role assigned. value a space-separated list of element ids possible eff...
...d to elements that have an aria role assigned. value a space-separated list of element ids possible effects on user agents and assistive technology when user agents compute the accessible name property of elements that have both an aria-labelledby attribute and an aria-label attribute, the user agents give precedence to aria-labelledby. ...
... by both its own individual label and by the label for the group: <div id="mybillingid">billing</div> <div> <div id="mynameid">name</div> <input type="text" aria-labelledby="mybillingid mynameid"/> </div> <div> <div id="myaddressid">address</div> <input type="text" aria-labelledby="mybillingid myaddressid"/> </div> example 2: associating headings with regions in the example below, header elements are associated with the content they head. note that the region being referenced is the region that contains the header. <div role="main" aria-labelledby="foo"> <h1 id="foo">wild fires spread across the san diego hills</h1> strong winds expand fires ignited by high temperatures ... </div> example 3: radio groups in the example below, the container of a radiogroup is ass...
...And 5 more matches
@supports - CSS: Cascading Style Sheets
Web › CSS › @supports
supportsrule. syntax the @supports at-rule associates a block of statements with a supports condition. the supports condition consists of one or more name-value pairs combined by conjunctions (and), disjunctions (or), and/or negations (not). precedence of operators can be defined with parentheses. ...
...tion. the supports condition consists of one or more name-value pairs combined by conjunctions (and), disjunctions (or), and/or negations (not). precedence of operators can be defined with parentheses. declaration syntax the most basic supports condition is a simple declaration (a property name followed by a value, separated by a colon). the declaration must be surrounded by parentheses. the following example returns true if the browser's transform-origin property considers 5% 5% valid: @supports (transform-origin: 5% 5%) {} function syntax the second basic supports condition is a supports function, the syntax for these is supported by all browsers, but the functions themselves are still being standardized. selector() tests if the browser supports the tested selector syntax. the foll...
...l browsers, but the functions themselves are still being standardized. selector() tests if the browser supports the tested selector syntax. the following example returns true if the browser supports the child combinator: @supports selector(a > b) {} the not operator the not operator can precede any expression to create a new expression, resulting in the negation of the original one. the following example returns true if the browser's transform-origin property doesn't consider 10em 10em 10em valid: @supports not (transform-origin: 10em 10em 10em) {} as with any operator, the not operator can be applied to a declaration of any complexity. ...
...And 5 more matches
CSS Box Alignment - CSS: Cascading Style Sheets
tical alignment capabilities. if you initially learned flexbox then you may consider these properties to be part of the flexbox specification, and some of the properties are indeed listed in level 1 of flexbox. however the specification notes that the box alignment specification should be referred to as it may add additional capabilities over what is currently in flexbox. basic examples the following examples demonstrate how some of the box alignment properties are applied in grid and flexbox. css grid layout alignment example in this example using grid layout, there is extra space in the grid container after laying out the fixed width tracks on the inline (main) axis. this space is distributed using justify-content. on the block (cross) axis the alignment of the items inside their grid ...
...rms of the start and end of the particular dimension we are working with. this ensures that alignment works in the same way whichever writing mode the document has. two dimensions of alignment when using the box alignment properties you will align content on one of two axes — the inline (or main) axis, and the block (or cross) axis. the inline axis is the axis along which words in a sentence flow in the writing mode being used — for english, for example, the inline axis is horizontal. the block axis is the axis along which blocks, such as paragraph elements, are laid out and it runs across the inline axis. when aligning items on the inline axis you will use the properties which begin with justify-: justify-items justify-self justify-content when aligning items on the block axi...
...tems, this will be the margin box of the element that this property is being used on. the justify-content and align-content properties differ per layout method. the alignment container the alignment container is the box the subject is being aligned inside. this will typically be the alignment subject’s containing block. an alignment container may contain one or many alignment subjects. the below image shows an alignment container with two alignment subjects inside. fallback alignment if you set an alignment that cannot be fulfilled, then the fallback alignment will come into play and deal with the available space. this fallback alignment is specified individually for each layout method and detailed on the page for that method. types of alignment there are three different types of a...
...And 5 more matches
CSS Display - CSS: Cascading Style Sheets
css display is a module of css that defines how the css formatting box tree is generated from the document element tree and defines properties controlling it. ...
...ss that defines how the css formatting box tree is generated from the document element tree and defines properties controlling it. ...
...t defines how the css formatting box tree is generated from the document element tree and defines properties controlling it. ...
...And 5 more matches
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
therefore modularised, and the various css specifications are different modules that make up css today. these modules relate to each other, and are at different stages of development. the box alignment module for many people the first reason they start to look at flexbox is because of the ability to properly align flex items inside a flex container. flexbox provides access to properties that allow the alignment of items on their cross axis and justification of items on the main axis. these properties started life in the flexbox specification, but are now also part of the box alignment specification. this specification details how alignment works in all layout — not just flexbox. box alignment deals with alignment and justification, and also distribution of space along an axis. the reas...
......
... layout methods. it is worth noting that we might want to change the writing mode of our document for reasons other than publishing content in a language that uses a different writing mode. see this article for a full description of writing modes and ways to use them, both for content in other languages and for creative reasons. the writing modes the writing modes specification defines the following values of the writing-mode property, which serve to change the direction that blocks are laid out on the page, to match the direction that blocks lay out when content is formatted in that particular writing mode. you can change the live example below to these modes in order to see what happens to the flex layout. horizontal-tb vertical-rl vertical-lr sideways-rl sideways-lr note th...
...And 5 more matches
Basic concepts of Logical Properties and Values - CSS: Cascading Style Sheets
start and end as opposed to left and right/top and bottom. ...
...start and end as opposed to left and right/top and bottom. ...
...operties? css traditionally has sized things according to the physical dimensions of the screen. therefore we describe boxes as having a width and height, position items from the top and left, float things left, assign borders, margin, and padding to the top, right, bottom, left, etc. ...
...And 5 more matches
CSS reference - CSS: Cascading Style Sheets
Web › CSS › Reference
by type. also included is a brief dom-css / cssom reference. basic rule syntax style rule syntax style-rule ::= selectors-list { properties-list } ... where : selectors-list ::= selector[:pseudo-class] [::pseudo-element] [, selectors-list] properties-list ::= [property : value] [; properties-list] see the index of selectors, pseudo-classes, and pseudo-elements below. the syntax for each specified value depends on the data type defined for each specified property. style rule examples strong { color: red; } div.menu-bar li:hover > ul { display: block; } for a beginner-level introduction to the syntax of selectors, see our guide on css selectors. be aware that any syntax error in a rule definition invalidates the entire rule. invalid rules are ignored ...
...nsion>:dirdirection:disableddisplay<display-box><display-inside><display-internal><display-legacy><display-listitem><display-outside>dpcmdpidppxdrop-shadow()eelement()ellipse()em:emptyempty-cells:enabledenv()exffallback (@counter-style)filter<filter-function>:first:first-child::first-letter (:first-letter)::first-line (:first-line):first-of-typefit-content()<flex>flexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloat:focusfont@font-facefont-familyfont-family (@font-face)font-feature-settingsfont-feature-settings (@font-face)@font-feature-valuesfont-kerningfont-language-overridefont-optical-sizingfont-sizefont-size-adjustfont-stretchfont-stretch (@font-face)font-stylefont-style (@font-face)font-synthesisfont-variantfont-variant (@font-face)font-variant-alternatesfont-variant-c...
...face)font-synthesisfont-variantfont-variant (@font-face)font-variant-alternatesfont-variant-capsfont-variant-east-asianfont-variant-ligaturesfont-variant-numericfont-variant-positionfont-variation-settingsfont-variation-settings (@font-face)font-weightfont-weight (@font-face)format()fr<frequency><frequency-percentage>:fullscreenggapgrad<gradient>grayscale()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...
...And 5 more matches
Shorthand properties - CSS: Cascading Style Sheets
lly 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 individual properties values can inherit. as missing values are replaced by their initial value, it is impossible to allow inheritance of individual properties by omitting them. the keyword inherit can be applied to a property, but only as a whole, not as a keyword for one value or another. that means that the only way to make some specific value to be inherited is to use the longhand property with the keyword inherit. shorthand properties try not to force a specific order for the values of the properties they repla...
...p right and bottom left ones, and the third value the bottom right corner the 4-value syntax: border-radius: 1em 2em 3em 4em — the four values represent the top left, top right, bottom right and bottom left corners respectively, always in that order, that is clock-wise starting at the top left. background properties a background with the following properties ... background-color: #000; background-image: url(images/bg.gif); background-repeat: no-repeat; background-position: left top; ... can be shortened to just one declaration: background: #000 url(images/bg.gif) no-repeat left top; (the shorthand form is actually the equivalent of the longhand properties above plus background-attachment: scroll and, in css3, some additional propert...
...epeat; background-position: left top; ... can be shortened to just one declaration: background: #000 url(images/bg.gif) no-repeat left top; (the shorthand form is actually the equivalent of the longhand properties above plus background-attachment: scroll and, in css3, some additional properties.) see background for more detailed information, including css3 properties. font properties the following declarations ... font-style: italic; font-weight: bold; font-size: .8em; line-height: 1.2; font-family: arial, sans-serif; ... can be shortened to the following: font: italic bold .8em/1.2 arial, sans-serif; this shorthand declaration is actually equivalent to the longhand declarations above plus font-variant: normal and font-size-adjust: none (css2.0 / css3), font-stretch: normal (css3). ...
...And 5 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
oz-user-select: none; user-select: none; } .ui-input-slider * { float: left; height: 100%; } /* input slider */ .ui-input-slider > input { margin: 0; padding: 0; width: 50px; text-align: center; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .ui-input-slider-info { width: 90px; padding: 0px 10px 0px 0px; text-align: right; text-transform: lowercase; line-height: inherit; } .ui-input-slider-left, .ui-input-slider-right { width: 16px; cursor: pointer; background: url("arrows.png") center left no-repeat; } .ui-input-slider-right { background: url("arrows.png") center right no-repeat; } .ui-input-slider-name { width: 90px; padding: 0 10px 0 0; text-align: right; text-transform: lowercase; } .ui-input-slider-btn-set { width: ...
...; user-select: none; } .ui-slider > * { float: left; height: 100%; line-height: 100%; } /* slider */ .ui-slider-slider { height: 10px; width: 200px; margin: 4px 10px; display: block; border: 1px solid #999; border-radius: 3px; background: #eee; } .ui-slider-slider:hover { cursor: pointer; } .ui-slider-name { width: 90px; padding: 0 10px 0 0; text-align: right; text-transform: lowercase; } .ui-slider-pointer { width: 12px; height: 13px; margin: 0 0 0 -7px; background-color: #eee; border: 1px solid #2c9fc9; border-radius: 3px; position: relative; top: -3px; left: 0%; } .ui-slider-button { width: 25px; background-color: #2c9fc9; border-radius: 3px; color: #fff; font-weight: bold; line-height: 14px; text-align: center; } .ui-slider-button:hover { backgroun...
...n select button */ .ui-dropdown-select { padding: 0 0.75em; color: #fff; line-height: 2em; } /* dropdown list */ .ui-dropdown-list { width: 100%; height: 150px; max-height: 150px; margin: 0; padding: 0 0.3em; border: 1px solid #3490d2; border-color: #208b20; background: #666; background-color: #eef1f5; color: #000; position: absolute; top: 100%; left: 0; z-index: 100; overflow: hidden; transition: all 0.3s; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .ui-dropdown-list:hover { overflow: auto; } .ui-dropdown-list[data-hidden='true'] { height: 0 !important; opacity: 0; visibility: hidden; } .ui-dropdown[data-position='left'] .ui-dropdown-list { left: -100%; top: 0; } .ui-dropdown[data-position='right'] .ui-dropdown...
...And 5 more matches
<custom-ident> - CSS: Cascading Style Sheets
the <custom-ident> css data type denotes an arbitrary user-defined string used as an identifier. it is case-sensitive, and certain values are forbidden in various contexts to prevent ambiguity. syntax the syntax of <custom-ident> is similar to css identifiers (such as property names), except that it is case-sensitive. it consists of one or more characters, where characters can be any of the following: any alphabetical character (a to z, or a to z), any decimal digit (0 to 9), a hyphen (-), an underscore (_), an escaped character (preceded by a backslash, \), a unicode character (in the format of a backslash, \, followed by one to six hexadecimal digits, representing its unicode code point) note that id1, id1, id1 and id1 are all different identifiers as they are case-sensitive. o...
...d1, id1, id1 and id1 are all different identifiers as they are case-sensitive. on the other hand, as there are several ways to escape a character, toto\? and toto\3f are the same identifiers. forbidden values a <custom-ident> must not be placed between single or double quotes as this would be identical to a <string>. moreover, the first character must not be a decimal digit, nor a hyphen (-) followed by a decimal digit or another hyphen. to prevent ambiguity, each property that uses <custom-ident> forbids the use of specific values: animation-name forbids the global css values (unset, initial, and inherit), as well as none. counter-reset counter-increment forbids the global css values (unset, initial, and inherit), as well as none. @counter-style list-style-type forbids the globa...
...ounter-reset counter-increment forbids the global css values (unset, initial, and inherit), as well as none. @counter-style list-style-type forbids the global css values (unset, initial, and inherit), as well as the values none, inline, and outside. ...
...And 5 more matches
Cross-browser audio basics - Developer guides
mp4 files typically contain aac encoded audio. you can use type="audio/mp4". (currently, browsers that support mp3 also suppor...
...ase, we've provided a simple paragraph including a link to download the audio directly. the controls attribute on the <audio> element is specified when we require the browser to provide us with default playback controls. if you don't specify this attribute, no controls will appear — and you will instead have to create your own controls and program their functionality using the media api (see below). however, that can be a good approach, 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 wi...
...tails. loop the loop attribute will ensure that upon getting to the end of the audio clip, the audio clip will loop back to the beginning and start playing again. <audio loop> ... </audio> muted if you want the audio to start muted (no volume), add the muted attribute. <audio muted> ... </audio> note: this value is often ignored on mobile platforms. ...
...And 5 more matches
Live streaming web audio and video - Developer guides
that is represented by a file, whether it be an mp3 or webm file. this file sits on a server and can be delivered — 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 ...
... 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 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 ...
...ing 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 advantages to this: latency is generally lower so media will start playing more quickly adaptive streaming makes for better experiences on a variety of devices media is downloaded just in time which makes bandwidth usage more efficient streaming protocols while static media is usually served over http, there are several protocols for serving adaptive streams; let's take a look at the options. http for now, http is by far the most com...
...And 5 more matches
Making content editable - Developer guides
d fast rich text editor. this article provides some information about this functionality. note: in firefox 63 beta/dev edition, some of the rich-text editing features have been disabled by default, for better cross-browser compatibility. these are object resizing on <img>, <table>, and absolutely-positioned elements; inline table editing to add or remove rows and columns; and the grabber that allows moving of absolutely-positioned elements. see bug 1449564 and firefox-specific html editing ui has been deprecated for additional details. how does it work? all you have to do is set the contenteditable attribute on nearly any html element to make it editable. here's a simple example which creates a <div> element whose contents the user can edit. <div contenteditable="true"> this text can...
... the separate lines in <div> elements, matching the behavior of chrome, modern opera, edge, and safari. try it out in the above example. note: internet explorer, which is no longer being developed, uses <p> elements instead of <div>. if you want to use a different paragraph separator, the above browsers all support document.execcommand, which provides a defaultparagraphseparator command to allow you to change it. for example, to use <p> elements: document.execcommand("defaultparagraphseparator", false, "p"); additionally, firefox supports the non-standard argument, br, for defaultparagraphseparator since firefox 55. this is useful if your web application expects the older firefox behavior, and you don't want to or don't have the time to update it to use the new behavior. you can use th...
...behavior, and you don't want to or don't have the time to update it to use the new behavior. you can use the older firefox behavior with this line: document.execcommand("defaultparagraphseparator", false, "br"); security for security reasons, firefox doesn't let javascript code use clipboard related features (copy, paste, etc.) by default. ...
...And 5 more matches
<input type="checkbox"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › checkbox
<input> elements of type checkbox are rendered by default as boxes that are checked (ticked) when activated, like you might see in an official government paper form. the exact appearance depends upon the operating system configuration under which the browser is running. generally this is a square but it may have rounded corners. a checkbox allows you to select single values for submission in a form (or not). 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: radio buttons are similar to checkboxes, but with an important distinction — radio buttons are grouped into a set in which only one radio button can be ...
...ive 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: radio buttons are similar to checkboxes, but with an important distinction — radio buttons are grouped into a set in which only one radio button can be selected at a time, whereas 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 ...
...ue 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">subscribe to newsletter?</label> </div> <div> <button type="submit">subscribe</button> </div> </form> in this example, we've got a name of subscribe, and a value of newsletter. when the form is submitted, the data name/value pair will be subscr...
...And 5 more matches
<input type="password"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › password
e 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. specifics of how the entry process works may vary from browser to browser; mobile devices, for example, often display the typed character for a moment before obscuring it, to allow the user to be sure they pressed the key they meant to press; this is helpful given the small size of keys and the ease with which the wrong one can be pressed, especially on virtual keyboards. 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 pa...
...ore information. note: the line feed (u+000a) and carriage return (u+000d) characters are not permitted in a password value. when setting the value of a password control, line feed and carriage return characters are stripped out of the value. ...
... password input boxes generally work just like other textual input boxes; the main difference is the obscuring of the content to prevent people near the user from reading the password. a simple password input here we see the most basic password input, with a label established using the <label> element. ...
...And 5 more matches
CSP: connect-src - HTTP
vigator.sendbeacon(). note: connect-src 'self' does not resolve to websocket schemas in all browsers, more info: https://github.com/w3c/webappsec-csp/issues/7 csp version 1 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the connect-src policy: content-security-policy: connect-src <source>; content-security-policy: connect-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use...
...: url scheme. mail.example.com:443: matches all attempts to access port 443 on mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a scheme such as http: or https:. the colon is required. unlike other values below, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. f...
...es shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' ...
...And 5 more matches
CSP: style-src-attr - HTTP
directive specifies valid sources for inline styles applied to individual dom elements. csp version 3 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the style-src directive, and if both of them are absent, fallback to default-src directive. ...
...the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as the port number, indicating that all legal ports are valid for the source. ...
...: url scheme. mail.example.com:443: matches all attempts to access port 443 on mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a scheme such as http: or https:. the colon is required. unlike other values below, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. f...
...And 5 more matches
CSP: style-src-elem - HTTP
alid sources for stylesheets <style> elements and <link> elements with rel="stylesheet". csp version 3 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the style-src directive, and if both of them are absent, fallback to default-src directive. ...
...the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as the port number, indicating that all legal ports are valid for the source. ...
...: url scheme. mail.example.com:443: matches all attempts to access port 443 on mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a scheme such as http: or https:. the colon is required. unlike other values below, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. f...
...And 5 more matches
Text formatting - JavaScript
.org/show_bug.cgi?id=857438 ). string literals you can create simple strings using either single or double quotes: 'foo' "bar" more advanced strings can be created using escape sequences: hexadecimal escape sequences the number after \x is interpreted as a hexadecimal number. '\xa9' // "©" unicode escape sequences the unicode escape sequences require at least four hexadecimal digits following \u. '\u00a9' // "©" unicode code point escapes new in ecmascript 2015. with unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use unicode code points up to 0x10ffff. with simple unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result. see also string.fromcodepoint() or string.proto...
...can have counterintuitive behavior. for example: const firststring = '2 + 2'; // creates a string literal value const secondstring = new string('2 + 2'); // creates a string object eval(firststring); // returns the number 4 eval(secondstring); // returns the string "2 + 2" a string object has one property, length, that indicates the number of utf-16 code units in the string. for example, the following code assigns hellolength the value 13, because "hello, world!" has 13 characters, each represented by one utf-16 code unit. you can access each code unit using an array bracket style. you can't change individual characters because strings are immutable array-like objects: const hello = 'hello, world!'; const hellolength = hello.length; hello[0] = 'l'; // this has no effect, because strings ar...
...ces such as the formation of strings with unmatched surrogate code units, in violation of the unicode standard. (examples should be added to this page after mdn bug 857438 is fixed.) see also string.fromcodepoint() or string.prototype.codepointat(). a string object has a variety of methods: for example those that return a variation on the string itself, such as substring and touppercase. the following table summarizes the methods of string objects. methods of string method description charat, charcodeat, codepointat return the character or character code at the specified position in string. indexof, lastindexof return the position of specified substring in the string or last position of specified substring, respectively. startswith, end...
...And 5 more matches
SyntaxError: Unexpected token - JavaScript
error: expected rest argument name, got "x" syntaxerror: expected closing parenthesis, got "x" syntaxerror: expected '=>' after argument list, got "x" error type syntaxerror what went wrong? a specific language construct was expected, but something else was provided. this might be a simple typo. ...
... for example, when chaining expressions, trailing commas are not allowed. ...
...railing commas are not allowed. for (let i = 0; i < 5,; ++i) { console.log(i); } // syntaxerror: expected expression, got ')' correct would be omitting the comma or adding another expression: for (let i = 0; i < 5; ++i) { console.log(i); } not enough brackets sometimes, you leave out brackets around if statements: function round(n, upperbound, lowerbound){ if(n > upperbound) || (n < lowerbound){ throw 'number ' + string(n) + ' is more than ' + string(upperbound) + ' or less than ' + string(lowerbound); }else if(n < ((upperbound + lowerbound)/2)){ return lowerbound; }else{ return upperbound; } } // syntaxerror: expected expression, got '||' the brackets may look correct at first, but note how the || is outside the brackets. correct would be putting brackets aro...
...And 5 more matches
new operator - JavaScript
perator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function. syntax new constructor[([arguments])] parameters constructor a class or function that specifies the type of the object instance. arguments a list of values that the constructor will be called with. description the new keyword does the following things: creates a blank, plain javascript object; links (sets the constructor of) this object to another object; passes the newly created object from step 1 as the this context; returns this if the function doesn't return an object. creating a user-defined object requires two steps: define the object type by writing a function. create an instance of the object with new. to define...
...is context; returns this if the function doesn't return an object. creating a user-defined object requires two steps: define the object type by writing a function. create an instance of the object with new. to define an object type, create a function for the object type that specifies its name and properties. an object can have a property that is itself another object. see the examples below. when the code new foo(...) is executed, the following things happen: a new object is created, inheriting from foo.prototype. the constructor function foo is called with the specified arguments, and with this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments. the object (not null, false, 3.1415 or ot...
...fect any other objects. to add the new property to all objects of the same type, you must add the property to the definition of the car object type. you can add a shared property to a previously defined object type by using the function.prototype property. this defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. the following code adds a color property with value "original color" to all objects of type car, and then overwrites that value with the string "black" only in the instance object car1. for more information, see prototype. function car() {} car1 = new car(); car2 = new car(); console.log(car1.color); // undefined car.prototype.color = 'original color'; console.log(car1.color); // 'original color' ...
...And 5 more matches
MathML documentation index - MathML
Web › MathML › Index
thml language. just like html, mathml is described with tags and attributes. html becomes verbose when your document contains advanced structures like lists or tables but fortunately there are many generators from simple notations, wysiwyg editors and other content management systems to help writing web pages. 3 examples beginner, example, guide, mathml, needsbeginnerupdate below you'll find some examples you can look at to help you to understand how to use mathml to display increasingly complex mathematical concepts in web content. 4 mathml: deriving the quadratic formula beginner, education, example, guide, html5, mathml, needsbeginnerupdate this page outlines the derivation of the quadratic formula. 5 proving the pythagorean theorem ...
...g. mathml accepts different units and constants for specifying lengths. 8 mathml documentation index index, mathml found 40 pages: 9 mathml element reference mathml, mathml reference this is an alphabetical list of mathml presentation elements. 10 <maction> mathml, mathml reference, mathml:element, mathml:enlivening expressions the following example uses the "toggle" actiontype: 11 <math> mathml, mathml reference, mathml:element the top-level element in mathml is <math>. every valid mathml instance must be wrapped in <math> tags. in addition you must not nest a second <math> element in another, but you can have an arbitrary number of other child elements in it. 12 <menclose> mathml, mathml refer...
...ng 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> element allows you to create tensor-like objects. in a descriptive way tensors are multidimensional matrices (mathematical imprecise but exemplified). the degree of a tensor depends on the dimensionality of a representative array. for example, a number is a 0-dimensional array, or a 0th-order tensor. a 1-dimensional array (e.g. vectors) is a 1st-order tensor and so 2nd-order tensors are needed to represent squ...
...And 5 more matches
Progressive web apps (PWAs)
ressive web apps are a useful design pattern, though they aren't a formalized standard. pwa can be thought of as similar to ajax or other similar patterns that encompass a set of application attributes, including use of specific web technologies and techniques. this set of docs tells you all you need to know about them. in order to call a web app a pwa, technically speaking it should have the following features: secure contexts (https), one or more service workers, and a manifest file. secure contexts (https) the web application must be served over a secure network. being a secure site is not only a best practice, but it also establishes your web application as a trusted site especially if users need to make secure transactions. most of the features related to a pwa such as geolocation a...
...st be served over a secure network. being a secure site is not only a best practice, but it also establishes your web application as a trusted site especially if users need to make secure transactions. most of the features related to a pwa such as geolocation and even service workers are available only once the app has been loaded using https. service workers a service worker is a script that allows intercepting and control of how a web browser handles its network requests and asset caching. with service workers, web developers can create reliably fast web pages and offline experiences. manifest file a json file that controls how your app appears to the user and ensures that progressive web apps are discoverable. it describes the name of the app, the start url, icons, and all of the other...
...essary to transform the website into an app-like format. pwa advantages pwas should be discoverable, installable, linkable, network independent, progressive, re-engageable, responsive, and safe. to find out more about what these mean, read progressive web app advantages. to find out how to implement pwas, read through our pwa developer guide. ...
...And 5 more matches
Paths - SVG: Scalable Vector Graphics
Web › SVG › Tutorial › Paths
traight lines can be created as <polyline>s. while <polyline>s and <path>s can create similar-looking shapes, <polyline>s require a lot of small straight lines to simulate curves, and don't scale well to larger sizes. a good understanding of paths is important when drawing svgs. while creating complex paths using an xml editor or text editor is not recommended, understanding how they work will allow to identify and repair display issues in svgs. 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 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. an uppercase letter specifies absolute coordinates on the page, and a lowercase letter specifies relative coordinates (e.g., move 10px up and 7px to the left from the last point). coordinates in the d parameter are always unitless and hence in the user coordinate system. later, we will learn how paths can be transformed to suit other needs. line commands there are five line commands for <path> nodes. the first command is the "move to" or m, which was described above...
... for <path> nodes. the first command is the "move to" or m, which was described above. it takes two parameters, a coordinate (x) and coordinate (y) to move to. if the cursor was already somewhere on the page, no line is drawn to connect the two positions. the "move to" command appears at the beginning of paths to specify where the drawing should start. for example: m x y (or) m dx dy in the following example there's only a point at (10,10). note, though, that it wouldn't show up if a path was just drawn normally. for example: <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <path d="m10 10"/> <!-- points --> <circle cx="10" cy="10" r="2" fill="red"/> </svg> there are three commands that draw lines. the most generic is the "line to" command, called with l. l ta...
...And 5 more matches
page-mod - Archive of obsolete content
run scripts in the context of web pages whose url matches a given pattern. usage to use page-mod, you specify: one or more scripts to attach. the sdk calls these scripts "content scripts". a pattern that a page's url must match, in order for the script(s) to be attached to that page. ...
...ontrols the point during document load at which content scripts are attached. exclude has the same syntax as include, but specifies the urls to which content scripts should not be attached, even if they match include: so it's a way of excluding a subset of the urls that include specifies. the exclude option is new in firefox 32. these options are documented in detail below. for all the details on content scripts, see the guide to content scripts. communicating with content scripts your add-on's "main.js" can't directly access the state of content scripts you load, but you can communicate between your add-on and its content scripts by exchanging messages. to do this, you'll need to listen to the page-mod's attach event. this event is triggered every time the pag...
...tate of content scripts you load, but you can communicate between your add-on and its content scripts by exchanging messages. to do this, you'll need to listen to the page-mod's attach event. this event is triggered every time the page-mod's content script is attached to a document. the listener is passed a worker object that your add-on can use to send and receive messages. for example, the following add-on retrieves the html content of specific tags from documents that match the pattern. the main add-on code sends the desired tag to the content script, and the content script replies by sending the html content of all the elements with that tag. /lib/main.js: var tag = "p"; var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozill...
...And 4 more matches
File I/O - Archive of obsolete content
m"); var file = new fileutils.file("/home"); or the same without using fileutils.jsm: var file = components.classes["@mozilla.org/file/local;1"]. createinstance(components.interfaces.nsilocalfile); file.initwithpath("/home"); note: the path should be in the "native" form (for example"c:\\windows"). if you need to use file:// uris as initializers, see discussion of nsiioservice below. note: you can still get a file object even if the specified file does not exist, and no exception will be thrown. an exception is thrown only when methods that require the file to exist are called, e.g., isdirectory(), moveto(), and so on. getting files in special directories components.utils.import("resource://gre/modules/fileutils.jsm"); // get the "data.txt" file in the profile directory...
...rings available: xpcom/io/nsappdirectoryservicedefs.h, xpcom/io/nsdirectoryservicedefs.h. other such keys as the "profd" key are available; check the known locations. enumerating drives on windows while you can use initwithpath("/") on unix-like systems (linux, mac) to get the root of the file system, there's no such root on windows. however, you can enumerate available drives using the following code: components.utils.import("resource://gre/modules/fileutils.jsm"); var root = new fileutils.file("\\\\."); var drivesenum = root.directoryentries, drives = []; while (drivesenum.hasmoreelements()) { drives.push(drivesenum.getnext(). queryinterface(components.interfaces.nsilocalfile).path); } creating folders fileutils.getdir() can create a folder automatically if it doesn't exis...
...siuri; see nsiioservice::newuri for getting a string into a nsiuri. var file = url.queryinterface(components.interfaces.nsifileurl).file; // file is a nsifile to load from file://, http://, chrome://, resource:// and other urls directly, use xmlhttprequest or netutil.asyncfetch(). also note that generally you don't need to use nsifile::path. use nsifile directly wherever possible. an example below shows how you should save a path in user prefs. storing nsifile in preferences the following two snippets show the right way to store a file path in user preferences (more about preferences in mozilla): absolute path (nsifile) to store an arbitrary path in user preferences, use this code: // |file| is nsilocalfile. uses services.jsm. // 1. write path to prefs var prefs = services.prefs.getbr...
...And 4 more matches
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
t even bother. stick to javascript. on windows platforms the first time i built mozilla i used this guide. i can't even remember why anymore, but i got stuck in a number of places, and the whole affair ended up taking far longer than i originally expected. much furniture was smashed, much hair torn out by the roots. here's a comprehensive looking guide that's gotten good reviews. 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...
...e issues involved in creating and registering xpcom components, building jar files and manifests, installing the lot into the firefox extensions/ directory and so forth. so it behooves us to piggyback on this infrastructure to build our extension. first of all, think of a catchy name for your extension and create a directory with that name under the /mozilla/extensions/ directory. use only lowercase letters. you should see a bunch of other directories (inspector/, reporter/ and so forth) at the same level in the build tree. note that before actually building anything, the mozilla build system invokes a configuration process that generates the actual makefiles used for the build from makefile templates called makefile.in. the actual makefiles tend to be very similar or identical ...
...name = myextension dist_files = install.rdf include $(topsrcdir)/config/rules.mk a detailed description of the make process, describing the key features of this makefile, can be found here. module and xpi_name are both set to the name of your extension; they should be repeated in all project makefiles so that all of the files land in the same place in the xpi staging area (see below). install_extension_id is the unique id of your extension. this can be a guid, but the format shown above is prettier and, let's face it, a lot easier to remember. you don't have to provide an xpi_pkgname, but if you do an xpi file, suitable for distribution, is automatically created in the root of the xpi staging area (/mozilla/$(moz_objdir)/dist/xpi-stage/). every extension must include ...
...And 4 more matches
Multiple item extension packaging - Archive of obsolete content
s are no longer accepted by amo. a multiple item package provides the ability to package multiple installable bundles which can then be downloaded and installed by a user, or provided pre-packaged with an application or by an external program. every multiple item package must provide an install.rdf file (not old-style install.js!) and has the same requirements as an extension except as noted below. there is currently no feature to prevent or warn the user when installing an older version of an extension. multiple item package file layout the multiple item package file layout is a simplified form of an installable bundle and requires a file extension of xpi. a multiple item package may contain both extensions (e.g. xpi file extension) and themes (e.g. jar file extension). the basic struc...
...ently no feature to prevent or warn the user when installing an older version of an extension. multiple item package file layout the multiple item package file layout is a simplified form of an installable bundle and requires a file extension of xpi. a multiple item package may contain both extensions (e.g. xpi 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...
...roperties 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#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <!-- nsiupdateitem type for a multiple item package --> <em:type nc:parsetype="integer">32</em:type> ... for the firefox and thunderbird 2.0 extension manager you can use ...
...And 4 more matches
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
an extension in firefox. see https://addons.mozilla.org/firefox/216/. install the extension in firefox directly from the above url and relaunch firefox. starting up select “javascript debugger” from the tools menu. targeting javascript for debugging. when venkman first launches, it can only debug the file currently open in your web browser. this is because a lot of javascript files can slow down the browser down if they’re opened for debugging, but you’ll need to lift this restriction in order to develop extensions. uncheck the “exclude browser files” menu item under the debug menu (figure 1). fixme: figure 1: uncheck “exclude browser files.” set up quicknote for the purposes of this explanation, we’re going to use the file-storage mechanism in quicknote1 for our de...
...ened for debugging, but you’ll need to lift this restriction in order to develop extensions. uncheck the “exclude browser files” menu item under the debug menu (figure 1). fixme: figure 1: uncheck “exclude browser files.” set up quicknote for the purposes of this explanation, we’re going to use the file-storage mechanism in quicknote1 for our debugger. install quicknote from the following url and relaunch firefox. https://addons.mozilla.org/firefox/46/. after relaunching firefox, activate quicknote. then select tools:quicknote:float to display it in its own window. using venkman read in source code activate venkman, and then select open windows:quicknote.xul:files on the top-left of the screen. double-click on quicknote.js to open it in source-code view (figure 2). fixme: ...
... continue to shift to that location and start investigating again. fixme: figure 4: adding a watch target mozunit mozunit is a tool for javascript that assists with unit testing. it provides an ui similar to that of eclipse’s junit test runner. it should be very easy for java programmers to get up to speed on it quickly. installing mozunit is a feature of mozlab. ...
...And 4 more matches
Getting Started with Firefox Extensions - Archive of obsolete content
taken from the extensions page. as described in the quoted text, an extension is a small application that adds something new to one or more mozilla applications. ...
...tensions are add-ons, but add-ons can also be themes, plugins, or language packs. this tutorial is about extension development, but themes and language packs are developed in a very similar way. plugins are entirely different, and they will not be covered here. you can read more about plugins and their development in the plugins page. firefox provides a very rich and flexible architecture that allows extension developers to add advanced features, customize the user's experience, and completely replace and remove parts of the browser. the mozilla add-ons repository (amo) holds an extensive number of extensions with a wide variety of functions: content filtering (adblock plus, noscript), web application interaction (delicious bookmarks, ebay companion) and web development (dom inspector, fireb...
... so you should go through this tutorial before giving them a try. we'll begin the tutorial by analyzing a very simple extension. the hello world extension our sample extensions and this tutorial in general are meant for modern versions of firefox, but most of it works on older versions too. we'll now begin with a basic "hello world" extension. let's start by installing it. click on the link below. ...
...And 4 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...
...s, 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 from a number of sources. each source is a js file that contains some special functions not available in regular code. the following files are used: default preferences: these are stored in the directory defaults/pref in the firefox installation directory. current preferences: these are stored in the profile directory with the name prefs.js. this is where the user's settings are stored. this file is updated when preferences are modified by the user. user preferences: the file user.js in the user's profile directory hol...
...ds of other preferences firefox handles that are not readily available to the user. these are hidden because they are too advanced or obscure for regular users to manage, and because the preferences window should be as easy to use as possible. to access all other preferences, enter "about:config" into the location bar. this xul page lists all the preferences defined in the firefox installation, allowing you to change them as you please. as the warning message states, you should be very careful when changing preferences. incorrect values can make firefox behave oddly or break altogether. you can type on the "filter" textbox to search for specific preferences. if you type the word "homepage", it will filter all the preferences and display only the ones which include the word "homepage" in its ...
...And 4 more matches
Intercepting Page Loads - Archive of obsolete content
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", this._loadhandler, true); finally, the actual code for the handler, which is very simple: _onpageload : fu...
... keep your observer code in non-chrome objects (your xpcom 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...
...aevent.target; let webprogress = gbrowser.getbrowserfortab(tab).webprogress; this._toggleprogresslistener(webprogress, ("tabopen" == aevent.type)); }, _toggleprogresslistener : function(awebprogress, aisadd) { if (aisadd) { awebprogress.addprogresslistener(this, awebprogress.notify_all); } else { awebprogress.removeprogresslistener(this); } } this shouldn't be too hard to follow. we register and unregister the progress listeners for the first tab manually, and then add tab open and close event listeners so we can keep track of the rest of the listeners for all the tabs. we're being careful about removing all listeners, as not doing it has the potential of causing memory leaks. there are a couple of things left to do: implementing the progress listener methods, and figur...
...And 4 more matches
The Box Model - Archive of obsolete content
t 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. any xul interface can be broken down into the following basic components: boxes text images alignment and flexibility widths and heights margins and paddings menus, toolbar buttons, and even the most complex elements in xul are composed of these simple ingredients. complex elements are created from simpler ones through xbl, which will be covered later on. once you grasp this simple idea, you'll be able to use the dom inspector and css to ...
... html has been the fact that xul boxes can be oriented vertically or horizontally (this behavior is being introduced into html standards). there are 3 basic box elements in xul: hbox, vbox and box. an hbox is oriented horizontally by default, meaning that its child nodes are displayed next to each other from left to right. a vbox is oriented vertically by default, its child nodes displayed one below the other from top to bottom. a box is a generic version that you can orient as you please, but its default is horizontal orientation, so it's pretty much equivalent to an hbox and it is seldom used. here's a very simple example of an hbox with 3 child buttons: <hbox> <button label="cat" /> <button label="parrot" /> <button label="porcupine" /> </hbox> this is how it looks on mac os (th...
...e 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 we also add flexibility to the "cat" button, this is what we get: now 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...
...And 4 more matches
XPCOM Objects - Archive of obsolete content
ayers. the largest of the two is a compiled platform, mostly written in c++. on top of it lies the chrome, mostly written in xml, javascript and css. in fact, you can separate the two. we often mention other "mozilla based applications". well, those are applications that, simply put, take the underlying platform with perhaps a few changes and additions, and then write their own chrome layer. ...
... the two. we often mention other "mozilla based applications". well, those are applications that, simply put, take the underlying platform with perhaps a few changes and additions, and then write their own chrome layer. this lower layer is called xulrunner, and it is a very powerful platform, providing a very robust development base for web-enabled, cross-platform applications. the fact that it allows to easily create os-independent applications is a big selling point for xulrunner. xpcom is the way in which the two layers (xulrunner and chrome) communicate. most of the objects and functions in the lower layers are hidden from the chrome; those that need to be publicized are exposed through xpcom components and interfaces. you can think of xpcom as a reference to all the capabilities availab...
... using xpcom components is relatively simple, as you've seen in previous examples. ...
...And 4 more matches
Case Sensitivity in class and id Names - Archive of obsolete content
identify elements. we have discovered, however, that many authors are running into trouble with class and id names because they're used to the bugs of browsers that don't fully support open standards. the most common case is where the name uses different case in the document source than is found in the css or javascript. ...
...bugs of browsers that don't fully support open standards. the most common case is where the name uses different case in the document source than is found in the css or javascript. for example, there might be this css: p.warning {color: red; background: yellow;} ...coupled with this html: <p class="warning">warning!</p> in netscape 6, the paragraph in question will have neither red text nor a yellow background. ...
...it is also important to avoid using class or id names which are a case-insensitive match within the same document. ...
...And 4 more matches
Localizing an extension - Archive of obsolete content
his by moving the strings into a string bundle. string bundles are created by establishing a property file that maps keys to string values. for a detailed explanation of how this works, see xul tutorial:property files. ...
...ing the strings into a string bundle. string bundles are created by establishing a property file that maps keys to string values. for a detailed explanation of how this works, see xul tutorial:property files. ...
... for a detailed explanation of how this works, see xul tutorial:property files. create a properties file the first thing we do is create a property file for the literal strings used by the javascript code in stockwatcher2.js: changestring=chg: openstring=open: lowstring=low: highstring=high: volumestring=vol: the stockwatcher2.properties file shown above maps five keys (changestring, openstring, lowstring, highstring, and volumestring) to the corresponding text in english. ...
...And 4 more matches
Images, Tables, and Mysterious Gaps - Archive of obsolete content
nted 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 the mix. note where the image sits by default: its bottom edge is aligned with the baseline of the line box. this placement can be changed with vertical-align-- we'll talk about that in a bit-- but almost n...
...es that are one pixel tall, as illustrated in figure 7. now there's all kinds of space unexpectedly opening up. it's enough to drive a designer mad. how about a fix? there is one obvious fix-- stop creating designs that are dependent on tables and sliced up or single-pixel images-- but it's not terribly practical for many designers, and it sure doesn't help fix old designs that are suddenly blowing apart in recent browsers. there's another obvious fix, which is to make sure your document doesn't trigger the "standards"rendering mode. you can do this by using a doctype that will trigger either "quirks" mode or "almost standards" mode, or not having a doctype appear in your document at all. the lack of a doctype will prevent validation, and so is not recommended. for authors who are worki...
...l 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 style="background: red;"> <img src="smallred.gif" height="1" width="1"></td></tr> <tr><td> <p style="margin: 0.5em;">this is text in another cell of the table. within the textthere is an icon <im...
...And 4 more matches
Modularization techniques - Archive of obsolete content
0; }; the ns_imethod and ns_imethod_(type) macros are basically shorthand for virtual nsresult and virtualtype. on windows they expand to virtual nsresult __stdcall and virtual type __stdcall for com compatibility reasons. you don't have to use them in your interfaces unless you're concerned with com compatibility. all mozilla interfaces inherit from nsisupports. inheriting from nsisupports allows any interface to be interrogated about other interfaces that its instance may support, and insures that reference 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 qu...
... 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 implementations of addref() and release(). they can maintain a single reference count for the entire object, or individual reference counts for each interface. a static object would chose to ignore reference counts altogether. however, a poor implementation of these functions can have negative results, such as memory leaks or inadvertent access of freed ...
... const nsiid &aiid, void **aresult) = 0; ns_imethod lockfactory(prbool alock) = 0; the reason for using factories is that it provides a mechanism for creating an object without having access to the class declaration for that object. calling new foo() requires that at compile time you have access to the class declaration of foo(). a factory allows an implementor to hide both the class declaration and creation details of an object, an extremely important step for allowing maximum flexibility in the implementation of a class and reducing compile time dependencies. it can even be used to eliminate all link time dependencies on the class and its factory entirely. the component manager one of the major goals of our modularization is to remov...
...And 4 more matches
A XUL Bestiary - Archive of obsolete content
and referenced graphics for a xul file, the localization strings are just a dtd, and the content is just the xul. the chrome url this concept of a chrome as an integrated, dynamic thing in some way divorced from the "appcore" is realized in the use of the chrome url to point to chunks of xul and their related files. the chrome url, which appears in place of the http url in pointers like the following global skin processing instruction: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> specifies a chrome to be loaded by the gecko rendering engine. in the example above, the chrome is simply a skin file to be loaded into the xul file, but the chrome can also be used to load whole chromes, as when a <menuitem> in one window brings up a new chrome: <menuitem value="mozilla h...
...zilla's there is a special flag you can use to start mozilla with some chrome other than the default. when you invoke mozilla from the command line with the -chrome flag, you can specify a chrome just as you would in the previous example: mozilla -chrome chrome://help/content/help.xul brings up the help package mentioned in the previous example as a "stand-alone" chrome. this special option allows you to create and access chromes independent of the mozilla browser and begins to suggest some possibilities for xul-as-platform beyond the simple restyling of the browser. package a package is in some ways like a chrome, but it is specific to the mozilla architecture. a package is a chunk of interface code that sits in a particular place within mozilla's package hierarchy. like a chrome, that...
...rl, though that directory exists in the actual structure). when you create different chrome for a package, you can create a subdirectory underneath content whose contents are loaded instead of default. for example, if you want to create a different skin for the navigator package, you can create a subdirectory underneath navigator/skin/ whose contents will be loaded instead of default's. ...
...And 4 more matches
XUL Events - Archive of obsolete content
the events listeners can be attached using addeventlistener and removed using removeeventlistener. some of the events can be attached using attributes as well. when attaching event listeners using attributes, be aware that only one listener can be attached at a time. any previously attached listeners are disconnected. the attribute name is the event name with an 'on' prefix. xul event reference subpages broadcastthe broadcast event is executed when the attributes of the element (such as a broadcaster) being listened to are changed. ...
... the keydown event is sent to an element that has the focus while a key is pressed but not released. attribute: onkeydown keypress the keypress event is sent to an element that has the focus when a key is pressed and released. when the user presses a key, the keydown event is sent first, followed by the keypress event and then the keyup event. in a textbox, a user can normally hold down a key to repeat a character in this case, multiple sets of key events are sent (as if the user pressed the same key repeatedly). attribute: onkeypress keyup the keyup event is sent to an element that has the...
... attribute: ondragover input this event is sent when a user enters text in a textbox. this event is only called when the text displayed would change, thus it is not called when the user presses non-displayable keys. attribute: oninput overflow this event is only sent to a box or other layout element with a css overflow property set to a value other than 'visible'. when there is not enough space to display the contents of the element at full size, the overflow event will be fired. depending on the value of the overflow property, scrollbars may have appeared. for example, if a box has a maximum size of 10...
...And 4 more matches
Custom toolbar button - Archive of obsolete content
to the extensions directory there. note: for information about how to find the profile directory, see: profile folder explanation: the profile directory contains information specific to a user, keeping it separate from the application. if the application is reinstalled or upgraded, information in the profile is not affected. 2. in the extensions directory, create a new directory with the following name. copy the name from here and paste it, to avoid typing errors: custom-toolbar-button@example.com perform the following steps in this new directory, creating two files and a directory there. explanation: the name is a unique identifier for the extension. there is more information about identifiers in a later section of this tutorial. 3. create a plain text file named install.rdf. ...
...py the name from here and paste it, to avoid typing errors: custom-toolbar-button@example.com perform the following steps in this new directory, creating two files and a directory there. explanation: the name is a unique identifier for the extension. there is more information about identifiers in a later section of this tutorial. 3. create a plain text file named install.rdf. copy the following content, making sure that you scroll to get all of it. paste it into the new 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:name="custom button" em:description="my custom toolbar button" em:creator="my name" em:id="custom-too...
...sections for target applications that you do not want. save the file. explanation: this file contains information used by the application's extension manager. sections for target applications specify the versions where the extension works. the last section in the file specifies that this extension adds content to the application. 4. create a plain text file named chrome.manifest. ...
...And 4 more matches
Adding HTML Elements - Archive of obsolete content
element in a xul file, meaning that java applets and tables can be placed in a window. you should avoid using html elements in xul files if you can. (there are some reasons, and the main one concerns the control of the layout described later). however, this section will describe how to use them anyway. remember that xml is case-sensitive though, so you'll have to enter the tags and attributes in lowercase. xhtml namespace in order to use html elements in a xul file, you must declare that you are doing so using the xhtml namespace. this way, mozilla can distinguish the html tags from the xul ones. the attribute below should be added to the window tag of the xul file, or to the outermost html element. xmlns:html="http://www.w3.org/1999/xhtml" this is a declaration of html much like the one we...
... using html elements you can use any html tag although some such as head ...
...file-window" title="find files" orient="horizontal" xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> then, you can use html tags as you would normally, keeping in mind the following: you must add a html: prefix to the beginning of each tag, assuming you declared the html namespace as above. 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 such as head and body are not really useful. some examples of using html elements are shown below. <html:img src="banner.jpg"/> <html:input type="checkbox" valu...
...And 4 more matches
Adding Methods to XBL-defined Elements - Archive of obsolete content
cts, such as window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open(). you can define custom methods for your elements using the method element. the general syntax of methods is as follows: <implementation> <method name="method-name"> <parameter name="parameter-name1"/> <parameter name="parameter-name2"/> . . . <body> <-- method script goes here --> </body> </method> </implementation> a method declaration goes inside the implementation element, like the fields and properties do. the method element contains two type of child elements, parame...
...the method. for example, if the method had three parameters, there would be three parameter elements. you do not need to have any though, in which case the method would take no parameters. the body element contains the script that is executed when the method is called. the names of the parameters are defined as variables in the script as if they had been passed as parameters. ...
...to the method. note that the less-than symbol has to be escaped because otherwise it would look like the start of a tag. you can also use a cdata section to escape the entire block of code. you can call the method by using code such as element.getmaximum(5, 10) where element is a reference to an element defined by the xbl containing the getmaximum method. ...
...And 4 more matches
Anonymous Content - Archive of obsolete content
element. the xul file only needs to specify the outer element while the inner elements are described in the xbl. this is useful for creating a single widget that is made up of a set of other widgets, but can be referred to as only a single widget. mechanisms are provided for adding attributes to the inner elements that were specified on the outer element. ...
...s content that will be added to the scroll 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 displaye...
...zilla will assume that the elements are xbl, not understand them, and your elements won't work correctly. filename input field example another example, this time for a field for entering a filename: <binding id="fileentry"> <content> <textbox/> <button label="browse..."/> </content> </binding> attaching this binding to an element will cause it to contain 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 e...
...And 4 more matches
Creating a Window - Archive of obsolete content
« previousnext » we're going to be creating a simple find files utility throughout this tutorial. first, however, we should look at the basic syntax of a xul file. creating a xul file an xul file can be given any name but it really should have a .xul extension. the simplest xul file has the following structure: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <!-- other elements go here --> </window> this window will not do anything since it doesn't contain any ui elements. those will be added in the next section. in fact, there will not be shown any window at all. if you want to...
...ion 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 be created and set to |true|. the correct way, of course, is to open the window using javascript. no new syntax is necessary as you can use the window.open() function as one can do for html documents. however, one additional flag, called 'chrome' is necessary to indicate to the browser ...
... is to open the window using javascript. no new syntax is necessary as you can use the window.open() function as one can do for html documents. however, one additional flag, called 'chrome' is necessary to indicate to the browser that this is a chrome document to open. this will open the window without the toolbars and menus and so forth that a normal browser window has. ...
...And 4 more matches
List Controls - Archive of obsolete content
l" /> </listbox> like with the html option element, you can assign a value for each item using the value attribute. you can then use the value in a script. the list box will default to a suitable size, but you can control the size with the rows attribute. set it to the number of rows to display in the list box. a scroll bar will appear that the user can use to display the additional rows. the following example demonstrates these additional features: example 2 : source view <listbox rows="3"> <listitem label="butter pecan" value="bpecan" /> <listitem label="chocolate chip" value="chocchip" /> <listitem label="raspberry ripple" value="raspripple" /> <listitem label="squash swirl" value="squash" /> </listbox> the example has been changed to display only 3 rows at a time. values have a...
...u want to have three columns, you will need to add three listcell elements inside each listitem. to specify the text content of a cell, place a label attribute on a listcell. for the simple case where there is only one column, you may also place the label attributes directly on the listitem elements and leave the listcell elements out entirely, as was seen in the earlier listbox examples. ...
...this is much like a regular row except that it is displayed differently. you would use this to create column headers. two new elements are used. the listhead element is used for the header rows, just as the listitem element is used for regular rows. the header row is not a normal row however, so using a script to get the first row in the list box will skip the hea...
...And 4 more matches
Styling a Tree - Archive of obsolete content
styling the tree you can style the tree border and the column headers in the same way as other elements. style added to the tree element will apply to the entire tree. adding a style to the treecol element does not cause the style to be applied to the column but only to the header. the body of the tree must be styled in a somewhat different way than other elements. this is because the tree body is stored in a different way to other elements. the outer treechildren is the only real element in the tree body. the inner elements are just placeholders. setting properties instead, you must use the properties attribute on the rows or cells to set one or more named properties. ...
...rees with static content, rdf built content or with those with a custom view. let's say we want a particular row to have a blue background color. this would be used to implement mozilla mail's labels feature. we'll use a property called 'makeitblue'. you can use whatever name you want. you can set multiple properties by separating them with spaces. set the property on a row or cell, as in the following example: <treerow properties="makeitblue"> css selectors for the tree the style sheet can take this property and use it to change the appearance of the row for unread messages or labels. you can think of the properties as functioning much like style classes, although they require a somewhat more complex syntax to use in a style sheet. this is because you can specify the style for a number ...
... use it to change the appearance of the row for unread messages or labels. you can think of the properties as functioning much like style classes, although they require a somewhat more complex syntax to use in a style sheet. this is because you can specify the style for a number of parts of the cell individually. you can style not only the cell and its text, but the twisty and indentation. the following is the syntax that needs to be used: treechildren::-moz-tree-row(makeitblue) { background-color: blue; } this style which has a complex selector is used to style the background color of rows that have the 'makeitblue' property. this special syntax is needed because the cells themselves are not separate elements. all of the content inside the tree's body is rendered by the treechildren ele...
...And 4 more matches
The Box Model - Archive of obsolete content
« previousnext » in this section, we'll look at how xul handles layout. introduction to boxes the main form of layout in xul is called the 'box model'. this model allows you to divide a window into a series of boxes. elements inside of a box will orient themselves horizontally or vertically. by combining a series of boxes, spacers and elements with flex and pack attributes, you can control the layout of a window. although a box is the fundamental part of xul element layout, it follows a few very simple rules. a box can lay out its children in one of two orientations, either horizontally or vertically. a horizontal box lines up its elements horizontally and a vertical box orients its elements vertically. you can think of a box as one row or one column from an html table. vario...
...s, either horizontally or vertically. a horizontal box lines up its elements horizontally and a vertical box orients its elements vertically. you can think of a box as one row or one column from an html table. various attributes placed on the child elements in addition to some css style properties control the exact position and size of the children. box elements the basic syntax of a box is as follows: <hbox> <!-- horizontal elements --> </hbox> <vbox> <!-- vertical elements --> </vbox> the hbox element is used to create a horizontally oriented box. each element placed in the hbox will be placed horizontally in a row. the vbox element is used to create a vertically oriented box. added elements will be placed underneath each other in a column. there is also a generic box element which de...
...elements will be placed underneath each other in a column. there is also a generic box element which defaults to horizontal orientation, meaning that it is equivalent to the hbox. however, you can use the orient attribute to control the orientation of the box. you can set this attribute to the value horizontal to create a horizontal box and vertical to create a vertical box. thus, the two lines below are equivalent: <vbox></vbox> <box orient="vertical"></box> the following example shows how to place three buttons vertically. example 1 : source view <vbox> <button id="yes" label="yes"/> <button id="no" label="no"/> <button id="maybe" label="maybe"/> </vbox> the three buttons here are oriented vertically as was indicated by the box. to change the buttons so that they are oriented h...
...And 4 more matches
Trees - Archive of obsolete content
Archive › Mozilla › XUL › Tutorial › Trees
« previousnext » xul provides a way to create tabular or hierarchical lists using a tree. the tree one of the more complex elements in xul is the tree. a tree may be used to display rows of text in columns. it can be used with rows either in a flat list or arranged into a hierarchy. a tree also allows the user to rearrange, resize and hide individual columns. some examples of trees include the list of messages in a mail application, or the bookmarks window in mozilla. in some ways, a tree has some similarities with the listbox. both can be used to create tables of data with multiple rows and columns, and both may contain column headers. the tree also supports nested rows, whereas the listbox does not. however, listboxes may contain any type of content, whereas trees may o...
...cify 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. this means that the tree is scalable to any number of rows without any performance problems. of course, this is independant of the performance of the view object itself. a tree ...
...e view is an object which implements the nsitreeview interface. this interface contains thirty properties and functions which you may implement. these functions will be called by the tree as necessary to retrieve data and state about the tree. for instance, the getcelltext() function will be called to get the label for a particular cell in the tree. an advantage of using a tree view is that it allows the view to store the data in a manner which is more suitable for the data, or to load the data on demand as rows are displayed. this allows more flexibility when using trees. naturally, having to implement a tree view with thirty or so properties and methods for every tree can be very cumbersome, especially for simple trees. fortunately, xul provides a couple of built-in view implementations w...
...And 4 more matches
Trees and Templates - Archive of obsolete content
« previousnext » the following describes how to use a template with a tree. adding datasources to trees when using a tree, you will often use a template to build its content, to handle a large amount of hierarchial data. using a template with a tree uses very much the same syntax as with other elements. you need to add a datasources and a ref attribute to the tree element, which specify the datasource and root node to display. multiple rules can be used to indicate different content for different types of data. ...
...ou will often use a template to build its content, to handle a large amount of hierarchial data. using a template with a tree uses very much the same syntax as with other elements. you need to add a datasources and a ref attribute to the tree element, which specify the datasource and root node to display. multiple rules can be used to indicate different content for different types of data. the following example uses the history datasource: <tree datasources="rdf:history" ref="nc:historybydate" flags="dont-build-content"> as described in the previous section, the tree may use a tree builder for template generation instead of the normal content builder. this means that elements will not be created for every row in the tree, making it more efficient. the flags attribute set to the val...
... it is needed. with hierarchical trees, the children don't get generated until the parent nodes have been opened by the user. in the template, there will be one treecell for each column in the tree. the cells should have a label attribute to set the label for the cell. this would normally be set to an rdf property so that the label is pulled from the datasource. template-built tree example the following example demonstrates a template-built tree, in this case for the file system. example 1 : source <tree id="my-tree" flex="1" datasources="rdf:files" ref="nc:filesroot" flags="dont-build-content"> <treecols> <treecol id="name" label="name" primary="true" flex="1"/> <splitter/> <treecol id="date" label="date" flex="1"/> </treecols> <template> <rule> <tre...
...And 4 more matches
The Implementation of the Application Object Model - Archive of obsolete content
wo-fold. the first section of the document describes the motivation and reasoning behind using rdf as the foundation of xul. this section makes a technical argument both for having xul in the first place and for using rdf as the underlying implementation of xul's content model. the second section describes the xul/rdf architecture itself and outlines enhancements to the xul language in order to allow the markup language to reference local data and to indicate how and when it would like to be annotatable with local data. the case for the xul/rdf approach what is xul? xul (pronounced zool) used to be a ravening demon intent upon taking over the earth in ghost busters. in recent years, xul dropped the z from its name and replaced it with an x, and upon doing so, transformed into something f...
...nificant portion of which are redundant. every new kind of content node would have to implement all of these interfaces. several of the implemented functions would even have identical implementations, i.e. duplicate code that would be doing the same thing in the function bodies. here's another problem. the various interfaces, nsicontent et.al., are not yet solidified. they are likely to change following the first release of nglayout, and when they do, anyone that implemented one of those interfaces will have to change as well in order to upgrade to the new world. statement #1 the two points raised in the previous two paragraphs, namely (1) redundancy of methods in the interfaces as well as a likely code redundancy in the implementation of some of those methods, and (2) the desire to be ins...
...quired feature set, is a combination of xul and rdf. the xul/rdf architecture if you've read this far, you should now have a general idea of what the architecture is like, as well as the motivations for choosing such an architecture. now it's time to fill in some of the details by mentioning xul and rdf specifically. a picture (provided by chris waterson) of the xul/rdf architecture is shown below. let's start over on the left side of the picture. a xul document is read into gecko's parser, and a specialized content sink, known as the xul content sink, is responsible for constructing the in-memory rdf graph representation of the xul. the rdf graph represented by the xul is then aggregated with the contents of other rdf stores (like bookmarks or history) to construct a composite data sourc...
...And 4 more matches
browser - Archive of obsolete content
story type: boolean disables global history for the docshell attached to the browser while keeping session history active. disablesecurity type: boolean set this attribute to true to disable the security ui for this browser. omit this attribute off to enable it. ...
...it does not have any correlation with the user's browser homepage; instead it is a convenient property to hold a home page. you can switch to this home page using the gohome method. showcaret type: boolean whether or not to cause a typing caret to be visible in the content area. default is false. ...
... the user's browser homepage; instead it is a convenient property to hold a home page. you can switch to this home page using the gohome method. showcaret type: boolean whether or not to cause a typing caret to be visible in the content area. default is false. src type: uri the uri of the content to appear in the element. type type: one of the values below. the type of browser, which can be used to set access of the document loaded inside the browser. if this is not set, the loaded document has the same access as the window containing the browser. more precisely: the document loaded into a chrome window is always of chrome type. subdocuments of chrome documents are of chrome type, unless the container element (one of iframe, browser or editor) has...
...And 4 more matches
button - Archive of obsolete content
an 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 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. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (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; } 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 ordered from left to right (for horizontal scales) or from top to bottom (for vertical scales) for other elements, the...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. dlgtype...
...And 4 more matches
tabbrowser - Archive of obsolete content
replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata addprogresslistener( listener ) return type: no return value add a progress listener to the browser which will monitor loaded documents. the progress listener should implement the nsiwebprogresslistener interface. addtab( url, referreruri, charset, postdata, owner, allowthirdpartyfixup ) addtab( url, {referreruri: ..., charset: ..., postdata: ..., owner: ..., allowthirdpartyfixup: ..., relatedtocurrent: ... }) return type: tab element opens a new tab that loads a page with the specified url. the rest of the parameters are optional. the row of tabs will appear if needed. firefox 3.6 note the second form of this method was added in firefox 3.6; it allo...
...wser.tabs.loadgroup. the argument should be an array of objects, one for each document to load. the objects may be defined in script and contain a uri property for the url of the page to load. a referreruri property may also be optionally used to set the referrer page. this function returns a reference to the first tab loaded. ...
...ay be defined in script and contain a uri property for the url of the page to load. a referreruri property may also be optionally used to set the referrer page. this function returns a reference to the first tab loaded. loadonetab( url, referreruri, charset, postdata, loadinbackground, allowthirdpartyfixup ) loadonetab( url, { referreruri: ..., charset: ..., postdata: ..., inbackground: ..., allowthirdpartyfixup: ..., relatedtocurrent: ... }) return type: tab element opens a new tab that loads a page with the specified url. the rest of the parameters are optional. this method works the same as addtab except for the loadinbackground parameter which allows you to choose whether to open the new tab in foreground or background. there's also no owner parameter as the owner tab is specified au...
...And 4 more matches
toolbarbutton - Archive of obsolete content
lean 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 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. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (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; } 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 ordered from left to right (for horizontal scales) or from top to bottom (for vertical scales) for other elements, the ...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. dlgtype ...
...And 4 more matches
XULRunner tips - Archive of obsolete content
ger to be able to install any extensions, you first need to enable the extension manager in application.ini. xulrunner 1.8.0 does not load extensions from the application directory; only the xulrunner directory and the user profile directory are checked. however, it seems that with xulrunner 1.9 the xulrunner directory is ignored, while the profile and application directories are checked. ...
... 1.9 or greater, you can create your own alias in your chrome manifest add a "skin" line: skin communicator classic/1.0 skin/communicator/ add a skin folder named "communicator" and add a single css file named "communicator.css" with this content: @import url("chrome://global/skin"); dom inspector to add dom inspector 2.0.* to your xulrunner 1.9.0.* application follow these steps: download the dom inspector (instead of clicking the "add to..." button, right-click and select "save link as..."). save the dom_inspector-*.xpi package to a temporary directory unzip the package copy the following files: chrome/inspector.jar to the chrome directory of your xulrunner application components/inspector-cmdline.js to your components directory defaults/preferen...
...spector/content/viewers/dom/commandoverlay.xul to launch dom inspector in your application, you need to open its main window, with a command like this: window.open("chrome://inspector/content/inspector.xul", "", "chrome"); alternatively, the dom inspector may also be added as an extension: (if you already have inspector installed for another application you can skip to the next step) follow the instructions above through "unzip the package." create a file in the extensions directory of your application with the same name as the dom inspector id (inspector@mozilla.org) containing one line of text -- the exact path to the root directory of dom inspector (where the install.rdf is) like this one: /home/username/.mozilla/firefox/numbersandletters/extensions/inspector@mozilla.org/ n...
...And 4 more matches
NPAPI plugin reference - Archive of obsolete content
np_initialize provides global initialization for a plug-in. ...
... np_initialize provides global initialization for a plug-in. ...
...o repaint part of the window, and so forth. the names of all of these methods begin with npn_ to indicate that they are implemented by the browser and called by the plug-in. np_getmimedescription np_getmimedescription returns a supported mime type list for your plugin. it works on unix (linux) and macos. on windows you have to define supported mimetypes in the dll resource file. np_getvalue allows the browser to query the plug-in for information. np_initialize provides global initialization for a plug-in. np_port contains information required by the window field of an npwindow structure. np_shutdown provides global deinitialization for a plug-in. npanycallbackstruct contains information required during embedded mode printing. npapi plug-in side api this chapter describes methods...
...And 4 more matches
CSS - Archive of obsolete content
Archive › Web › CSS
e -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 identifying a region container in the document that accepts the content flow from the data source.-ms-flow-intothe -ms-flow-into css property is a microsoft extension that gets or sets a value identifying an iframe container in the document that serves as the region's data source.-ms-high-contrast-adjustthe -ms-...
...ate-limit-zonethe -ms-hyphenate-limit-zone css property is a microsoft extension specifying the width of the hyphenation zone.-ms-ime-alignthe -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. ...
...hyphenate-limit-zone css property is a microsoft extension specifying the width of the hyphenation zone.-ms-ime-alignthe -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. ...
...And 4 more matches
Array comprehensions - Archive of obsolete content
g usages, consider using array.prototype.map, array.prototype.filter, arrow functions, and spread syntax. obsolete since gecko 58 (firefox 58 / thunderbird 58 / seamonkey 2.55)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. ...
... array comprehension was previously proposed to be standardized in ecmascript 2016, it provide a useful shortcut for constructing a new array based on the contents of another. ...
...ved from the standard and the firefox implementation. do not use it! ...
...And 4 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
a 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 var s = new java.io.inputstreamreader( c.getinputstream() ); var b = new java.io.bufferedreader( s ); var l, str = ""; while( ( l = b.readline()...
...is accounts for added simplicity and promotes rapid development methodologies. managing context to take advantage of all the operating contexts of jaxer, you'll need to specify how your scripts should behave using the runat attribute of the script tag (or by setting a runat property on a javascript function object). the common values for this attribute are explained below, though there are more than just these. runat=”client” – code contained in this block is restricted to execution client-side, which is also what happens if no runat attribute is specified. runat=”server” – code contained in this block is restricted to execution server-side. runat=”both” – code may be invoked on the client or server side.
...e. runat=”client” – code contained in this block is restricted to execution client-side, which is also what happens if no runat attribute is specified. runat=”server” – code contained in this block is restricted to execution server-side. runat=”both” – code may be invoked on the client or server side. runat=”server-proxy” – allows for the exposure of server-side javascript functions to the browser. jaxer manages ajax calls behind the scenes to accomplish this. while most of the runat attribute values above are self explanatory, the server-proxy concept is best explained through example. consider the code in listing 4. listing 4 - demonstration of server and client context <script runat="serve...
...And 4 more matches
Game promotion - Game development
if you make a good game for a competition and win some prizes in the process your game will automatically be promoted by the organizers and other attendees. you'll be rich and famous, or so they say. many great games get started as a quick, sloppy demo submitted to a competition. if both the idea and the execution are good enough, you will succeed. plus competitions generally require games to follow a mandatory theme, so you can get creative around a theme if you are stuck for ideas. website and blog you should definitely create your own website containing all the information about your games, so people can see what you've worked on. the more information you can include the better — you should include screenshots, description, trailer, press kit, requirements, available platforms, suppor...
... a theme if you are stuck for ideas. website and blog you should definitely create your own website containing all the information about your games, so people can see what you've worked on. the more information you can include the better — you should include screenshots, description, trailer, press kit, requirements, available platforms, support details and more. you'll get bonus points for allowing your users to directly play your games online — at least in demo form. also, you should do some work on seo to allow people to find your games more easily. you should also blog about everything related to your gamedev activities. write about your development process, nasty bugs you encounter, funny stories, lessons learned, and the ups and downs of being a game developer. continually publis...
... 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 media. social media your social media presence is very important — follow the right hashtags, make friends, engage in conversations, help other devs in need. honesty is key and you should be authentic, because nobody likes boring press releases or pushy advertisements. when the time comes your community will help you spread the word about your shiny little game. you should use at least twitter and facebook and be active on appropriate forums — the most popular one i...
...And 4 more matches
Mouse controls - Game development
after completing this lesson at gamedev-canvas-workshop/lesson9.html. the game itself is actually finished, so let's work on polishing it up. we have already added keyboard controls, but we could easily add mouse controls too. listening for mouse movement listening for mouse movement is even easier than listening for key presses: all we need is the listener for the mousemove event. ...
...l. the game itself is actually finished, so let's work on polishing it up. we have already added keyboard controls, but we could easily add mouse controls too. listening for mouse movement listening for mouse movement is even easier than listening for key presses: all we need is the listener for the mousemove event. ...
...nt is even easier than listening for key presses: all we need is the listener for the mousemove event. add the following line in the same place as the other event listeners, just below the keyup event: document.addeventlistener("mousemove", mousemovehandler, false); anchoring the paddle movement to the mouse movement we can update the paddle position based on the pointer coordinates — the following handler function will do exactly that. ...
...And 4 more matches
Paddle and keyboard controls - Game development
ng this lesson at gamedev-canvas-workshop/lesson4.html. the ball is bouncing off the walls freely and you can watch it indefinitely, but currently there's no interactivity. it's not a game if you cannot control it! so let's add some user interaction: a controllable paddle. defining a paddle to hit the ball so, we need a paddle to hit the ball. let's define a few variables for that. ...
...hat. add the following variables near the top of your code, beside your other variables: var paddleheight = 10; var paddlewidth = 75; var paddlex = (canvas.width-paddlewidth) / 2; here we're defining the height and width of the paddle and its starting point on the x axis for use in calculations further on down the code. let's create a function that will draw the paddle on the screen. add the following just below your drawball() function: function drawpaddle() { ctx.beginpath(); ctx.rect(paddlex, canvas.height-paddleheight, paddlewidth, paddleheight); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); } allowing the user to control the paddle we can draw the paddle wherever we want, but it should respond to the user's actions. it's time to implement some keyboard ...
... two event listeners for keydown and keyup events. ...
...And 4 more matches
Animations and tweens - Game development
explore how to implement phaser animations and tweens in our game. animations in phaser, animations, involve taking a spritesheet from an external source and displaying the sprites sequentially. as an example, we will make the ball wobble when it hits something. first of all, grab the spritesheet from github and save it in your /img directory. next, we will load the spritesheet — put the following line at the bottom of your preload() function: game.load.spritesheet('ball', 'img/wobble.png', 20, 20); instead of loading a single image of the ball we can load the whole spritesheet — a collection of different images. 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 fr...
...mages. 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,2,0], 24); to add an animation to the object we use the animations.add() method, which contains the following parameters the name we chose for the animation an array defining the order in which to display the frames during the animation. if you look again at...
...ys that we are displaying frame 0, then 1, then 0, etc. the framerate, in fps. since we are running the animation at 24fps and there are 9 frames, the animation will display just under three times per second. ...
...And 4 more matches
Test your skills: Selectors - Learn web development
the aim of this task is to help you check your understanding of selectors in css. note: you can try out solutions in the interactive 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. selectors one without changing the html, use css to do the following things: make h1 headings blue. give h2 headings a blue background and white text. cause text wrapped in a span to have a font-size of 200%. ...
... 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. selectors one without changing the html, use css to do the following things: make h1 headings blue. give h2 headings a blue background and white text. cause text wrapped in a span to have a font-size of 200%. 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. selectors two without changing the html, make the following changes to the look of the content in this example: give the element with an id of special a yellow background. give the element with a class of alert a 1px gre...
... style links, making the link-state orange, visited links green, and remove the underline on hover. ...
...And 4 more matches
Type, class, and ID selectors - Learn web development
king with files, html basics (study introduction to html), and an idea of how css works (study css first steps.) objective: to learn about the different css selectors we can use to apply css to a document. type selectors a type selector is sometimes referred to as a tag name selector or element selector, because it selects an html tag/element in your document. in the example below we have used the span, em and strong selectors. all instances of <span>, <em> and <strong> elements are therefore styled accordingly. try adding a css rule to select the <h1> element and change its color to blue. the universal selector the universal selector is indicated by an asterisk (*) and selects everything in the document (or inside the parent element if it is being chained together wi...
...ces of <span>, <em> and <strong> elements are therefore styled accordingly. try adding a css rule to select the <h1> element and change its color to blue. the universal selector the universal selector is indicated by an asterisk (*) and selects everything in the document (or inside the parent element if it is being chained together with another element and a descendant combinator). in the following example we have used the universal selector to remove the margins on all elements. this means that instead of the default styling added by the browser, which spaces out headings and paragraphs with margins, everything is close together and we can't see the different paragraphs easily. this kind of behavior can sometimes be seen in "reset stylesheets", which strips out all of the browser sty...
...g added by the browser, which spaces out headings and paragraphs with margins, everything is close together and we can't see the different paragraphs easily. this kind of behavior can sometimes be seen in "reset stylesheets", which strips out all of the browser styling. since the universal selector makes global changes, we use it to deal with very specific situations such as the one outlined below. using the universal selector to make your selectors easier to read one use of the universal selector is to make selectors easier to read and more obvious in terms of what they are doing. for example, if i wanted to select the first child of any descendant element of <article> , no matter what element it was, and make it bold, i could use the :first-child selector, which we will learn more abou...
...And 4 more matches
What is CSS? - Learn web development
prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, and html basics (study introduction to html.) objective: to learn what css is. in the introduction to html module we covered what html is, and how it is used to mark up documents. these documents will be readable in a web browser. ...
... the browser applies to html to make sure it will be basically readable even if no explicit styling is specified by the author of the page. however, the web would be a boring place if all websites looked like that. using css you can control exactly how html elements look in the browser, presenting your markup using whatever design you like. for more on browser/default styles, check out the following video: what is css for? as we have mentioned before, css is a language for specifying how documents are presented to users — how they are styled, laid out, etc. a document is usually a text file structured using a markup language — html is the most common markup language, but you may also come across other markup languages such as svg or xml. presenting a document to a user means con...
...ated information. it can even be used for effects such as animation. have a look at the links in this paragraph for specific examples. css syntax css is a rule-based language — you define rules specifying groups of styles that should be applied to particular elements or groups of elements on your web page. for example "i want the main heading on my page to be shown as large red text." the following code shows a very simple css rule that would achieve the styling described above: h1 { color: red; font-size: 5em; } the rule opens with a selector . this selects the html element that we are going to style. in this case we are styling level one headings (<h1>). we then have a set of curly braces { }. inside those will be one or more declarations, which take the form of property and...
...And 4 more matches
Styling links - Learn web development
er's mouse pointer, styled using the :hover pseudo class. focus: a link when it has been focused (for example moved to by a keyboard user using the tab key or similar, or programmatically focused using htmlelement.focus()) — this is styled using the :focus pseudo class. active: a link when it is being activated (e.g. clicked on), styled using the :active pseudo class. default styles the following example illustrates what a link will behave like by default (the css is simply enlarging and centering the text to make it stand out more.) <p><a href="#">a simple link</a></p> p { font-size: 2rem; text-align: center; } note: all the links in the examples in this page are fake links — a # (hash, or pound sign) is put in place of the real url. this is because if the real links were...
... links at all, just that you should not stray too far from the expected behaviour. you should at least: use underlining for links, but not for other things. if you don't want to underline links, at least highlight them in some other way. make them react in some way when hovered/focused, and in a slightly different way when activated. the default styles can be turned off/changed using the following css properties: color for the text color. cursor for the mouse pointer style — you shouldn't turn this off unless you've got a very good reason. outline for the text outline (an outline is similar to a border, the only difference being that border takes up space in the box and an outline doesn't; it just sits over the top of the background). the outline is a useful accessibility aid, so...
...re distinct. the next two rules use a:focus and a:hover to set focused and hovered links to have different background colors, plus an underline to make the link stand out even more. two points to note here are: the underline has been created using border-bottom, not text-decoration — some people prefer this because the former has better styling options than the latter, and is drawn a bit lower, so doesn't cut across the descenders of the word being underlined (e.g. the tails on g and y). the border-bottom value has been set as 1px solid, with no color specified. doing this makes the border adopt the same color as the element's text, which is useful in cases like this where the text is a different color in each case. finally, a:active is used to give the links an inverted col...
...And 4 more matches
CSS basics - Learn web development
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, we still need to apply this css (above) to your html document. otherwise, the styling won't change the appearance of the html. (if you haven't been following our project, pause here to read dealing with files and html basics.) open your index.html file. paste the following line in the head (between the <head> and </head> tags): <link href="styles/style.css" rel="stylesheet"> save index.html and load it in your browser. you should see something like this: if your paragraph text is red, congratulations! your css is working. anatomy of a c...
...ere between the <head> and </head> tags). it looks something like this: <link href="https://fonts.googleapis.com/css?family=open+sans" rel="stylesheet"> this code links your page to a style sheet that loads the open sans font family with your webpage. next, delete the existing rule you have in your style.css file. it was a good test, but let's not continue with lots of red text. add the following lines (shown below), replacing the font-family assignment with your font-family selection from what will your website look like?. the property font-family refers to the font(s) you want to use for text. this rule defines a global base font and font size for the whole page. since <html> is the parent element of the whole page, all elements inside it inherit the same font-size and font-family. ...
... google fonts */ } note: anything in css between /* and */ is a css comment. the browser ignores comments as it renders the code. css comments are a way for you to write helpful notes about your code or logic. now let's set font sizes for elements that will have text inside the html body (<h1>, <li>, and <p>). we'll also center the heading. finally, let's expand the second ruleset (below) with settings for line height and letter spacing to make body content more readable. h1 { font-size: 60px; text-align: center; } p, li { font-size: 16px; line-height: 2; letter-spacing: 1px; } adjust the px values as you like. your work-in-progress should look similar to this: css: all about boxes something you'll notice about writing css: a lot of it is about boxes. this in...
...And 4 more matches
What’s in the head? Metadata in HTML - Learn web development
ts, then refreshing the page in your browser. have some fun with it. the <title> element contents are also used in other ways. for example, if you try bookmarking the page (bookmarks > bookmark this page or the star icon in the url bar in firefox), you will see the <title> contents filled in as the suggested bookmark name. the <title> contents are also used in search results, as you'll see below. metadata: the <meta> element metadata is data that describes data, and html has an "official" way of adding metadata to a document — the <meta> element. of course, the other stuff we are talking about in this article could also be thought of as metadata too. there are a lot of different types of <meta> elements that can be included in your page's <head>, but we won't try to explain them all ...
... 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 searc...
... in the browser tab containing each open page, and next to bookmarked pages in the bookmarks panel. a favicon can be added to your page by: saving it in the same directory as the site's index page, saved in .ico format (most browsers will support favicons in more common formats like .gif or .png, but using the ico format will ensure it works as far back as internet explorer 6.) adding the following line into your html's <head> block to reference it: <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> here is an example of a favicon in a bookmarks panel: there are lots of other icon types to consider these days as well. for example, you'll find this in the source code of the mdn web docs homepage: <!-- third-generation ipad with high-resolution retina display: --> ...
...And 4 more matches
Making asynchronous programming easier with async and await - Learn web development
to use them. the basics of async/await there are two parts to using async/await in your code. the async keyword first of all we have the async keyword, which you put in front of a function declaration to turn it into an async function. an async function is a function that knows how to expect the possibility of the await keyword being used to invoke asynchronous code. try typing the following lines into your browser's js console: function hello() { return "hello" }; hello(); the function returns "hello" — nothing special, right? but what if we turn this into an async function? try the following: async function hello() { return "hello" }; hello(); ah. invoking the function now returns a promise. this is one of the traits of async functions — their return values are guarante...
...unction definition you can see that the code closely resembles the previous promise version, but there are some differences. instead of needing to chain a .then() block on to the end of each promise-based method, you just need to add an await keyword before the method call, and then assign the result to a variable. the await keyword causes the javascript runtime to pause your code on this line, allowing other code to execute in the meantime, until the async function call has returned its result. once that's complete, your code continues to execute starting on the next line. for example: let response = await fetch('coffee.jpg'); the response returned by the fulfilled fetch() promise is assigned to the response variable when that response becomes available, and the parser pauses on this line ...
... so it's compatible with all the features offered by promises. this includes promise.all() — you can quite happily await a promise.all() call to get all the results returned into a variable in a way that looks like simple synchronous code. again, let's return to an example we saw in our previous article. keep it open in a separate tab so you can compare and contrast with the new version shown below. converting this to async/await (see live demo and source code), this now looks like so: async function fetchanddecode(url, type) { let response = await fetch(url); let content; if (!response.ok) { throw new error(`http error! status: ${response.status}`); } else { if(type === 'blob') { content = await response.blob(); } else if(type === 'text') { content = awa...
...And 4 more matches
Functions — reusable blocks of code - Learn web development
in this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define them, scope, and parameters. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps. objective: to understand the fundamental concepts behind javascript functions. ...
...d a random number: let mynumber = math.random(); // the random() function generates a random number between // 0 and up to but not including 1, and returns that number ...we were using a function! note: feel free to enter these lines into your browser's javascript console to re-familiarize yourself with their functionality, if needed. ...
...ed. the javascript language has many built-in functions to allow you to do useful 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 det...
...And 4 more matches
Test your skills: Strings - Learn web development
this aim of this skill test is to assess whether you've understood our handling text — strings in javascript and useful string methods articles. note: you can try out solutions in the interactive 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. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). strings 1 in our first strings task, we start off small. you already have half of a famou...
...he other half of the quote, and add it to the example inside a variable called quoteend. concatenate the two strings together to make a single string containing the complete quote. save the result inside a variable called finalquote. you'll find that you get an error at this point. can you fix the problem with quotestart, so that the full quote displays correctly? 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. strings 2 in this task you are provided with two variables, quote and substring, which contain two strings. we would like you to: retrieve the length of the quote, and store it in a variable called quotelength. find the index position where substring appears in...
... quote, and store it in a variable called quotelength. find the index position where substring appears in quote, and store that value in a variable called index. use a combination of the variables you have and available string properties/methods to trim down the original quote to "i do not like green eggs and ham.", and store it in a variable called revisedquote. ...
...And 4 more matches
Adding features to our bouncing balls demo - Learn web development
te javascript/css panels, feel free to put them inline <script>/<style> elements inside the html page. note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. hints and tips a couple of pointers before you get started. this assessment is quite challenging. read the whole assessment before you start coding, and take each step slowly and carefully. it might be a good idea to save a separate copy of the demo after you get each stage working, so you can refer back to it if you find yourself in trouble later on. project brief our bouncy ball demo is fun, but now we want to make it a little bit more interactive by adding a user-controlled evil circle, which will eat the balls if it catches them. we also want to test your ob...
...ur bouncy ball demo is fun, but now we want to make it a little bit more interactive by adding a user-controlled evil circle, which will eat the balls if it catches them. we also want to test your object-building skills by creating a generic shape() object that our balls and evil circle can inherit from. finally, we want to add a score counter to track the number of balls left to capture. the following screenshot gives you an idea of what the finished program should look like: to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do. creating our new objects first of all, change your existing ball() constructor so that it becomes a shape() constructor and add a new ball() ...
...computer-controlled evil circles. you're probably not going to take over the world with a single evil circle, but it will do for this assessment. the evilcircle() constructor should inherit x, y, velx, vely, and exists from shape(), but velx and vely should always equal 20. you should do this something like shape.call(this, x, y, 20, 20, exists); it should also define its own properties, as follows: color — 'white' size — 10 again, remember to define your inherited properties as parameters in the constructor, and set the prototype and constructor properties correctly. defining evilcircle()'s methods evilcircle() should have four methods, as described below. draw() this method has the same purpose as ball()'s draw() method: it draws the object instance on the canvas. it will w...
...And 4 more matches
Perceived performance - Learn web development
ter. 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, like staring at a monochrome screen. if both the passive and acti...
...ely 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 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 init...
...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, loading them when they become necessary. loading additional assets and resources after initial page load improves perceived performance. ...
...And 4 more matches
Componentizing our React app - Learn web development
ible 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 valuable: making a component out of common ui elements allows you to change your code in one place and see those changes everywhere that component is used. you don't have to break everything out into components right away, either. let's take the second bullet point as inspiration and make a component out of the most reused, most important piece of the ui: a todo list item. make a <todo /> before we can make a component, we should create a new file for it...
...e that component is used. you don't have to break everything out into components right away, either. let's take the second bullet point as inspiration and make a component out of the most reused, most important piece of the ui: a todo list item. make a <todo /> before we can make a component, we should create a new file for it. in fact, we should make a directory just for our components. the following commands make a components directory and then, within that, a file called todo.js. make sure you're in the root of your app before you run these! mkdir src/components touch src/components/todo.js our new todo.js file is currently empty! open it up and give it its first line: import react from "react"; since we're going to make a component called todo, you can start adding the code for that...
...ponents directory and then, within that, a file called todo.js. make sure you're in the root of your app before you run these! mkdir src/components touch src/components/todo.js our new todo.js file is currently empty! open it up and give it its first line: import react from "react"; since we're going to make a component called todo, you can start adding the code for that to todo.js too, as follows. in this code, we define the function and export it on the same line: export default function todo() { return ( ); } this is ok so far, but our component has to return something! go back to src/app.js, copy the first <li> from inside the unordered list, and paste it into todo.js so that it reads like this: export default function todo() { return ( <li classname="todo stack-small"> ...
...And 4 more matches
Adding a new todo form: Vue events, methods, and models - Learn web development
this is what we'll cover in this article. ...
...nctions), you'll need a terminal with node + npm installed. objective: to learn about handling forms in vue, and by association, events, models, and methods. creating a new to-do form we now have an app that displays a list of to-do items. however, we can't update our list of items without manually changing our code! let's fix that. let's create a new component that will allow us to add a new to-do item. in your components folder, create a new file called todoform.vue. add a blank <template> and a <script> tag like before: <template></template> <script> export default {}; </script> let's add in an html form that lets you enter a new todo item and submit it into the app. we need a <form> with a <label>, an <input>, and a <button>. update your tem...
... new to-do item. in your components folder, create a new file called todoform.vue. add a blank <template> and a <script> tag like before: <template></template> <script> export default {}; </script> let's add in an html form that lets you enter a new todo item and submit it into the app. we need a <form> with a <label>, an <input>, and a <button>. ...
...And 4 more matches
Understanding client-side JavaScript frameworks - Learn web development
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. 2. beginning our react todo list let's say that we’ve been tasked with creating a proof-of-concept in react – an app that allows users to add, edit, and delete tasks they want to work on, and also mark tasks as complete without deleting them. this article will walk you through putting the basic app component structure and styling in place, ready for individual component definition and interactivity, which we'll add later. 3. componentizing our react app at this point, our app is a monolith. before we can make it do thin...
... 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. 4. ...
...we'll look at conditional ui rendering along the way. 6. ...
...And 4 more matches
Accessibility API cross-reference
vel is expressed with the aria-level attribute. heading <h1> ... <h6> <h1> ... <h6>. <h> is also available but its use is not recommended because of lack of suitable tools - and the heading level is undefined click on this thing and then click on the item for tooltip style help helpballoon n/a n/a n/a editable field that allows user to assign a key combination hotkeyfield n/a n/a n/a graphic that indicates something, such as an arrow indicator n/a n/a n/a abstract role - a generic type of widget that allows user input. input n/a hypertext link that can be on image or text link n/a link <a...
...in meaningful order and old information may disappear. log the main content of a document, distinct from complementary info, headers, footers, navigation, asides etc. main <main> a type of live region where non-essential information changes frequently. marquee the main menu bar below the app's title bar menubar menu_bar menu_bar menubar a menu item menuitem menu_item menu_item menuitem a menuitem with a checkable state whose possible values are true, false, or mixed. menuitemcheckbox a checkable menuitem in a set of elements with the same role, only one of which c...
...ended for specifying search criteria. searchbox a renderable structural containment unit in a document or application. section (abstract role) <section> <sect> a structure that labels or summarizes the topic of its related section. 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=r...
...And 4 more matches
Accessibility Features in Firefox
ire vox extension. fire vox can also be used on windows or os x. for more detailed information, please check the assistive technology compatibility guide is kept on an editable wiki. keyboard support "mozilla firefox is a web-browser with superior keyboard support." alan cantor, cantor access consulting firefox includes keyboard access to all of its amazing features: browse with caret allows users to select arbitrary content with the keyboard and move through content as if inside a read-only editor. this allows copying arbitrary pieces of text to the clipboard. the f7 key toggles this feature on/off. tabbed browsing helps keyboard users by putting all of the browsed documents in one firefox application window rather than cluttering the alt+tab order which makes keyboard navigation ...
...ing the alt+tab order which makes keyboard navigation within the entire windows os much simpler. both history and bookmarks can be searched with a "quick search" field that quickly narrows the list down via a substring search. bookmarks can have a keyword assigned to them which can be typed into the address bar to bring up the bookmark. a "smart keywords" feature enhances this even further by allowing custom searches from the command line such as "word punditry" to look up the word "punditry" in an online dictionary. these smart keywords can be setup via the context menu for 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 swi...
... 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 there are far fewer keys to type to get the desired location. for example, it is possi...
...And 4 more matches
CSUN Firefox Materials
is a great little browser. it's a quick download, occupies very little disk space, and has a clean, no-nonsense interface." - pc magazine firefox 1.5 is a fast, free, standards compliant web browser which is rapidly gaining recognition for its fresh, streamlined approach to browsing the web. in addition to winning major awards such as pc world product of the year, firefox has attracted a huge following among savvy users who simply care enough about their web browsing experience to download a new piece of software. websites such as online magazines with sophisticated audiences are now reporting upwards of 25% firefox usage. why do the most discerning users switch to firefox? because firefox rethinks the web, and does away with many of the common annoyances that cause browsing to be difficult ...
...d support in the industry via gok, the gnome onscreen keyboard. basic screen reader accessibility is available via gnopernicus or the fire vox extension. keyboard support "mozilla firefox is a web-browser with superior keyboard support. " - alan cantor, cantor access consulting (http://www.cantoraccess.com) firefox includes keyboard access to all of its amazing features: find as you type 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 there are far fewer keys to type to get the desired location. for example, it is possible to navigate to the desired link by pressing 2 letter keys ...
...the f7 key toggles this feature on/off. ...
...And 4 more matches
Theme concepts
er, programmatically include a theme in an extension using the theme api. see dynamic themes. defining a theme to create a theme (in this example a simple, single image theme): create a folder in a suitable location on your computer. add the theme image file to the folder: <mytheme> <your_header_image>.<type> create a file called manifest.json in the folder and edit its content as follows: { "manifest_version": 2, "version": "1.0", "name": "<your_theme_name>", "theme": { "images": { "theme_frame": "<your_header_image>.<type>" }, "colors": { "frame": "#ffffff", "tab_background_text": "#000" } } } where: "frame": is the heading area background color for your theme. "tab_background_text": the color of the text in the heading...
...me": "<your_theme_name>", "theme": { "images": { "theme_frame": "<your_header_image>.<type>" }, "colors": { "frame": "#ffffff", "tab_background_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: ...
... 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 of 200 pixels high. the maximum image width is determined by the resolution of the monitor firefox is displaying on and how much of the monitor firefox is using. practically, this means you would need to allow for a width of up to 5120 pixels wide (for the next generation of 5k monitors). however, rather than creating a very wide image, a better approach is to use a narrower image with a transparent left edge so that it fades to the background color. for example, we could use this image combined with a complementary background color, to create this effect in the header see details about this them...
...And 4 more matches
Browser API
it currently works in (privileged) chrome code on firefox desktop (version 47 and above). browser api concepts and usage the browser api consists of two major parts: custom <iframe> attributes: by adding a mozbrowser attribute to the <iframe> element we can make it appear like a top-level browser window to the embedded content. this means that window.top, window.parent, window.frameelement, etc. should not reflect the frame hierarchy. ...
.... api extensions: the api includes several new methods and events to manipulate and listen for changes to the embedded content's state, interited by the htmliframeelement interface. browser api interfaces to support the requirement of a browser <iframe>, the htmliframeelement dom interface has been extended with new methods that give the <iframe> some super powers. navigation methods the following navigation methods allow navigation through the browsing history of the <iframe>. they are necessary to be able to implement back, forward, stop, and reload buttons. htmliframeelement.reload() allows reloading of the <iframe> element content. htmliframeelement.stop() allows stopping of the <iframe>'s content loading. htmliframeelement.getcangoback() indicates whether it's possible to n...
...mationframe. htmliframeelement.getvisible() indicates the current visibility state of the browser <iframe>. htmliframeelement.setactive() sets the current <iframe> as the active frame, which has an effect on how it is prioritized by the process manager. htmliframeelement.getactive() indicates whether the current browser <iframe> is the currently active frame. audio-related methods the following methods allow direct control of sound in the browser element. htmliframeelement.getvolume() gets the current volume of the browser <iframe>. htmliframeelement.setvolume() sets the current volume of the browser <iframe>. htmliframeelement.mute() mutes any audio playing in the browser <iframe>. htmliframeelement.unmute() unmutes any audio playing in the browser <iframe>. htmliframeele...
...And 4 more matches
gettext
default keyword for regular messages is gettext() and _(). for messages with plural support, the default keyword is ngettext(). a definition of a string with plurals takes three arguments: the singular form of the english string, the plural form of the english string, and the number basing on which the function will return the correct (singular or plural) form of the string. 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 th...
...m 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 with the value of $num. for english, the above code will produce the following output: 1 user likes this. the string definition in the messages.po file will look like this: #: file.php: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 msgst...
...ts 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 equals 1, the expression is evaluated to false, or 0, so msgstr[0] will be used. consider another example, gaeilge (irish): plural-forms: nplurals=3; plural=n==1...
...And 4 more matches
Fonts for Mozilla's MathML engine
fonts with appropriate unicode coverage and open font format features are required for good math rendering. this wiki page describes how users can install and use such math fonts with mozilla's mathml engine. note that most of these instructions may as well apply to other web rendering engines. installation instructions windows install the latin modern math and stix fonts as follows: download latinmodern-math-1959.zip. open the zip archive, move inside the latinmodern-math-1959 directory and then inside the otf directory. you will find a latinmodern-math font file. open the latinmodern-math font file and click the install button. download stixv2.0.2.zip. open the zip archive, move inside the /stixv2.0.0/fonts/otf/ directory. you will find the stixmath-regular, stix-regular, ...
...lar font file and click the install button. if desired, you may also do the same for the other font files. note:cambria math is installed by default on windows 7 and later versions and should ensure relatively good mathml rendering. an enhancement request has been submitted to microsoft to install latin modern math and stix by default. os x install the latin modern math and stix fonts as follows: download latinmodern-math-1959.zip. extract the zip archive, move inside the latinmodern-math-1959 directory and then inside the otf directory. you will find a latinmodern-math font file. double-click the latinmodern-math font file click the "install the font" button from the window that opens. download stixv2.0.2.zip. open the zip archive, move inside the /stixv2.0.0/fonts/otf/ director...
...ively 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. ...
...And 4 more matches
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. ...
...you may also want to check out the mozilla mathml torture test to test your installation against concrete examples. ...
...support for mathvariant attribute (e.g. to write double-struck, script or fraktur text). all the fonts mentioned above may already be installed by default on your system or can easily be installed via your software manager. for convenience we provide a zip archive of mathml fonts. the fonts may be installed by extracting the font files (which have the .otf extension) from the zip archive, then following instructions for microsoft windows, or copying the files to a ~/library/fonts folder on mac os x, or to a ~/.fonts/ directory (which may need to be created) on unix/linux systems. alternatively, follow dafont's "how to install a font". these fonts are opentype postscript fonts, which are supported by most modern operating systems. however some operating systems may not support these fonts. on ...
...And 4 more matches
MathML Demo: <mo> - operator, fence, separator, or accent
the symbols occur in the context of a simple expression. in general, the lspace and rspace around the relation should be greater than that around the operation. operator and relations center vertically on the math axis. ...
...the symbols occur in the context of a simple expression. in general, 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.
...the symbols occur in the context of a simple expression. in general, the lspace and rspace around negated relations should be similar to the spacing around relations. a + b ≠ c ⋅ d a + b = c ⋅ d a - b ∉ c * d a - b ∈ c * d a +...
...And 4 more matches
Mozilla Port Blocking
mozilla responded by modifying how protocols can access ports. ...
...mozilla responded by modifying how protocols can access ports. ...
..."cross-protocol scripting". each protocol's handler can override this blocking for itself in order to enable the required access for that protocol. potential problems caused by port blocking port blocking can cause problems if a site or web application requires access to one of the ports which is blocked in mozilla. ...
...And 4 more matches
Investigating leaks using DMD heap scan mode
when combined with cycle collector logging, this can be used to investigate leaks of refcounted cycle collected objects, by figuring out what holds a strong reference to a leaked object. when should you use this? dmd heap scan mode is intended to be used to investigate leaks of cycle collected (cced) objects. ...
... mode is a "tool of last resort" that should only be used when all other avenues have been tried and failed, except possibly ref count logging. it is particularly useful if you have no idea what is causing the leak. if you have a patch that introduces a leak, you are probably better off auditing all of the strong references that your patch creates before trying this. the particular steps given below are intended for the case where the leaked object is alive all the way through shutdown. you could modify these steps for leaks that go away in shutdown by collecting a cc and dmd log prior to shutdown. however, in that case it may be easier to use refcount logging, or rr with a conditional breakpoint set on calls to release() for the leaking object, to see what object actually does the release t...
... refcount logging, or rr with a conditional breakpoint set on calls to release() for the leaking object, to see what object actually does the 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_shutd...
...And 4 more matches
Scroll-linked effects
scrolling model, the visual scroll position is updated in the compositor thread and is visible to the user before the scroll event is updated in the dom and fired on the main thread. this means that the effects implemented will lag a little bit behind what the user sees the scroll position to be. this can cause the effect to be laggy, janky, or jittery — in short, something we want to avoid. below are a couple of examples of effects that would not work well with asynchronous scrolling, along with equivalent versions that would work well: example 1: sticky positioning here is an implementation of a sticky-positioning effect, where the "toolbar" div will stick to the top of the screen as you scroll down. <body style="height: 5000px" onscroll="document.getelementbyid('toolbar').style.top =...
...ener is to use the css property designed for this purpose: <body style="height: 5000px"> <div id="toolbar" style="position: sticky; top: 0px; margin-top: 100px; width: 100px; height: 20px; background-color: green"></div> </body> this version works well with asynchronous scrolling because position of the "toolbar" div is updated by the browser as the user scrolls. example 2: scroll snapping below is an implementation of scroll snapping, where the scroll position snaps to a particular destination when the user's scrolling stops near that destination. <body style="height: 5000px"> <script> function snap(destination) { if (math.abs(destination - window.scrolly) < 3) { scrollto(window.scrollx, destination); } else if (math.abs(destination - window.scrolly) < ...
...he "snaptarget" div. if it is, then it triggers an animation to "snap" the scroll position to the top of the div. as this animation is driven by javascript on the browser's main thread, it can be interrupted by other javascript running in other tabs or other windows. therefore, the animation can end up looking janky and not as smooth as intended. instead, using the css snap-points property will allow the browser to run the animation asynchronously, providing a smooth visual effect to the user. <body style="height: 5000px"> <style> body, /* blink currently has bug that requires declaration on `body` */ html { scroll-snap-type: y proximity; } .snaptarget { scroll-snap-align: start; position: relative; top: 200px; height: 200px; background-co...
...And 4 more matches
TimerFirings logging
or every timer fired. this is useful because timer firings are a major cause of wakeups, which can cause high power consumption. 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. invocation timerfirings logging uses gecko's own logging mechanism, and so is able to be used in any build. set the following environment variable to enable it. nspr_log_modules=timerfirings:4 output once enabled, timerfirings will print one line of logging output per timer fired. it's best to redirect this output to a file. the following sample shows the basics of this output. -991946880[7f46c365ba00]: [6775] fn timer (slack 100 ms): layeractivitytracker -991946880[7f46c365ba00]: [6775] fn timer (one...
... the first two values identify the thread. this is not especially useful. the next value is the process id (pid). this is useful in a multi-process scenario. next is the timer kind, one of fn (function), iface (interface) or obs (observer), which are the three kinds of timers that gecko supports. then comes the function kind, one of one_shot (a single-use timer), slack or pre...
...conds. finally there is the identifying information for the timer. function timers have an informative label. interface and observer timers only have an address, which is less useful, but they are uncommon enough that this usually doesn't matter much. the above example shows only timers from c++ within gecko. there are also timers for settimer or setinterval calls in javascript code, as the following sample shows. -991946880[7f46c365ba00]: [6775] fn timer (one_shot 0 ms): [content] chrome://browser/content/tabbrowser.xml:1816:0 711637568[7f3219c48000]: [6835] fn timer (one_shot 100 ms): [content] http://edition.cnn.com/:5:7231 711637568[7f3219c48000]: [6835] fn timer (one_shot 100 ms): [content] http://a.visualrevenue.com/vrs.js:6:9423 these js timers are annotated with...
...And 4 more matches
Introduction to Network Security Services
erations. we guarantee that applications using the exported apis will remain compatible with future versions of those libraries. for a complete list of public functions exported by these shared libraries in nss 3.2, see nss functions. for information on which static libraries in nss 3.1.1 are replaced by each of the above shared libraries in nss 3.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 an...
...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. ...
...tion, 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-ux shared library libnss.a - unix static library nss3.dll - windows shared library nss3.lib - windows import library binding to nss3.dll nss.lib - windows static library nss, ssl, and s/mime have all of the above forms. the following static libaries aren't included in any shared libraries libcrmf.a/crmf.lib provides an api for crmf operations. libjar.a/jar.lib provides an api for creating jar files. the following static libaries are included only in external loadable pkcs #11 modules: libnssckfw.a/nssckfw.lib provides an api for writing pkcs #11 modules. libswfci.a/swfci.lib provides support for software fortezza...
...And 4 more matches
JSS Provider Notes
ner tool, which is distributed with the jdk. if you build jss yourself from source instead of using binaries downloaded from mozilla.org, your jar file will not have a valid signature. this means you will not be able to use the jss provider for jce algorithms. you have two choices. use the binary release of jss from mozilla.org. apply for your own jce code-signing certificate following the procedure at how to implement a provider for the javatm cryptography extension. then you can sign your own jss jar file. installing the provider in order to use any part of jss, including the jca provider, you must first call cryptomanager.initialize(). by default, the jca provider will be installed in the list of providers maintained by the java.security.security class. if yo...
...per-thread default token setting is only consulted inside getinstance(). once a jca object has been created it will continue to use the same token, even if the application later changes the per-thread default token. whenever a new thread is created, its token is initialized to the default, the internal key storage token. thus, the thread token is not inherited from the parent thread. ...
...se tokenb // was the per-thread default token when dsakpg was created. dsakpg.initialize(1024); keypair dsapair = dsakpg.generatekeypair(); supported classes cipher dsaprivatekey dsapublickey keyfactory keygenerator keypairgenerator mac messagedigest rsaprivatekey rsapublickey secretkeyfactory secretkey securerandom signature what's not supported the following classes don't work very well: keystore: there are many serious problems mapping the jca keystore interface onto nss's model of pkcs #11 modules. the current implementation is almost useless. since these problems lie deep in the nss design and implementation, there is no clear timeframe for fixing them. meanwhile, the org.mozilla.jss.crypto.cryptostore class can be used for some of ...
...And 4 more matches
Mozilla-JSS JCA Provider notes
sing the jarsigner tool, which is distributed with the jdk. if you build jss yourself from source instead of using binaries downloaded from mozilla.org, your jar file will not have a valid signature. this means you will not be able to use the jss provider for jce algorithms. you have two choices. use the binary release of jss from mozilla.org. apply for your own jce code-signing certificate following the procedure at how to implement a provider for the javatm cryptography extension. then you can sign your own jss jar file. installing the provider in order to use any part of jss, including the jca provider, you must first call cryptomanager.initialize(). by default, the jca provider will be installed in the list of providers maintained by the java.security.security class. if you do not wi...
.... the per-thread default token setting is only consulted inside getinstance(). once a jca object has been created it will continue to use the same token, even if the application later changes the per-thread default token. whenever a new thread is created, its token is initialized to the default, the internal key storage token. thus, the thread token is not inherited from the parent thread. ...
...efault token when dsakpg was created. ...
...And 4 more matches
nss tech note1
rena is a pointer to an nspr arena pool. this is the arena pool from which the decoder will allocate memory as needed. decoder templates : the sec_asn1template structure tells the decoder what to do with the input data. this structure contains four fields : kind . this 32-bit field tells the decoder what to do with a particular component within the input data. it is made of two parts : the lower byte, which can contain asn.1 tags, and the upper 3 bytes, which can contain decoder modifiers. if only an asn.1 tag is specified without a modifier, then the decoder will enforce the presence of a component of that type, and fail if it does not match. if kind is an asn.1 sequence tag (sec_asn1_sequence), then you must specify additional templates in a null-terminated array to define the conten...
...y required for dynamically allocating memory for the structure if the template is being included from an asn.1 sequence or sequence of, or if dynamic allocation was requested from the parent template using the sec_asn1_pointer modifier here is a description of the various tags and modifiers that apply to the <tt style="color: rgb(0,0,0);">kind field. asn.1 tags asn.1 tags are specified in the lower byte of the kind field of the template, as noted above. the following is not an attempt to explain asn.1 tags or their purposes. rather, the goal here is to explain what type of tags the decoder supports and which macros should be used when defining tags in decoder templates. it should be noted that we only support an older specification of asn.1; multibyte tags are not currently supported. t...
...ontext-specific, and private. you can specify the class of the tag using the macros sec_asn1_universal, sec_asn1_application, sec_asn1_context_specific and sec_asn1_private. universal is the default tag class and does not have to be specified, as the value of the class type is zero. the method type : whether the component type is constructed or primitive. this information is stored in the next lowest tag bit (number 5). you can use the macro sec_asn1_constructed for a constructed component type. a sec_asn1_primitive macro is also provided, but does not need to be included as it is zero. the tag number. it is stored in the lower 5 tag bits (number 0 through 4). the asn.1 standard only defines tag numbers in the universal class. if you you are using a tag of a different classes, you can d...
...And 4 more matches
NSS_3.12.3_release_notes.html
nss 3.12.3 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1. ...
...able is excerpted from https://developer.mozilla.org/en/nss_reference/nss_environment_variables environment variable value type description nsrandcount integer (byte count) sets the maximum number of bytes to read from the file named in the environment variable nsrandfile (see below). makes nsrandfile usable with /dev/urandom. nss_allow_weak_signature_alg boolean (any non-empty value to enable) enables the use of md2 and md4 hash algorithms inside signatures. this was allowed by default before nss 3.12.3. nss_hash_alg_support string specifies algorithms allowed to be u...
... (any non-empty value to enable) tells nss to send ec key points across the pkcs#11 interface in the non-standard unencoded format that was used by default before nss 3.12.3. the new key point format is a der encoded asn.1 octet string. nss_use_shexp_in_cert_name boolean (any non-empty value to enable) tells nss to allow shell-style wildcard patterns in certificates to match ssl server host names. this behavior was the default before nss 3.12.3. the new behavior conforms to rfc 2818. new korean seed cipher: new macros for seed support: in blapit.h: nss_seed nss_seed_cbc seed_block_size seed_key_length ...
...And 4 more matches
JS_GetGCParameter
e uint32_t (js_setgcparameter only) the value to assign to the parameter. ...
... 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_pretenure...
...ice_time_budget / "slicetimebudget" max milliseconds to spend in an incremental gc slice. 0 for infinite. jsgc_mark_stack_limit / "markstacklimit" maximum size the gc mark stack can grow to (units: entries). jsgc_high_frequency_time_limit / "highfrequencytimelimit" gcs less than this far apart in time will be considered 'high-frequency gcs'. jsgc_high_frequency_low_limit / "highfrequencylowlimit" controls for dynamic heap growth. when the gc is in "high frequency" mode (see above) then, the heap will be allowed to grow between collections according to these four parameters. see zoneheapthreshold::computezoneheapgrowthfactorforheapsize in gc.cpp for the details. the first two parameters are in mb and the remaining two are in percentage of heap s...
...And 4 more matches
Handling Mozilla Security Bugs
ence. we believe that both sets of concerns are valid, and that both are worth addressing as best we can. we have attempted to create a compromise scheme for how the mozilla project will handle reports of security vulnerabilities. we believe that it is a compromise that can be justified to those on both sides of the question regarding disclosure. ...
... believe that it is a compromise that can be justified to those on both sides of the question regarding disclosure. general policies mozilla.org has adopted the following general policies for handling bug reports related to security vulnerabilities: security bug reports can be treated as special and handled differently than "normal" bugs. in particular, the mozilla.org bugzilla system will allow bug reports related to security vulnerabilities to be marked as "security-sensitive," and will have special access control features specifically for use with such bug reports. however, a security bug can revert back to being a normal bug by having the "security-sensitive" flag removed, in which case the access control restrictions will no longer be in effect. full information about security bugs...
...roup the mozilla security module owner and peers will form the core of the mozilla security bug group, and will select a number of other people to round out the group's membership. each and every member of the mozilla security bug group will automatically have access to all mozilla bugs marked "security-sensitive." the members of the mozilla security bug group will be drawn primarily from the following groups: security developers (i.e., those whose bugs are often singled out as security-relevant or who have security-relevant bugs assigned to them), and security qa people who are the qa contacts for those bugs. exploit hunters with a good track record of finding significant mozilla security vulnerabilities. representatives of the various companies and groups actively distributing mozilla...
...And 4 more matches
Accessing the Windows Registry Using XPCOM
ms. to this end, there exist xpcom interfaces to read and write registry data. this article will show you how to use the available interfaces in several mozilla products. the examples in this document are all written in javascript using xpcom. support in firefox 1.5 or newer in firefox 1.5, a new api was added, nsiwindowsregkey, which provides extensive registry functionality. the interface follows the windows api fairly closely, but with many of the low-level details taken care of for you. if you are writing an extension that only needs to support firefox 1.5 or newer, then you only need to read this section. a simple example here's a simple example showing how to read your windows productid: var wrk = components.classes["@mozilla.org/windows-registry-key;1"] .creat...
...above shows how to read an existing string value. however, windows registry values can have several data types, so you need to ensure that you read the correct type. you can check the type of a value using the method getvaluetype(). this method returns an integer indicating the data type of the value. ...
...in this function, wrk is expected to be an already opened nsiwindowsregkey. function readregistryvalue(wrk, value) { switch (wrk.getvaluetype(value)) { case wrk.type_string: return wrk.readstringvalue(value); case wrk.type_binary: return wrk.readbinaryvalue(value); case wrk.type_int: return wrk.readintvalue(value); case wrk...
...And 4 more matches
Building the WebLock UI
the user interface described in this section is comprised of four files: weblockoverlay.xul is the file that defines the little status icon in the browser. weblock.xul defines the web lock manager dialog. weblock.css provides style rules for both of the xul files. weblock.js provides javascript functions for both of the xul files. each of these files is described briefly in the sections below. in the following chapter we'll describe how you can take these files and create a package, an installable archive that includes the weblock component and the new ui. because this step (particularly the overlay section) is so dependent on mozilla, the chapter is divided up into a couple of different sections. the second section, xul, describes the xml-based user interface language (xul) and how ...
...k component). client code overview before we get started on the actual user interface, we should establish how the client code is to access the weblock component and use its interfaces to control the web locking of the browser. first of all, it's important to be able to represent the basic state of the lock as soon as it's loaded. like the secure page icon, the weblock icon that appears in the lower right corner of the browser should indicate whether the browser is currently locked or unlocked. since the weblock component is always initialized as unlocked, we can have the client code - the javascript code in the interface - represent this state and track it as the user manipulates the iweblock interface. a boolean wlocked variable can do this: // initialize the wlocked variable as unlocke...
... the weblock component. in this section, we are going to create the xul interface that calls the javascript methods when the user interacts with it. the xul document the first thing to do is create the actual xul document in which the user interface for the dialog and the events that initiate interaction with the web locking are defined. at the top of all xul documents, an xml declaration is followed by the root element for the document, which is usually <window/> but for dialog boxes can also be the element <dialog/>. the "shell" for the xul file, then, looks like this: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <dialog id="weblock_ui" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" title="web lock manager" ...
...And 4 more matches
Components.utils.exportFunction
the less privileged code's global window object: it can be exported to any object in the target scope. exportfunction() is made available as a global in sandboxes which have the wantexporthelpers option set in the sandbox() constructor. this includes add-on sdk content scripts. to understand what happens if the functions you export accept arguments, see exporting functions that take arguments below. syntax components.utils.exportfunction(func, targetscope[, options]); 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.
...x components.utils.exportfunction(func, targetscope[, options]); 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...
...boolean, defaulting to false. ...
...And 4 more matches
nsDependentCString
ubstring 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 appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
... except that the resulting string is flat. void nsdependentcstring() - source constructs an nsdependentstring to be rebound later. nsdependentcstring(const nsacstring_internal&) - source obsolete in gecko 9. this constructor should not be used. parameters nsacstring_internal& str assertvalid void assertvalid() - source verify restrictions rebind void rebind(const char*) - source allow this class to be bound to a different string... parameters char* data void rebind(const char*, pruint32) - source parameters char* data pruint32 length void rebind(const char*, const char*) - source parameters char* start char* end operator= nscstring& operator=(const nscstring&) - source parameters nscstring& str nsacstring_internal& operator=(char) - source parameter...
...ameters 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. ...
...And 4 more matches
nsDependentString
ubstring 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 appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...parameters prunichar* data void rebind(const prunichar*, pruint32) - source parameters prunichar* data pruint32 length void rebind(const prunichar*, const prunichar*) - source parameters prunichar* start prunichar* end operator= nsstring& operator=(const nsstring&) - source parameters nsstring& str nsastring_internal& opera...
...ameters 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. ...
...And 4 more matches
nsISelectionPrivate
); void endbatchchanges(); void getcachedframeoffset(in nsiframe aframe, in print32 inoffset, in nspointref apoint); native code only! nsienumerator getenumerator(); nsframeselection getframeselection(); native code only! void getrangesforinterval(in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, out pruint32 resultcount, [retval, array, size_is(resultcount)] out nsidomrange results); void getrangesforintervalarray(in nsinode beginnode, in print32 beginoffset, in nsinode endnode, in print32 endoffset, in boolean allowadjacent, in rangearray results); native code only! void getrangesforintervalcomarray(in nsidomnode beginnode, in print32 beginoffset, in nsidomno...
...rray, size_is(resultcount)] out nsidomrange results); void getrangesforintervalarray(in nsinode beginnode, in print32 beginoffset, in nsinode endnode, in print32 endoffset, in boolean allowadjacent, in rangearray results); native code only! void getrangesforintervalcomarray(in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, in rangearray results); native code only! obsolete since gecko 12.0 long gettableselectiontype(in nsidomrange range); void removeselectionlistener(in nsiselectionlistener listenertoremove); void scrollintoview(in short aregion, in boolean aissynchronous, in short avpercent, in short ahpercent); void setancestorlimiter(in nsicontent acontent); native c...
...de only! void startbatchchanges(); wstring tostringwithformat(in string formattype, in unsigned long flags, in print32 wrapcolumn); attributes attribute type description cancacheframeoffset boolean frame offset cache can be used just during calling nseditor::endplaceholdertransaction. endplaceholdertransaction will give rise to reflow/refreshing view/scroll, and call times of nstextframe::getpointfromoffset whose return value is to be cached. see bug 35296 and bug 199412 native code only! interlineposition boolean type short returns the type of the selection (see nsiselectioncontroller for available constants). read only. constants constant value description ...
...And 4 more matches
XPCOM
interfaces in xpcom are defined in a dialect of idl called xpidl. xpcom itself provides a set of core components and classes, e.g. file and memory management, threads, basic data structures (strings, arrays, variants), etc. the majority of xpcom components are not part of this core set and are provided by other parts of the platform (e.g. gecko or necko) or by an application or even by an extension. ...
...c functionality, it is often useful to access the windows registry for information about the environment or other installed programs. to this end, there exist xpcom interfaces to read and write registry data. this article will show you how to use the available interfaces in several mozilla products.aggregating the in-memory datasourcealready_addrefedalready_addrefed in association with nscomptr allows you to assign in a pointer without addrefing it.binary compatibilityif mozilla decides to upgrade to a compiler that does not have the same abi as the current version, any built component may fail. it is a possiblity that is introduced when upgrading to a new compiler without recompiling everything. effectively, it is a different platform.bundling multiple binary componentsbinary xpcom component...
...ddrefing it.binary compatibilityif mozilla decides to upgrade to a compiler that does not have the same abi as the current version, any built component may fail. it is a possiblity that is introduced when upgrading to a new compiler without recompiling everything. effectively, it is a different platform.bundling multiple binary componentsbinary xpcom components are sometimes required to implement low-level features for extensions. since binary components are linked against a single gecko sdk, a dependency to a particular version of gecko is created. if the component uses only "frozen" xpcom interfaces, there is a good chance the same binary component will work with different versions of gecko (version 1.8 and 1.9, for example). the more likely case is that the component uses "unfrozen" interf...
...And 4 more matches
MailNews fakeserver
of all components, as edge cases with quirky servers being liberal with the specs will require different handlers. writing a new fakeserver since the number of protocols we use is very small, most people shouldn't have to write an entirely new daemon and handler setup by themselves. that said, someone writing a new test may have to take into account a new handler. a handler will contain the following methods: <caption> handler methods </caption> name arguments returns notes [command] rest of sent line server's response the name is normalized to be uppercase. onerror command, rest of sent line server's response called if handler does not define the command function. onstartup none server's response called when a connection is made. onmultiline sent line server's response or noth...
...after every command. the server is smart about the responses and will normalize all occurrences of '\n' (but not '\r') to '\r\n' for you, as well as append the '\r\n' to the response if not present. it will also properly queue all messages sent in pipelining mode and will present lines without any eol characters. in addition, it uses utf-8 as the transmission medium. the server presents the following api to the handler: <caption> server api </caption> name arguments returns description closesocket none nothing closes the socket and stops the test. setmultiline the new value of multiline nothing the value is a boolean, with true invoking multiline mode. it is off by default. extending a handler to provide different mechanisms is a process not defined here; please check the documen...
... 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. ...
...And 4 more matches
Mail composition back end
ity 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 task is the nsims...
...gsend interface. the feedback mechanism is provided by a nsimsgsendlistener which is implemented by the caller. the caller has the ability to add or remove listener interfaces to the nsimsgsend object and the interface can support multiple listeners. (for detailed information on the listener interfaces, see the listener interfaces section of this document) nsimsgsend the following describes the methods of the nsimsgsend interface. all of these methods are asynchronous operations. createandsendmessage the createandsendmessage method will create an rfc822 message and send it all in one operation as well as providing the ability to save disk files for later use. the mode of delivery can also be specified for the "send later", "drafts" and "templates"...
...g the ability to save disk files for later use. the mode of delivery can also be specified for the "send later", "drafts" and "templates" operations. (note: this method could easily be broken in to a few different calls. currently, this method does several functions depending on the arguments passed in, but this could easily lead to confusion. this is something that very well may change as time allows). ns_imethod createandsendmessage( 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 pe...
...And 4 more matches
Standard OS Libraries
h c functions that can be called from your add-on with js-ctypes. the dll/so/etc file you make must be shipped with your add-on. standard libraries offer the advantage of not having to ship anything. they are already available on the operating system for you. you just need to supply the path to appropriate files and set up the proper types of values/arguments in the js-ctypes code. this article allows you to find out what types to give to values/arguments by supplying links to the documentation of the os libraries. windows windows has many standard os libraries. the most common, found on all windows os version, is "winapi". windows also has the "winapilists" and ".net framework" (i'm not sure if it can be accessed jsctypes but probably). a complete list of windows apis can be found at the m...
...11. xorg is being re-written at the moment, it is known as wayland. wayland is not considered stable, but it's supposed to replace xorg in the long term. gtk+ and qt have begun porting their code to wayland. as wayland is not out yet in the wild this article does not focus on wayland, it will focus on gtk+ and xorg(x11/x). gdk is a stack under gtk+. gtk+ is the toolkit to build apps, gdk is more low-level. to be precise, x is "just" like a display machine. on top of which everybody uses "window managers" (known as "wm"s) such as fluxbox, i3, awesome, openbox, mutter (used by gnome 3), plasma (used by kde) etc. gnome and kde are "desktop environments" (known as "de"s). wms on ubuntu work a little differently but we'll revisit this topic later in this article (did you know they have a *specia...
.... one library that linux uses, and that can be used through js-ctypes, is x11. gdk as mentioned, all firefox's are a gtk+ app, which means it has to have gdk, as gdk is underlying level of gtk+. therefore all the gdk library functions are available for use. gdk has version 2 and 3, typically version 2 is referred to as just gdk and version 3 is referred to as gdk3. examples for both are found below. documentation for gdk functions are found here: gnome developer :: gdk 2 reference manual. for gdk3 documentation is found here: gnome developer :: gdk 3 reference manual. because gnome is in the name of the websites don't get confused and think this only works on gnome. it is true though that gdk was developed by the gnome team. example: gdk_window_get_pointer this example is fot the gdk 2.0 ...
...And 4 more matches
DevTools API - Firefox Developer Tools
hen the toolbox is opened). there is no way to "close/destroy" a toolpanel. the only way to close a toolpanel is to close its containing toolbox. all these objects implement the eventemitter interface. api gdevtools the gdevtools api can be used to register new tools, themes and handle toolboxes for different tabs and windows. to use the gdevtools api from an add-on, it can be imported with following snippet const { gdevtools } = require("resource:///modules/devtools/gdevtools.jsm"); methods registertool(tooldefinition) registers a new tool and adds a tab to each existing toolbox. parameters: tooldefinition {tooldefinition} - an object that contains information about the tool. see tooldefinition for details. unregistertool(tool) unregisters the given tool and removes it f...
...ch the themedefinition object for the theme with the given id. parameters: themeid {string} - the id of the theme. return value: a themedefinition object if the theme exists, null otherwise. getthemedefinitionmap() returns a toolid → themedefinition map for available themes. getthemedefinitionarray() returns an array of themedefinition objects for avialble themes. events following events are emitted by the gdevtools object via the eventemitter interface. tool-registered(toolid) a new tool has been registered. tool-unregistered(tool) a tool has been unregistered. the parameter is a tooldefinition object. theme-registered(themeid) a new theme has been registered. theme-unregistered(theme) a theme has been unregistered. the parameter is a themedef...
.... toolbox a toolbox is a frame for the toolpanels that is debugging a specific target. properties target target. the target this toolbox is debugging. hosttype toolbox.hosttype. the type of the host this toolbox is docked to. the value is one of the toolbox.hosttype constants. zoomvalue the current zoom level of the toolbox. constants the toolbox constructor contains following constant properties. toolbox.hosttype.bottom host type for the default toolbox host at the bottom of the browser window. toolbox.hosttype.side host type for the host at the side of the browser window. toolbox.hosttype.window host type for the separate toolbox window. toolbox.hosttype.custom host type for a custom frame host. methods getcurrentpanel() get the...
...And 4 more matches
Examine and edit CSS - Firefox Developer Tools
you can examine and edit css in the inspector's css pane. examine css rules the rules view lists all the rules that apply to the selected element, ordered from most-specific to least-specific: the four buttons on the right top of the rules view allow you to change the display of certain css and rules view features. 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. this can help you understand why certain styles are not being app...
...n 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. this can help you understand why certain styles are not being applied. in the following example, a spelling error, "background-colour" instead of "background-color" has made the rule invalid: rule display it displays each rule as in a stylesheet, with a list of selectors followed by a list of property:value; declarations. highlight matched elements: next to the selector is a target icon: click this to highlight all nodes in the page that match this selector. overridden ...
...containing border-bottom-color and background-color as well as just color.: if you enclose the search query in backticks, like this: `color`, the search is restricted to exact matches: expanding shorthand properties shorthand properties can be expanded to display their related longhand properties by clicking the arrow besides them. ...
...And 4 more matches
AddressErrors - Web APIs
es that a validation error occurred for the member of the same name in an address described using paymentaddress. addresserrors is the type of the object returned by shippingaddresserrors in the paymentdetailsupdate passed into paymentrequestupdateevent.updatewith() by the shippingaddresschange event handler if a change to the address resulted in a validation error occurring. see the examples below to see how this works. properties addressline a domstring which, if present, indicates that the addressline 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. city a domstring which, if present, indicates that the city property of the paymentaddress...
...dress 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). examples snippet: limiting destination countries this first example is just a snippet showing an implementation of the event handler for the shippingaddresschange event which checks to be sure the chosen add...
...or a description of how this code works. complete example here we'll see a complete, working version of the example above (except of course that it's not connected to an actual payment handler, so no payments are actually processed). in the example, we're handling a donation to an organization that will be sending a "thank you" gift to the donor, so it requests shipping information along with allowing the donation payment itself. javascript payment request data first, we declare the variables supportedhandlers, which is compatible with paymentmethoddata, and defaultpaymentdetails, which is a paymentdetailsupdate object. let supportedhandlers = [ { supportedmethods: "basic-card", data: { supportednetworks: ["visa", "mastercard", "amex", "discover"], supportedtypes: ...
...And 4 more matches
BiquadFilterNode.type - Web APIs
the type property of the biquadfilternode interface is a string (enum) value defining the kind of filtering algorithm the node is implementing. syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = 'lowpass'; value a string (enum) representing a biquadfiltertype. type values and their meaning type description frequency q gain lowpass standard second-order resonant lowpass filter with 12db/octave rolloff. frequencies below the cutoff pass through; frequencies above it are attenuated. the cutoff frequency. indicates how peaked the frequency is around the cutoff. the greater the value is, the greater is the peak. not used highpass standard second-order resonant highpass filter...
... the cutoff frequency. indicates how peaked the frequency is around the cutoff. the greater the value, the greater the peak. not used bandpass standard second-order bandpass filter. frequencies outside the given range of frequencies are attenuated; the frequencies inside it pass through. ...
...he cutoff. the greater the value, the greater the peak. not used bandpass standard second-order bandpass filter. frequencies outside the given range of frequencies are attenuated; the frequencies inside it pass through. the center of the range of frequencies. controls the width of the frequency band. the greater the q value, the larger the frequency band. not used lowshelf standard second-order lowshelf filer. frequencies lower than the frequency get a boost, or an attenuation; frequencies over it are unchanged. the upper limit of the frequencies getting a boost or an attenuation. not used the boost, in db, to be applied; if negative, it will be an attenuation. highshelf standard second-order highshelf filer. frequencies higher than the...
...And 4 more matches
BiquadFilterNode - Web APIs
it is an audionode that can represent different kinds of filters, tone control devices, and graphic equalizers. a biquadfilternode always has exactly one input and one output. number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor biquadfilternode() creates a new instance of a biquadfilternode object. properties inherits properties from its parent, audionode. ...
... quality factor. biquadfilternode.gain read only is an a-rate audioparam, a double representing the gain used in the current filtering algorithm. biquadfilternode.type is a string value defining the kind of filtering algorithm the node is implementing. the meaning of the different parameters depending of the type of the filter (detune has the same meaning regardless, so isn't listed below) type description frequency q gain lowpass standard second-order resonant lowpass filter with 12db/octave rolloff. frequencies below the cutoff pass through; frequencies above it are attenuated. the cutoff frequency. indicates how peaked the frequency is around the cutoff. the greater the value is, the greater is the peak. not used ...
... the cutoff frequency. indicates how peaked the frequency is around the cutoff. the greater the value, the greater the peak. not used bandpass standard second-order bandpass filter. frequencies outside the given range of frequencies are attenuated; the frequencies inside it pass through. ...
...And 4 more matches
DirectoryEntrySync - Web APIs
the directoryentrysync interface of the file system api represents a directory in a file system. it includes methods for creating, reading, looking up, and recursively removing files in a directory. this interface has been abandonned: it was on a standard track and it proves not a good idea. do not use it anymore. about this document this document was last updated on march 2, 2012 and follows the w3c specifications (working draft) drafted on april 19, 2011. this specification is pretty much abandoned, having failed to reach any substantial traction. basic concepts if you want to create subdirectories, you have to create each child directory in sequence. if you try to create a directory using a full path that includes parent directories that do not exist yet, you get an error. so cr...
...ate subdirectories, you have to create each child directory in sequence. if you try to create a directory using a full path that includes parent directories that do not exist yet, you get an error. so create the hierarchy by recursively adding a new path after creating the parent directory. example the getfile() method returns a fileentrysync, which represents a file in the file system. the following creates an empty file called seekrits.txt in the root directory. var fileentry = fs.root.getfile('seekrits.txt', {create: true}); the getdirectory() method returns a directoryentrysync, which represents a file in the file system. the following creates a new directory called superseekrit in the root directory. var direntry = fs.root.getdirectory('superseekrit', {create: true}); method over...
...es (fileexception); void removerecursively () raises (fileexception); methods createreader() creates a new directoryreadersync to read 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 option...
...And 4 more matches
HTMLImageElement - Web APIs
the htmlimageelement interface represents an html <img> element, providing the properties and methods used to manipulate image elements. ...
....src a usvstring that reflects the src html attribute, which contains the full url of the image including base uri. you can load a different image into the element by changing the url in the src attribute. htmlimageelement.srcset a usvstring reflecting the srcset html attribute. this specifies a list of candidate images, separated by commas (',', u+002c comma). each candidate image is a url followed by a space, followed by a specially-formatted string indicating the size of the image. the size may be specified either the width or a size multiple. read the srcset page for specifics on the format of the size substring. htmlimageelement.usemap a domstring reflecting the usemap html attribute, containing the page-local url of the <map> element describing the image map to use. the page-local ...
...ly-formatted string indicating the size of the image. the size may be specified either the width or a size multiple. read the srcset page for specifics on the format of the size substring. htmlimageelement.usemap a domstring reflecting the usemap html attribute, containing the page-local url of the <map> element describing the image map to use. the page-local url is a pound (hash) symbol (#) followed by the id of the <map> element, such as #my-map-element. the <map> in turn contains <area> elements indicating the clickable areas in the image. htmlimageelement.width an integer value that reflects the width html attribute, indicating the rendered width of the image in css pixels. htmlimageelement.x read only an integer indicating the horizontal offset of the left border edge of the image...
...And 4 more matches
install - Web APIs
firefox 3 note in firefox 3 the callback is no longer invoked unless the website performing the installation is whitelisted. ...
... firefox 3 note in firefox 3 the callback is no longer invoked unless the website performing the installation is whitelisted. ...
... firefox 3 note in firefox 3 the callback is no longer invoked unless the website performing the installation is whitelisted. ...
...And 4 more matches
RTCConfiguration - Web APIs
the options include ice server and transport settings and identity information. ...
...of type rtccertificate which are used by the connection for authentication. if this property isn't specified, a set of certificates is generated automatically for each rtcpeerconnection instance. although only one certificate is used by a given connection, providing certificates for multiple algorithms may improve the odds of successfully connecting in some circumstances. see using certificates below for additional information. this configuration option cannot be changed after it is first specified; once the certificates have been set, this property is ignored in future calls to rtcpeerconnection.setconfiguration(). icecandidatepoolsize optional an unsigned 16-bit integer value which specifies the size of the prefetched ice candidate pool. the default value is 0 (meaning no candidate pre...
...once the certificates have been set, this property is ignored in future calls to rtcpeerconnection.setconfiguration(). icecandidatepoolsize optional an unsigned 16-bit integer value which specifies the size of the prefetched ice candidate pool. the default value is 0 (meaning no candidate prefetching will occur). you may find in some cases that connections can be established more quickly by allowing the ice agent to start fetching ice candidates before you start trying to connect, so that they're already available for inspection when rtcpeerconnection.setlocaldescription() is called. changing the size of the ice candidate pool may trigger the beginning of ice gathering. iceservers optional an array of rtciceserver objects, each describing one server which may be used by the ice agent...
...And 4 more matches
SVGLengthList - Web APIs
numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svglength newitem) svglength clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is i...
...current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svglength returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domex...
...sponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svglength returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in svglength newitem, in unsigned long index) svglength inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list before it is inserted into this li...
...And 4 more matches
SVGNumberList - Web APIs
numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgnumber newitem) svgnumber clears all existing current items from the list and re-initializes the list to hold the single item specified by newitem. if the inserted item is already in a list, it is removed from its previous list before it is inser...
...ng current items from the list and re-initializes the list to hold the single item specified by newitem. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgnumber returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a ...
...s to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgnumber returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in svgnumber newitem, in unsigned long index) svgnumber inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list before it is inserted into ...
...And 4 more matches
SVGPathSegList - Web APIs
sread only unsigned long the number of items in the list. methods clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list cannot be modified. initialize(in svgpathseg newitem) svgpathseg clears all existing current items from the list and re-initializes the list to hold the single item specified by newitem. if the inserted item is already in a list, it is removed from its previous li...
...om the list and re-initializes the list to hold the single item specified by newitem. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list cannot be modified. getitem(in unsigned long index) svgpathseg returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. ...
... getitem(in unsigned long index) svgpathseg returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list cannot be modified. insertitembefore(in svgpathseg newitem, in unsigned long index) svgpathseg inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list...
...And 4 more matches
SVGPointList - Web APIs
ems in the list. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgpoint newitem) svgpoint clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is...
... the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgpoint returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first ite...
... only. getitem(in unsigned long index) svgpoint returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in svgpoint newitem, in unsigned long index) svgpoint inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its pr...
...And 4 more matches
SVGStringList - Web APIs
of items in the list. length unsigned long a mirror of the value in numberofitems, for consistency with other interfaces. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in domstring newitem) domstring clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is...
...rent items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) domstring returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a ...
...s to a read only attribute or when the object itself is read only. getitem(in unsigned long index) domstring returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in domstring newitem, in unsigned long index) domstring inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list before it is inserted into this ...
...And 4 more matches
Sensor APIs - Web APIs
f the device along all three axes at the time it is read. sensors may or may not correspond exactly to a physical device sensor. for example, the gyroscope interface corresponds exactly to a physical device interface. alternatively, the absoluteorientationsensor interface provides information that is algorithmically agregated from two or more device sensors. these sensor types are referred to as low-level and high-level respectively. the latter type of sensor is also called a fusion sensor (alternatively, virtual or synthetic sensors). feature detection sensor interfaces are only proxies for the underlying device sensors. consequently, feature detection is more complicated for sensors than it is for other apis. the presence of a sensor api does not tell you whether that api is connected to...
... 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.ambientlightsensor) { // go...
...ature 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 gracefully so that the user experience is enhanced rather than degraded. the code example below illustrates these principles. the try...catch block catches errors thrown during sensor instantiation. it implements a handler for sensor.onerror to catch errors thrown during use. the only time anything is shown to the user is when permissions need to be requested and when the sensor type isn't supported by the device. if a feature policy blocks use of a feature it is because your code is inco...
...And 4 more matches
Example and tutorial: Simple synth keyboard - Web APIs
because oscillatornode is based on audioscheduledsourcenode, this is to some extent an example for that as well. the video keyboard html there are three primary components to the display for our virtual keyboard. the first is the musical keyboard itself. ...
... because oscillatornode is based on audioscheduledsourcenode, this is to some extent an example for that as well. the video keyboard html there are three primary components to the display for our virtual keyboard. the first is the musical keyboard itself. ...
... another to select what periodic waveform to use when generating notes. the volume control first we create the <div> to contain the settings bar, so it can be styled 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. <div class="settingsbar"> <div class="left"> <span>volume: </span> <input type="range" min="0.0" max="1.0" step="0.01" value="0.5" list="volumes" name="volume"> <datalist id="volumes"> <option value="0.0" label="mute"> <option value="1.0" label="100%"> </datalist> </div> we specify a default ...
...And 4 more matches
Functions and classes available to Web Workers - Web APIs
workerglobalscope yes, on workerglobalscope yes, but is a no-op. ...
... 41 (41) (yes) (yes) (yes) console api provides access to the browser's debugging console (e.g., the web console in firefox). ...
...es) console api provides access to the browser's debugging console (e.g., the web console in firefox). the specifics of how it works vary from browser to browser, but there is a de facto set of features that are typically provided. 38 (38) (yes) (yes) (yes) crypto the crypto interface represents basic cryptography features available in the current context. it allows access to a cryptographically strong random number generator and to cryptographic primitives. ? no support ? ? customevent the customevent interface represents events initialized by an application for any purpose. 48 (48) (yes) (yes) (yes) domrequest and domcursor respectively, these objects represents an ongoing operation (with listeners for react...
...And 4 more matches
Window.prompt() - Web APIs
Web › API › Window › prompt
there is nothing to show in the prompt window. default optional a string containing the default value displayed in the text input field. note that in internet explorer 7 and 8, if you do not provide this parameter, the string "undefined" is the default value. return value a string containing the text entered by the user, or null. ...
...g lucky" sign = window.prompt('are you feeling lucky', 'sure'); // open the window with text "are you feeling lucky" and default value "sure" when the user clicks the ok button, text entered in the input field is returned. if the user clicks ok without entering any text, an empty string is returned. if the user clicks the cancel button, this function returns null. ...
...put field is returned. if the user clicks ok without entering any text, an empty string is returned. if the user clicks the cancel button, this function returns null. the above prompt appears as follows (in chrome on os x): notes a prompt dialog contains a single-line textbox, a cancel button, and an ok button, and returns the (possibly empty) text the user entered into that textbox. the following text is shared between this article, dom:window.confirm and dom:window.alert dialog boxes are modal windows; they prevent the user from accessing the rest of the program's interface until the dialog box is closed. for this reason, you should not overuse any function that creates a dialog box (or modal window). please note that result is a string. that means you should sometimes cast the value...
...And 4 more matches
Perceivable - Accessibility
y color is related, but covered in a different guideline — 1.4.1. 1.3.4 orientation (aa) added in 2.1 content does not restrict its view and operation to a single display orientation, such as portrait or landscape, unless a specific display orientation is essential. understanding orientation 1.3.5 identify input purpose (aa) added in 2.1 follow the list of 53 input fields to programmatically identify the purpose of a field. understanding identify input purpose 1.3.6 identify purpose (aaa) added in 2.1 in content implemented using markup languages, the purpose of user interface components, icons, and regions can be programmatically determined. understanding identify purpose note: also see the wcag descrip...
...ubled. this means that designs should be responsive, so that when the text size is increased, the content is still accessible. 1.4.5 images of text (aa) images should not be used to present content where text would do the job. for example, if an image is mostly textual, it could be represented using text as well as images. ...
...ented using text as well as images. 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. larger text is defined as at least 18pt, or 14pt bold. see color and color contrast. 1.4.7 low or no background audio (aaa) prerecorded audio recordings that primarily feature speech should have minimal background noise, so the content can be easily understood. 1.4.8 visual presentation (aaa) for text content presentation, the following should be true: foreground and background colors should be user-selectable. text blocks should be no wider than 80 ...
...And 4 more matches
font-stretch - CSS: Cascading Style Sheets
for a particular font family, authors can download various font faces which correspond to the different styles of the same font family, and then use the font-stretch descriptor to explicitly specify the font face's stretch. the values for the css descriptor is same as that of its corresponding font property. ...
...ondensed; font-stretch: semi-condensed; font-stretch: normal; font-stretch: semi-expanded; font-stretch: expanded; font-stretch: extra-expanded; font-stretch: ultra-expanded; font-stretch: 50%; font-stretch: 100%; font-stretch: 200%; /* multiple values */ font-stretch: 75% 125%; font-stretch: condensed ultra-condensed;; the font-weight property is described using any one of the values listed below. values normal specifies a normal font face. semi-condensed, condensed, extra-condensed, ultra-condensed specifies a more condensed font face than normal, with ultra-condensed as the most condensed. semi-expanded, expanded, extra-expanded, ultra-expanded specifies a more expanded font face than normal, with ultra-expanded as the most expanded. <percentage> a <percentage> value between ...
...semi-condensed, condensed, extra-condensed, ultra-condensed specifies a more condensed font face than normal, with ultra-condensed as the most condensed. semi-expanded, expanded, extra-expanded, ultra-expanded specifies a more expanded font face than normal, with ultra-expanded as the most expanded. <percentage> a <percentage> value between 50% and 200% (inclusive). negative values are not allowed for this property. in earlier versions of the font-stretch specification, the property accepts only the nine keyword values. css fonts level 4 extends the syntax to accept a <percentage> value as well. this enables variable fonts to offer something more like a continuum of character widths. for truetype or opentype variable fonts, the "wdth" variation is used to implement varying widths. if ...
...And 4 more matches
Border-image generator - CSS: Cascading Style Sheets
roup:before, .group:after { content: ""; display: table; } .group:after { clear:both; } .group { zoom: 1; /* for ie 6/7 (trigger haslayout) */ } /* grid column setup * ========================================================================== */ .col { display: block; float:left; margin: 1% 0 1% 1.6%; } .col:first-child { margin-left: 0; } /* all browsers except ie6 and lower */ /* * ui component */ .ui-input-slider { height: 20px; font-family: "segoe ui", arial, helvetica, sans-serif; -moz-user-select: none; user-select: none; } .ui-input-slider * { float: left; height: 100%; line-height: 100%; } /* input slider */ .ui-input-slider > input { margin: 0; padding: 0; width: 50px; text-align: center; -moz-box-sizing: border-box; -webkit-box-sizin...
...; user-select: none; } .ui-input-slider * { float: left; height: 100%; line-height: 100%; } /* input slider */ .ui-input-slider > input { margin: 0; padding: 0; width: 50px; text-align: center; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .ui-input-slider-info { width: 90px; padding: 0px 10px 0px 0px; text-align: right; text-transform: lowercase; } .ui-input-slider-left, .ui-input-slider-right { width: 16px; cursor: pointer; background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center left no-repeat; } .ui-input-slider-right { background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center right no-repeat; } .ui-input-slider-name { width: 90px; padding: 0 10px 0 0; text-align: right; text-tra...
...} .ui-input-slider-left, .ui-input-slider-right { width: 16px; cursor: pointer; background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center left no-repeat; } .ui-input-slider-right { background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center right no-repeat; } .ui-input-slider-name { width: 90px; padding: 0 10px 0 0; text-align: right; text-transform: lowercase; } .ui-input-slider-btn-set { width: 25px; background-color: #2c9fc9; border-radius: 5px; color: #fff; font-weight: bold; line-height: 14px; text-align: center; } .ui-input-slider-btn-set:hover { background-color: #379b4a; cursor: pointer; } /*************************************************************************************/ /**************************************************...
...And 4 more matches
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
ke a thorough look at how the alignment and justification properties work in flexbox. to center our box we use the align-items property to align our item on the cross axis, which in this case is the block axis running vertically. we use justify-content to align the item on the main axis, which in this case the inline axis running horizontally. you can take a look at the code of this example below. change the size of the container or nested element and the nested element always remains centered. properties that control alignment the properties we will look at in this guide are as follows. justify-content — controls alignment of all items on the main axis. align-items — controls alignment of all items on the cross axis. align-self — controls alignment of an individual flex it...
... of how much content is in the item. the reason the items become the same height is that the initial value of align-items, the property that controls alignment on the cross axis, is set to stretch. we can use other values to control how the items align: align-items: flex-start align-items: flex-end align-items: center align-items: stretch align-items: baseline in the live example below, the value of align-items is stretch. try the other values and see how all of the items align against each other in the flex container. aligning one item with align-self the align-items property sets the align-self property on all of the flex items as a group. this means you can explicitly declare the align-self property to target a single item. the align-self property accepts all of the sam...
...r we have looked at the behaviour when our flex-direction is row, and while working in a language written top to bottom. this means that the main axis runs along the row horizontally, and our cross axis alignment moves the items up and down. if we change our flex-direction to column, align-items and align-self will align the items to the left and right. you can try this out in the example below, which has a flex container with flex-direction: column yet otherwise is exactly the same as the previous example. aligning content on the cross axis — the align-content property so far we have been aligning the items, or an individual item inside the area defined by the flex-container. if you have a wrapped multiple-line flex container then you might also want to use the align-content pro...
...And 4 more matches
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
a set of items and want to space them out evenly in a container. you let the size of the content decide how much individual space each item takes up. if the items wrap onto a new line, they will work out their spacing based on their size and the available space on that line. grid works from the layout in. when you use css grid layout you create a layout and then you place items into it, or you allow the auto-placement rules to place the items into the grid cells according to that strict grid. it is possible to create tracks that respond to the size of the content, however, they will also change the entire track. if you are using flexbox and find yourself disabling some of the flexibility, you probably need to use css grid layout. an example would be if you are setting a percentage width on ...
... containing block you need to add the position property to the container with a value of relative, just as you would make a containing block for any other absolutely positioned items. once you have done this, if you give a grid item position: absolute it will take as its containing block the grid container or, if the item also has a grid position, the area of the grid it is placed into. in the below example i have a wrapper containing four child items. item three is absolutely positioned and also placed on the grid using line-based placement. the grid container has position: relative and so becomes the positioning context of this item. * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px so...
...00px; grid-gap: 20px; position: relative; } .box3 { grid-column-start: 2; grid-column-end: 4; grid-row-start: 1; grid-row-end: 3; position: absolute; top: 40px; left: 40px; } you can see that the item is taking the area from grid column line 2 to 4, and starting after line 1. then it is offset in that area using the top and left properties. however, it has been taken out of flow as is usual for absolutely positioned items and so the auto-placement rules now place items into the same space. the item also doesn’t cause the additional row to be created to span to row line 3. if we remove position: absolute from the rules for .box3 you can see how it would display without the positioning. a grid container as parent if the absolutely positioned child has a grid container...
...And 4 more matches
Subgrid - CSS: Cascading Style Sheets
some use cases and design patterns that are solved by the feature. important: this feature is shipped in firefox 71, which is currently the only browser to implement subgrid. introduction to subgrid when you add display: grid to a grid container, only the direct children become grid items and can then be placed on the grid that you have created. the children of these items display in normal flow. you can "nest" grids by making a grid item a grid container. these grids however are independent of the parent grid and of each other, meaning that they do not take their track sizing from the parent grid. this makes it difficult to line nested grid items up with the main grid. if you set the value subgrid on grid-template-columns, grid-template-rows or both, instead of creating a new track li...
...grid-template-columns: subgrid and the nested grid spans three column tracks of 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...
... be the same. subgrid for rows the next example is the same setup, however we are using subgrid as the value of grid-template-rows and defining explicit column tracks. so the column tracks behave as a regular nested grid, but the rows are tied to the two tracks that the child spans. a subgrid in both dimensions you can of course define both rows and columns as a subgrid, as in the example below. this means that your subgrid is tied in both dimensions to the number of tracks on the parent. no implicit grid in a subgridded dimension if you need to autoplace items, and do not know how many items you will have, take care when creating a subgrid, as it will prevent additional rows being created to hold those items. take a look at the next example — it uses the same parent and child gr...
...And 4 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. ...
...it has the same effect as the code in fluid typography but in one line, and without the use of media queries. ...
...(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 the size of the viewport, but doesn't go below a minimum font-size or above a maximum font-size. ...
...And 4 more matches
linear-gradient() - CSS: Cascading Style Sheets
ied, it defaults to to bottom. the values to top, to bottom, to left, and to right are equivalent to the angles 0deg, 180deg, 270deg, and 90deg, respectively. the other values are translated into an angle. <angle> the gradient line's angle of direction. a value of 0deg is equivalent to to top; increasing values rotate clockwise from there. <linear-color-stop> a color-stop's <color> value, followed by one or two optional stop positions, (each being either a <percentage> or a <length> along the gradient's axis). <color-hint> the 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 ...
...s). <color-hint> the 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 color stops. note: rendering of color stops in css gradients follows the same rules as color stops in svg gradients. note also that the first example above does not exactly render as depicted in mozilla firefox (particularly version 80.0b3). you'll have to set the html height property to 100% or 100vh to render as depicted. description as with any gradient, a linear gradient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a pr...
...ir respective starting or ending points. customizing gradients by adding more color-stop points on the gradient line, you can create a highly customized transition between multiple colors. a color-stop's position can be explicitly defined by using a <length> or a <percentage>. if you don't specify the location of a color, it is placed halfway between the one that precedes it and the one that follows it. the following two gradients are equivalent. linear-gradient(red, orange, yellow, green, blue); linear-gradient(red 0%, orange 25%, yellow 50%, green 75%, blue 100%); by default, colors transition smoothly from the color at one color stop to the color at the subsequent color stop, with the midpoint between the colors being the half way point between the color transition. you can move this m...
...And 4 more matches
Getting Started - Developer guides
shell, it is the use of the xmlhttprequest object to communicate with servers. it can send and receive information in various formats, including json, xml, html, and text files. ajax’s most appealing characteristic is its "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page. the two major features of ajax allow you to do the following: make requests to the server without reloading the page receive and work with data from the server step 1 – how to make an http request in order to make an http request to the server with javascript, you need an instance of an object with the necessary functionality. this is where xmlhttprequest comes in. its predecessor originated in internet explorer as an activ...
...ing the page receive and work with data from the server step 1 – how to make an http request in order to make an http request to the server with javascript, you need an instance of an object with the necessary functionality. this is where xmlhttprequest comes in. its predecessor originated in internet explorer as an activex object called xmlhttp. then, mozilla, safari, and other browsers followed, implementing an xmlhttprequest object that supported the methods and properties of microsoft's original activex object. meanwhile, microsoft implemented xmlhttprequest as well. // old compatibility code, no longer needed. if (window.xmlhttprequest) { // mozilla, safari, ie7+ ... httprequest = new xmlhttprequest(); } else if (window.activexobject) { // ie 6 and older httprequest = new ...
...od can be any data you want to send to the server if post-ing the request. form data should be sent in a format that the server can parse, like a query string: "name=value&anothername="+encodeuricomponent(myvar)+"&so=on" or other formats, like multipart/form-data, json, xml, and so on. note that if you want to post data, you may have to set the mime type of the request. ...
...And 4 more matches
Video player styling basics - Developer guides
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. ...
... 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 inside unordered list items. ...
...creen</button> </div> related css alteration the previous article simply set the display property of the video controls to block in order to display them. this has now been changed to use a data-state attribute, which this code already uses to handle its fullscreen implementation. this "data-state" idea is also used for setting the current state of buttons within the video control set, which allows specific state styling. javascript as mentioned above, a data-state attribute is used in various places for styling purposes and these are set using javascript. specific implementations will be mentioned at appropriate places below. styling the resultant video player style used here is rather basic — this is intentional, as the purpose is to show how such a video player could be styled and...
...And 4 more matches
Media buffering, seeking, and time ranges - Developer guides
ider a simple audio example: <audio id="my-audio" controls src="music.mp3"> </audio> we can access these attributes like so: var myaudio = document.getelementbyid('my-audio'); var bufferedtimeranges = myaudio.buffered; timeranges object timeranges are a series of non-overlapping ranges of time, with start and stop times. (learn more about timeranges). a timeranges object consists of the following properties: length: the number of time ranges in the object. start(index): the start time, in seconds, of a time range. end(index): the end time, in seconds, of a time range. without any user interaction there is usually only one time range, but if you jump about in the media more than one time range can appear, as illustrated by the below visualization. this represents two buffered tim...
...s two buffered time ranges — one spanning 0 to 5 seconds and the second spanning 15 to 19 seconds. ...
...ange. note: you can see the timerange code running live on js bin. seekable the seekable attribute returns a timeranges object and tells us which parts of the media can be played without delay; this is irrespective of whether that part has been downloaded or not. some parts of the media may be seekable but not buffered if byte-range requests are enabled on the server. byte range requests allow parts of the media file to be delivered from the server and so can be ready to play almost immediately — thus they are seekable. var seekabletimeranges = myaudio.seekable; creating our own buffering feedback if we wish to create our own custom player, we may want to provide feedback on how much of the media is ready to be played. in practice a good way to do this is use the seekable attribut...
...And 4 more matches
<a>: The Anchor element - HTML: Hypertext Markup Language
Web › HTML › Element › a
ey can use any url scheme supported by browsers: sections of a page with fragment urls pieces of media files with media fragments telephone numbers with tel: urls email addresses with mailto: urls while web browsers may not support other url schemes, web sites can with registerprotocolhandler() hreflang hints at the human language of the linked url. no built-in functionality. allowed values are the same as the global lang attribute. ping a space-separated list of urls. when the link is followed, the browser will send post requests with the body ping to the urls. typically for tracking. referrerpolicy how much of the referrer to send when following the link. see referrer-policy for possible values and their effects. rel the relationship of the linked url as space-sepa...
...(default) _blank: usually a new tab, but users can configure browsers to open a new window instead. _parent: the parent browsing context of the current one. ...
...>, as long as they had identical values. note: use the global attribute id instead. revobsolete since html5 specified a reverse link; the opposite of the rel attribute. deprecated for being very confusing. shapeobsolete since html5 the shape of the hyperlink’s region in an image map. note: use the <area> element for image maps instead. ...
...And 4 more matches
<meter>: The HTML Meter element - HTML: Hypertext Markup Language
Web › HTML › Element › meter
the html <meter> element represents either a scalar value within a known range or a fractional value. 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, labelable content, palpable content. permitted content phrasing content, but there must be no <meter> element among its descendants. tag omission 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 ...
... 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. note: unless the value attribute is between 0 and 1 (inclusive), the min and max attributes should define the range so that the value attribute's value is within it. min the lower numeric bound of the measured range. this must be less than the maximum value (max attribute), if specified. if unspecified, the minimum value is 0. max the upper numeric bound of the measured range. this must be greater than the minimum value (min attribute), if specified. if unspecified, the maximum value is 1. low the upper numeric bound of the low end of the measured range. this must be...
...mum value (min attribute), if specified. if unspecified, the maximum value is 1. low the upper numeric bound of the low end of the measured range. this must be greater than the minimum value (min attribute), and it also must be less than the high value and maximum value (high attribute and max attribute, respectively), if any are specified. if unspecified, or if less than the minimum value, the low value is equal to the minimum value. high the lower numeric bound of the high end of the measured range. this must be less than the maximum value (max attribute), and it also must be greater than the low value and minimum value (low attribute and min attribute, respectively), if any are specified. if unspecified, or if greater than the maximum value, the high value is equal to the maximum value...
...And 4 more matches
<table>: The Table element - HTML: Hypertext Markup Language
Web › HTML › Element › table
resents tabular data — that is, information presented in a two-dimensional table comprised of rows and columns of cells containing data. 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. ...
...ository. 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. ...
...ption> element, zero or more <colgroup> elements, an optional <thead> element, either one of the following: zero or more <tbody> elements one or more <tr> elements an optional <tfoot> element tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content implicit aria role table permitted aria roles any dom interface htmltableelement attributes this element includes the global attributes. ...
...And 4 more matches
<tr>: The Table Row element - HTML: Hypertext Markup Language
Web › HTML › Element › tr
rol over how cells fit into (or span across) columns, both <th> and <td> support the colspan attribute, which lets you specify how many columns wide the cell should be, with the default being 1. similarly, you can use the rowspan attribute on cells to indicate they should span more than one table row. this can take a little practice to get right when building your tables. we have some examples below, but for more examples and an in-depth tutorial, see the html tables series in our learn web development area, where you'll learn how to use the table elements and their attributes to get just the right layout and formatting for your tabular data. attributes this element includes the global attributes. there are also several deprecated attributes, which you should avoid but may need to know whe...
... the html tables series in our learn web development area, where you'll learn how to use the table elements and their attributes to get just the right layout and formatting for your tabular data. attributes this element includes the global attributes. there are also several deprecated attributes, which you should avoid but may need to know when reading older code. deprecated attributes the following attributes may still be implemented in browsers but are no longer part of the html specification and may be missing or may not work as expected. they should be avoided. alignobsolete since html5 a domstring which specifies how the cell's context should be aligned horizontally within the cells in the row; this is shorthand for using align on every cell in the row individually. possible valu...
...ext fills the full width of each cell (full justification). char align each cell in the row on a specific character (such that each row in the column that is configured this way will horizontally align its cells on that character). this uses the char and charoff to establish the alignment character (typically "." or "," when aligning numerical data) and the number of characters that should follow the alignment character. this alignment type was never widely supported. if no value is expressly set for align, the parent node's value is inherited. instead of using the obsolete align attribute, you should instead use the css text-align property to establish left, center, right, or justify alignment for the row's cells. to apply character-based alignment, set the css text-align propert...
...And 4 more matches
Content negotiation - HTTP
device should opt-in to sharing the amount of device memory with the server. the value is given in miliseconds and it's use is optional. the accept-encoding header the accept-encoding header defines the acceptable content-encoding (supported compressions). the value is a q-factor list (e.g.: br, gzip;q=0.8) that indicates the priority of the encoding values. the default value identity is at the lowest priority (unless otherwise declared). compressing http messages is one of the most important ways to improve the performance of a web site, it shrinks the size of the data transmitted and makes better use of the available bandwidth; browsers always send this header and the server should be configured to abide to it and to use compression. the accept-language header the accept-language heade...
...s always send this header and the server should be configured to abide to it and to use compression. the accept-language header the accept-language header is used to indicate the language preference of the user. it is a list of values with quality factors (like: "de, en;q=0.7"). a default value is often set according the language of the graphical interface of the user agent, but most browsers allow to set different language preferences. due to the configuration-based entropy increase, a modified value can be used to fingerprint the user, it is not recommended to change it and a web site cannot trust this value to reflect the actual wish of the user. site designers must not be over-zealous by using language detection via this header as it can lead to a poor user experience: they should a...
...guage using this header. the user-agent header though there are legitimate uses of this header for selecting content, it is considered bad practice to rely on it to define what features are supported by the user agent. the user-agent header identifies the browser sending the request. this string may contain a space-separated list of product tokens and comments. a product token is a name followed by a '/' and a version number, like firefox/4.0.1. there may be as many of them as the user-agent wants. a comment is a free string delimited by parentheses. obviously parentheses cannot be used in that string. the inner format of a comment is not defined by the standard, though several browser put several tokens in it, separated by ';'. the vary response header in opposition to the previous ...
...And 4 more matches
CSP: object-src - HTTP
the http content-security-policy object-src directive specifies valid sources for the <object>, <embed>, and <applet> elements. to set allowed types for <object>, <embed>, and <applet> elements, use the plugin-types directive. elements controlled by object-src are perhaps coincidentally considered legacy html elements and aren't receiving new standardized features (such as the security attributes sandbox or allow for <iframe>). therefore it is recommended to restrict this fetch-directive (e.g. explicitly set object-src 'none' if possible). csp version 1 directive type fetch directive default-src fallback yes. ...
...urity attributes sandbox or allow for <iframe>). therefore it is recommended to restrict this fetch-directive (e.g. explicitly set object-src 'none' if possible). csp version 1 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the object-src policy: content-security-policy: object-src <source>; content-security-policy: object-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a ...
... mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a schema such as 'http:' or 'https:'. the colon is required, single quotes shouldn't be used. you can also specify data schemas (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin fr...
...And 4 more matches
Feature-Policy: fullscreen - HTTP
the http feature-policy header fullscreen directive controls whether the current document is allowed to use element.requestfullscreen(). when this policy is enabled, the returned promise rejects with a typeerror. by default, top-level documents and their same-origin child frames can request and enter fullscreen mode. this directive allows or prevents cross-origin frames from using fullscreen mode. this includes same-origin frames. if both this directive (i.e. via the allow attribute) and the allowfullscreen attribute are present on an <iframe> element, this directive takes precedence. there was a bug whereby the fullscreen directive didn't work unless the allowfullscreen attribute was also present, but this has been fixed as of firefox 80 (bug 1608358). syntax feature-policy:...
...includes same-origin frames. if both this directive (i.e. via the allow attribute) and the allowfullscreen attribute are present on an <iframe> element, this directive takes precedence. there was a bug whereby the fullscreen directive didn't work unless the allowfullscreen attribute was also present, but this has been fixed as of firefox 80 (bug 1608358). syntax feature-policy: fullscreen <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. ...
...te was also present, but this has been fixed as of firefox 80 (bug 1608358). syntax feature-policy: fullscreen <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. ...
...And 4 more matches
Feature-Policy: screen-wake-lock - HTTP
note: this api is still actively being developed and available only behind a flag on select browsers and platforms. the http feature-policy header screen-wake-lock directive controls whether the current document is allowed to use screen wake lock api to indicate that device should not dim or turn off the screen. note: in earlier specification drafts this directive was called wake-lock. ...
...developed and available only behind a flag on select browsers and platforms. the http feature-policy header screen-wake-lock directive controls whether the current document is allowed to use screen wake lock api to indicate that device should not dim or turn off the screen. note: in earlier specification drafts this directive was called wake-lock. ...
...ailable only behind a flag on select browsers and platforms. the http feature-policy header screen-wake-lock directive controls whether the current document is allowed to use screen wake lock api to indicate that device should not dim or turn off the screen. note: in earlier specification drafts this directive was called wake-lock. syntax feature-policy: screen-wake-lock <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. ...
...And 4 more matches
Proxy Auto-Configuration (PAC) file - HTTP
xy.autoconfig_url.include_path. host the hostname extracted from the url. this is only for convenience; it is the same string as between :// and the first : or / after that. the port number is not included in this parameter. it can be extracted from the url when necessary. description returns a string describing the configuration. the format of this string is defined in return value format below. ...
...at. the port number is not included in this parameter. it can be extracted from the url when necessary. description returns a string describing the configuration. the format of this string is defined in return value format below. ...
... the pac file is named proxy.pac command line: pactester -p ~/pacparser-master/tests/proxy.pac -u http://www.mozilla.org (passes the host parameter www.mozilla.org and the url parameter http://www.mozilla.org) isplainhostname() syntax isplainhostname(host) parameters host the hostname from the url (excluding port number). description true if and only if there i...
...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...
... the fundamentals, you can use the javascript reference to get more details on individual objects and statements. what is javascript? javascript is a cross-platform, object-oriented scripting language used to make webpages interactive (e.g., having complex animations, clickable buttons, popup menus, etc.). there are also more advanced server side versions of javascript such as node.js, which allow you to add more functionality to a website than simply downloading files (such as realtime collaboration between multiple computers). inside a host environment (for example, a web browser), javascript can be connected to the objects of its environment to provide programmatic control over them. javascript contains a standard library of objects, such as array, date, and math, and a core set of lan...
... array, date, and math, and a core set of language elements such as operators, control structures, and statements. core javascript can be extended for a variety of purposes by supplementing it with additional objects; for example: client-side javascript extends the core language by supplying objects to control a browser and its document object model (dom). ...
...And 4 more matches
Functions - JavaScript
rs of a function call are the function's arguments. arguments are passed to functions by value. if the function changes the value of an argument, this change is not reflected globally or in the calling function. ...
...ist of such strings separated with a comma; for example "x", "thevalue", or "a,b". functionbody a string containing the javascript statements comprising the function definition. invoking the generatorfunction constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. function parameters default parameters default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. for more details, see default parameters. rest parameters the rest parameter syntax allows representing an indefinite number of arguments as an array. for more details, see rest parameters. the arguments object you can refer to a function's arguments within the function by using the arguments object. s...
... set binds an object property to a function to be called when there is an attempt to set that property. method definition syntax starting with ecmascript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. see method definitions for more information. var obj = { foo() {}, bar() {} }; constructor vs. declaration vs. ...
...And 4 more matches
Array.prototype.forEach() - JavaScript
ue in the array. array optional the array foreach() was called upon. thisarg optional value to use as this when executing callback. return value undefined. description foreach() calls a provided callback function once for each element in an array in ascending order. it is not 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 ...
...ach() 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 time foreach() visits them; elements that are deleted before being visited are not visited. if elements that are already visited are removed (e.g. using shift()) during the iteration, later elements will be skipped. (see this example, below.) foreach() executes the callback function once for each array element; unlike map() 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 ex...
... const items = ['item1', 'item2', 'item3'] const copyitems = [] // before for (let i = 0; i < items.length; i++) { copyitems.push(items[i]) } // after items.foreach(function(item){ copyitems.push(item) }) printing the contents of an array note: in order to display the content of an array in the console, you can use console.table(), which prints a formatted version of the array. the following example illustrates an alternative approach, using foreach(). the following code logs a line for each element in an array: function logarrayelements(element, index, array) { console.log('a[' + index + '] = ' + element) } // notice that index 2 is skipped, since there is no item at // that position in the array... [2, 5, , 9].foreach(logarrayelements) // logs: // a[0] = 2 // a[1] = 5 // a...
...And 4 more matches
Array.prototype.map() - JavaScript
one https://github.com/mdn/interactive-examples and send us a pull request. syntax let new_array = arr.map(function callback( currentvalue[, index[, array]]) { // return element for new_array }[, thisarg]) parameters callback function that is called for every element of arr. each time callback executes, the returned value is added to new_array. the callback function accepts the following arguments: currentvalue the current element being processed in the array. indexoptional the index of the current element being processed in the array. arrayoptional the array map was called upon. thisargoptional value to use as this when executing callback. return value a new array with each element being the result of the callback function. description map calls a pr...
...ns and before being visited are not visited. due to the algorithm defined in the specification, if the array which map was called upon is sparse, resulting array will also be sparse keeping same 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 // referenc...
...k, and o. mappedvalue = callback.call(t, kvalue, k, o); // iii. call the defineownproperty internal method of a with arguments // pk, property descriptor // { value: mappedvalue, // writable: true, // enumerable: true, // configurable: true }, // and false. // in browsers that support object.defineproperty, use the following: // object.defineproperty(a, k, { // value: mappedvalue, // writable: true, // enumerable: true, // configurable: true // }); // for best browser support, use the following: a[k] = mappedvalue; } // d. increase k by 1. k++; } // 9. return a return a; }; } examples mapping an array of nu...
...And 4 more matches
Array.prototype.sort() - JavaScript
ud655\ude55 will be sorted before the character \uff3a. if comparefunction is supplied, all non-undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to comparefunction). ...
...x lower than b (i.e. a comes first). if comparefunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. note: the ecmascript standard does not guarantee this behavior, thus, not all browsers (e.g. mozilla versions dating back to at least 2003) respect this. if comparefunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first). comparefunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. if inconsistent results are returned, then the sort order is undefined. ...
...ozilla versions dating back to at least 2003) respect this. if comparefunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first). comparefunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. if inconsistent results are returned, then the sort order is undefined. ...
...And 4 more matches
Array.prototype.splice() - JavaScript
an array.length - start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all the elements from start to the end of the array will be deleted. note: in ie8, it won't delete all when deletecount is omitted. if deletecount is 0 or negative, no elements are removed. in this case, you should specify at least one new element (see below). item1, item2, ... optional the elements to add to the array, beginning from start. if you do not specify any elements, splice() will only remove elements from the array. return value an array containing the deleted elements. if only one element is removed, an array of one element is returned. if no elements are removed, an empty array is returned. description if the specified number of...
...taining the deleted elements. if only one element is removed, an array of one element is returned. if no elements are removed, an empty array is returned. description if the specified number of elements to insert differs from the number of elements being removed, the array's length will be changed. ...
... if no elements are removed, an empty array is returned. description if the specified number of elements to insert differs from the number of elements being removed, the array's length will be changed. ...
...And 4 more matches
Math.clz32() - JavaScript
-speaking people). however, a clon function can easily be created by inversing the bits of a number and passing the result to math.clz32. doing this will work because the inverse of 1 is 0 and vice-versa. thus, inversing the bits will inverse the measured quantity of 0's (from math.clz32), thereby making math.clz32 count the number of ones instead of counting the number of zeros. ...
...es instead of counting the number of zeros. consider the following 32-bit word: var a = 32776; // 00000000000000001000000000001000 (16 leading zeros) math.clz32(a); // 16 var b = ~32776; // 11111111111111110111111111110111 (32776 inversed, 0 leading zeros) math.clz32(b); // 0 (this is equal to how many leading one's there are in a) using this logic, a clon function can be created as follows: var clz = math.clz32; function clon(integer){ return clz(~integer); } further, this technique could be extended to create jumpless "count trailing zeros" and "count trailing ones" functions as seen below. the ctrz function below fills in all the high bits with the lowest filled bit, then negates the bits to erase all higher set bits so that clz can then be used. var clz = math.clz32; fu...
...en negates the bits to erase all higher set bits so that clz can then be used. var clz = math.clz32; function ctrz(integer){ // count trailing zeros // 1. fill in all the higher bits after the first one integer |= integer << 16; integer |= integer << 8; integer |= integer << 4; integer |= integer << 2; integer |= integer << 1; // 2. now, inversing the bits reveals the lowest bits return 32 - clz(~integer) |0; // `|0` ensures integer coercion } function ctron(integer){ // count trailing ones // no shift-filling-in-with-ones operator is available in // javascript, so the below code is the fastest return ctrz(~integer); /* alternate implementation for demonstrational purposes: // 1. erase all the higher bits after the first zero inte...
...And 4 more matches
Promise - JavaScript
the promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. to learn about the way promises work and how you can use them, we advise you to read using promises first. description a promise is a proxy for a value not necessarily known when the promise is created. it allows you to associate handlers with an asynchronous action's eventual success value or failure reason. this lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future. a promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation completed successf...
...lerejectedc); // or, perhaps better ... const mypromise = (new promise(myexecutorfunc)) .then(handlefulfilleda) .then(handlefulfilledb) .then(handlefulfilledc) .catch(handlerejectedany); handling a rejected promise too early has consequences further down the promise chain. sometimes there is no choice, because an error 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" stat...
...omise, the effect is a dynamic replacement. the return causes a promise to be popped, but the nextvalue promise is pushed into its place. for the nesting shown above, suppose the .then() associated with "promise b" returns a nextvalue of "promise x". the resulting nesting would look like this: (promise d, (promise c, (promise x) ) ) a promise can participate in more than one nesting. for the following code, the transiton of promisea into a "settled" state will cause both instances of .then() to be invoked. const promisea = new promise(myexecutorfunc); const promiseb = promisea.then(handlefulfilled1, handlerejected1); const promisec = promisea.then(handlefulfilled2, handlerejected2); an action can be assigned to an already "settled" promise. in that case the action (if appropriate) will b...
...And 4 more matches
String.prototype.charAt() - JavaScript
acters in a string are indexed from left to right. the index of the first character is 0, and the index of the last character—in a string called stringname—is stringname.length - 1. if the index you supply is out of this range, javascript returns an empty string. if no index is provided to charat(), the default is 0. ...
...aracter at index 1 is '" + anystring.charat(1) + "'"); console.log("the character at index 2 is '" + anystring.charat(2) + "'"); console.log("the character at index 3 is '" + anystring.charat(3) + "'"); console.log("the character at index 4 is '" + anystring.charat(4) + "'"); console.log("the character at index 999 is '" + anystring.charat(999) + "'"); these lines display the following: the character at index 0 is 'b' the character at index 0 is 'b' the character at index 1 is 'r' the character at index 2 is 'a' the character at index 3 is 'v' the character at index 4 is 'e' the character at index 999 is '' getting whole characters the following provides a means of ensuring that going through a string loop always provides a whole character, even if the strin...
... var code = str.charcodeat(i); if (number.isnan(code)) { return ''; // position not found } if (code < 0xd800 || code > 0xdfff) { return str.charat(i); } // high surrogate (could change last hex to 0xdb7f to treat high private // surrogates as single characters) if (0xd800 <= code && code <= 0xdbff) { if (str.length <= (i + 1)) { throw 'high surrogate without following low surrogate'; } var next = str.charcodeat(i + 1); if (0xdc00 > next || next > 0xdfff) { throw 'high surrogate without following low surrogate'; } return str.charat(i) + str.charat(i + 1); } // low surrogate (0xdc00 <= code && code <= 0xdfff) if (i === 0) { throw 'low surrogate without preceding high surrogate'; } var prev = str.charcodeat(i - 1...
...And 4 more matches
String.prototype.split() - JavaScript
n empty string (""), str is converted to an array of each of its utf-16 "characters". warning: when the empty string ("") is used as a separator, the string is not split by user-perceived characters (grapheme clusters) or unicode characters (codepoints), but by utf-16 codeunits. this destroys surrogate pairs. see “how do you get a string to a character array in javascript?” on stackoverflow. limit optional a non-negative integer limiting the number of pieces. if provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. any leftover text is not included in the array at all. the array may contain fewer entries than limit if the end of the string is reached before the limit is reached. if limit ...
... separator is an array, then that array is coerced to a string and used as a separator. examples using split() when the string is empty, split() returns an array containing one empty string, rather than an empty array. if the string and separator are both empty strings, an empty array is returned. const mystring = '' const splits = mystring.split() console.log(splits) // ↪ [""] the following example defines a function that splits a string into an array of strings using separator. after splitting the string, the function logs messages indicating the original string (before the split), the separator used, the number of elements in the array, and the individual array elements. function splitstring(stringtosplit, separator) { const arrayofstrings = stringtosplit.split(separator) ...
... the original string is: "oh brave new world that has such people in it." the separator is: "undefined" the array has 1 elements: oh brave new world that has such people in it. the original string is...
...And 4 more matches
encodeURI() - JavaScript
ibute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax encodeuri(uri) parameters uri a complete uri. return value a new string representing the provided string encoded as a uri. description the encodeuri() function does not encode characters that have special meaning (reserved characters) for a uri. the following example shows all the parts that a uri "scheme" can possibly contain. note how certain characters are used to signify special meaning: http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor hence encodeuri() does not encode characters that are necessary to formulate a complete uri. also, encodeuri() does not encode a few additional characters, known a...
...ain. note how certain characters are used to signify special meaning: http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor hence encodeuri() does not encode characters that are necessary to formulate a complete uri. ...
...: @ & = + $ - _ . ...
...And 4 more matches
<mo> - MathML
Web › MathML › Element › mo
the mathml <mo> element represents an operator in a broad sense. besides operators in strict mathematical meaning, this element also includes "operators" like parentheses, separators like comma and semicolon, or "absolute value" bars. attributes accent if the operator is used as an under- or overscript this attribute specifies whether the operator should be treated as an accent. allowed values are true or false. 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). fence there is no visual effect for this attribute, but it specifies whether the operator is a fence (such as parentheses). allowed values are true or false. form specifies the role of the operator in an enclosed expression,...
...for separators. (it is the default value if the operator is not included in a <mrow> element.) postfix, closing fences. (it is the default value if the operator is the last argument in a <mrow> element with more than one argument.) href used to set a hyperlink to a specified uri. largeop specifies whether the operator should be drawn larger than normal when displaystyle="true" is set. allowed values are either true or false. lspace the amount of space before the operator (see length for values and units). the constant thickmathspace (5/18em) is the default value. 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. mathsize the size of the content. see length for possibl...
...all, normal and big. these will be removed in the future. mathvariant this attribute specifies the logical class of the operator which varies in typography. that is, although the names suggest the typographic style for the class, semantically, items with the same class are treated "the same" within an expression, which might or might not involve displaying them with the named typography. ...
...And 4 more matches
Privacy, permissions, and information security
ntally, privacy of your data on the internet is about ensuring that information that has personal implications is kept out of the hands of unauthorized persons or organizations, regardless of how it's obtained. privacy exceptions may be granted to specific sites or applications, but it may also be granted conditionally, such as by permitting only a select group of people to access it, or only allowing the information to be accessed and used for a limited period of time. security security is about the active protection of data or a system against being accessed, downloaded, or operated by people or organizations that don't have permission to do so. good security practices aim to prevent unauthorized access to systems or data, regardless of what the target is. personal and private i...
...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 identification purposes. for example, if a web site queries a user's browser for the elapsed time, a comparison of that time to the time as reported by the server might be useful as a factor in fingerprinting. because of this, browsers typically introduce ...
...ainst security and privacy breaches. these start at the web server, include the very communication layer used over the network, and then extend through the web browser's security offerings before reaching your web app code and the efforts it takes to secure itself and the data the user entrusts to it. there are several web technologies and features at play to manage privacy and security. the following list includes features affecting both, since many of these features are used for both. web technologies and features used to enforce security and privacy technology or feature description certificate transparency an open standard for monitoring and auditing certificates, creating a database of public logs that can be used to help identify incorrect or malicious ce...
...And 4 more matches
SVG fonts - SVG: Scalable Vector Graphics
er sans bold"/> </font-face-src> </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...
...s the svg equivalent of the css @font-face declaration. it defines basic properties of the final font such as weight, style, etc. in the example above the first and most important to be defined is font-family, the value of which can then be referenced in css and svg font-family properties. the font-weight and font-style attributes have the same purpose as the equivalent descriptors in css. all following attributes are rendering instructions for the font layout engine, for example, how much of the glyphs' overall heights are ascenders. its child, the <font-face-src> element, corresponds to css' src descriptor in @font-face declarations. you can point to external sources for font declarations by means of its children <font-face-name> and <font-face-uri>. the above example states that if the re...
... of the glyphs' overall heights are ascenders. its child, the <font-face-src> element, corresponds to css' src descriptor in @font-face declarations. you can point to external sources for font declarations by means of its children <font-face-name> and <font-face-uri>. the above example states that if the renderer has a local font available named "super sans bold", it should use this instead. following <font-face-src> is a <missing-glyph> element. this defines what should be displayed if a certain glyph is not found in the font and if there are no fallback mechanisms. it also shows how glyphs are created: by simply adding any graphical svg content inside. you can use literally any other svg elements in here, even <filter>, <a> or <script>. for simple glyphs, however, you can simply add a d a...
...And 4 more matches
WebAssembly
in a nutshell webassembly has huge implications for the web platform — it provides a way to run code written in multiple languages on the web at near native speed, with client apps running on the web that previously couldn’t have done so. ...
... in a nutshell webassembly has huge implications for the web platform — it provides a way to run code written in multiple languages on the web at near native speed, with client apps running on the web that previously couldn’t have done so. ...
...eb platform — it provides a way to run code written in multiple languages on the web at near native speed, with client apps running on the web that previously couldn’t have done so. webassembly is designed to complement and run alongside javascript — using the webassembly javascript apis, you can load webassembly modules into a javascript app and share functionality between the two. this allows you to take advantage of webassembly's performance and power and javascript's expressiveness and flexibility in the same apps, even if you don't know how to write webassembly code. and what's even better is that it is being developed as a web standard via the w3c webassembly working group and community group with active participation from all major browser vendors. guides webassembly conc...
...And 4 more matches
Classes and Inheritance - Archive of obsolete content
a class is a blueprint from which individual objects are created. these individual objects are the instances of the class. each class defines one or more members, which are initialized to a given value when the class is instantiated. data members are properties that allow each instance to have their own state, whereas member functions are properties that allow instances to have behavior. inheritance allows classes to inherit state and behavior from an existing classes, known as the base class. unlike languages like c++ and java, javascript does not have native support for classical inheritance. instead, it uses something called prototypal inheritance. as it turns out, it is possible to emulate classical inheritance using prototypal inheritance, but not without writing a significant amount of...
...rs suppose we want to create a new class, circle, and inherit it from shape. since every circle is also a shape, the constructor for shape must be called every time we call the constructor for circle. since javascript does not have native support for inheritance, it doesn't do this automatically. instead, we need to call the constructor for shape explicitly. the resulting constructor looks as follows: function circle(x, y, radius) { if (!this) return new circle(x, y, radius); shape.call(this, x, y); this.radius = radius; } note that the constructor for shape is called as an ordinary function, and reuses the object created for the constructor call to circle. had we used a constructor call instead, the constructor for shape would have been applied to a different object than ...
...object than the constructor for circle. we can now use the above constructor to create instances of the class circle: let circle = circle(2, 3, 5); circle instanceof circle; // => true circle.x; // => 2 circle.y; // => 3 circle.radius; // => 5 inheritance and prototypes there is a problem with the definition of circle in the previous section that we have glossed over thus far. consider the following: let circle = circle(2, 3, 5); circle.draw(); // => typeerror: circle.draw is not a function this is not quite right. the method draw is defined on instances of shape, so we definitely want it to be defined on instances of circle. the problem is that draw is defined on the prototype of shape, but not on the prototype of circle. we could of course copy every property from the prototype of sh...
...And 3 more matches
Developing for Firefox Mobile - Archive of obsolete content
firefox for android implements its ui using native android widgets instead of xul. with the add-on sdk you can develop add-ons that run on this new version of firefox mobile as well as on the desktop version of firefox. you can use the same code to target both desktop firefox and firefox mobile, and use jpm-mobile instead of the normal jpm. right now not all modules are fully functional, but we're working on adding support for more modules. ...
...this guide list the modules that are currently supported on firefox mobile. this tutorial explains how to run sdk add-ons on an android device connected via usb to your development machine. we'll use the android debug bridge (adb) to communicate between the add-on sdk and the device. it's possible to use the android emulator to develop add-ons for android without access to a device, but it's slow, so for the time being it's much easier to use the technique described below. setting up the environment first you'll need an android device capable of running the native version of firefox mobile. then: install the nightly build of the native version of firefox mobile on the device. enable usb debugging on the device (step 2 of this link only) on the development machine: install versi...
...a.fennec pushing the addon to your device starting: intent { act=android.activity.main cmp=org.mozilla.fennec/.app (has extras) } --------- beginning of /dev/log/main --------- beginning of /dev/log/system could not read chrome manifest 'file:///data/data/org.mozilla.fennec/chrome.manifest'. info: starting info: starting zerdatime 1329258528988 - browser chrome startup finished. this will be followed by lots of debug output. on the device, you should see firefox launch with your add-on installed. console.log() output from your add-on is written to the command shell, just as it is in desktop development. however, because there's a lot of other debug output in the shell, it's not easy to follow. the command adb logcat prints adb's log, so you can filter the debug output after running the ad...
...And 3 more matches
Canvas code snippets - Archive of obsolete content
this can be very useful to compare for example if a user has painted over another area as explained in this blog post. ...
...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]...
...earrect', 'clip', 'closepath', 'drawimage', 'fill', 'fillrect', 'filltext', 'lineto', 'moveto', 'quadraticcurveto', 'rect', 'restore', 'rotate', 'save', 'scale', 'settransform', 'stroke', 'strokerect', 'stroketext', 'transform', 'translate']; var gettermethods = ['createpattern', 'drawfocusring', 'ispointinpath', 'measuretext', // drawfocusring not currently supported // the following might instead be wrapped to be able to chain their child objects 'createimagedata', 'createlineargradient', 'createradialgradient', 'getimagedata', 'putimagedata' ]; var props = ['canvas', 'fillstyle', 'font', 'globalalpha', 'globalcompositeoperation', 'linecap', 'linejoin', 'linewidth', 'miterlimit', 'shadowoffsetx', 'shadowoffsety', 'shadowblur', 'shadowcolor', 'strokest...
...And 3 more matches
HTML to DOM - Archive of obsolete content
atures are more widely available. safely parsing simple html to dom when using xmlhttprequest to get the html of a remote webpage, it is often advantageous to turn that html string into dom for easier manipulation. however, there are potential dangers involved in injecting remote content in a privileged context in your extension, so it can be desirable to parse the html safely. the function below will safely parse simple html and return a dom object which can be manipulated like web page elements. this will remove tags like <script>, <style>, <head>, <body>, <title>, and <iframe>. it will also remove all javascript, including element attributes that contain javascript. function htmlparser(ahtmlstring){ var html = document.implementation.createdocument("http://www.w3.org/1999/xhtml", "h...
...efore you can retrieve info within div tag like this: var dompars = htmlparser("<div id='userinfo'>john was a mediocre programmer, but people liked him <strong>anyway</strong>.</div>"); alert(dompars.getelementbyid('userinfo').innerhtml); to parse a complete html page, load it into an iframe whose type is content (not chrome). see using a hidden iframe element to parse html to a window's dom below. parsing complete html to dom loading an html document seems much simpler if it's loaded using the xmlhttprequest object. for that matter, we're going to load our html document first: var request = xmlhttprequest(); request.open("get", "http://example.org/file.html", false); request.send(null); our next step is to create the document object that will represent the dom into which we'll insert...
...create your own function using unique name, id, and so forth. var frame = document.getelementbyid("sample-frame"); if (!frame) { // create frame frame = document.createelement("iframe"); // iframe (or browser on older firefox) frame.setat...
...And 3 more matches
Adding windows and dialogs - Archive of obsolete content
, the second is an id to identify the window, and the last is an optional 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 wi...
...ing. never open modal windows at startup. resizable. indicates the user can resize the window or not. in general, windows should not be resizable unless they display dynamically generated content from a datasource, such as lists or trees that may need resizing to have a better view of the content. to open a new dialog, use the function window.opendialog, an extension of the open function. it allows you to send a set of optional parameters that can be used to communicate with the dialog. let somevalue = 2; let returnvalue = { accepted : false , result : "" }; window.opendialog( "chrome://xulschoolhello/content/somedialog.xul", "xulschoolhello-some-dialog", "chrome,centerscreen", somevalue, returnvalue); // you can send as many extra parameters as you need. // if (returnvalue.acce...
...k to use this function if you're just debugging some problem and want to see if the program reaches a specific line of code, or to inspect the value of a variable, but your final extension should not have alert calls anywhere. if you use window.alert, the alert window will have the title [javascript application], indicating that the source of the message is not well defined. ...
...And 3 more matches
Connecting to Remote Content - Archive of obsolete content
pen("get", url, true); request.send(null); in this example we demonstrate how to make a xmlhttprequest call in asynchronous mode. you can see that an instance of the xmlhttprequest class is created and it holds all functionality for making a request. we create this instance using xpcom instead of the usual way (new xmlhttprequest()) because this way works both in chrome and non-chrome code. following initialization, onload and onerror handlers are registered to a callback function to handle the response returned from the remote server. in both cases aevent.target is an nsixmlhttprequest. in the onload callback function, the responsetext parameter contains the server response as text. if the response is an xml document, the responsexml property will hold an xmldocument object that can be m...
...the response to be parsed as xml. request.overridemimetype("text/xml"); // do this before sending the request! the open method takes two required parameters: the http request method and the url to send the request. the http request method can be "get", "post" or "put". sending a post request requires you to set the content type of the request and to pass the post data to the send() method as below. request.open("post", url, true); request.setrequestheader("content-type", "application/x-www-form-urlencoded"); request.send("data=hello&version=2"); the third parameter for the open method specifies whether the request should be handled asynchronously or not. in asynchronous mode code execution continues immediately after the send call. in synchronous mode the code and user interface are blo...
...is obtained and processed. therefore, it is very important that xmlhttprequest calls are always done asynchronously. now let's look at the most common types of content you can use to communicate with remote servers. json content json is a very lightweight and simple data representation format, similar to the object representation used in javascript. unlike javascript, the json format doesn't allow any kind of code that can be run, only data. json used to be risky in terms of security because the favored way of parsing it was to use the javascript eval function. since eval executes any code contained in the string, workarounds had to be devised in order to close security holes. luckily, firefox now provides a few alternatives for extension developers. the json page explains in detail how t...
...And 3 more matches
Dehydra Object Reference - Archive of obsolete content
have a .loc. dehydra only sets boolean flags when they are true. for example, a pointer type will have .ispointer == true, but a class type will not have an .ispointer property. common properties property type description .loc location object source location of a type or declaration. .attributes array of objects attributes of the type or declaration. ...
... .type type object the type of this function or variable. .isstatic boolean flag .isreturn boolean flag the variable is being returned. .isdecl boolean flag the variable is being declared (local variables only). ...
... variable would be a .fieldof membervar/fn in foo->membervar or foo->memberfn(). note that when constructing the return value of a function (e.g. return t();), no container variable is available; in this case, .isreturn will be true (see function variable). variables can identified by their dehydradecl() prototype. function variable function objects are an extension of variable objects. the following additional properties are available on functions: property type description .isvirtual true or "pure" true for virtual methods, or "pure" for pure virtuals (e.g. virtual void foo() = 0;). .isconstructor boolean flag constructors generally have a .fieldof attribute (see variable objects). .isfunction boolean flag true for function variables. type objects dehydra provides detaile...
...And 3 more matches
Using Dehydra - Archive of obsolete content
as gcc compiles file, dehydra calls functions in the user analysis script with information about the code being compiled. for more information, see the function reference and the object reference. ...
... as gcc compiles file, dehydra calls functions in the user analysis script with information about the code being compiled. for more information, see the function reference and the object reference. ...
...unction reference and the object reference. ...
...And 3 more matches
Editor Embedding Guide - Archive of obsolete content
eated underneath and the event listeners are all prepa if (ns_failed(rv)) return ns_error_failure; // we are not setup??!! ...
...get the nsicommandmanager from the...
...get the nsicommandmanager from the nsiwebbrowser using do_getinterface: nscomptr<nsicommandmanager> commandmanager; nsiwebbrowser->do_getinterface(getter_addrefs(commandmgr)); 2. ...
...And 3 more matches
Style System Overview - Archive of obsolete content
e, since frames point to style contexts rather than the other way around. style contexts own their parents, since inheritance operates through style context parents (ugly when we have multiple frames per content node). there is one rule node on the path from the root rule node to the style context's rule node for each rule that the element matches. style context api the style context api allows data to be obtained through a set of structs (see nsstylestruct.h). a struct for a style context can be obtained through nsistylecontext::getstyledata. nsiframe::getstyledata does the same thing for the frame's mstylecontext member, and the global ::getstyledata is a typesafe helper that doesn't require the style struct id. this style struct is always const, and should always be declared as su...
... doc: b ↙ ↓ ↘ title: c para: f class="emph" para: d ↓ ↓ quote: a quote: a ↓ span: e class="emph" the rule tree and style data all of the style structs that can be obtained through a style context add up to around 900 bytes. this is big, and slow to fill in. the rule tree allows sharing. to allow for optimizations, each style struct contains only inherited properties or only “reset” properties. (thus these structs can be called inherited structs or reset structs.) in the normal case, a style rule has a small number of declarations (hitting only a small number of structs). the rule tree and style data we optimize for the structs f...
...like reset ones in the descendants of any rule node for which the data are fully specified. style data cached in style context tree if a style struct for a context depends on the data in the parent context, we will cache that struct in the style context tree. this happens when properties are inherited or when percentage units are used in a way that is handled by the style code (rather than reflow). if the data are exactly the same as those of the parent, we copy the struct to the child style context and set a bit saying that it doesn't own the struct. (the context tree can be deep.) each rule node has a per-struct set of “none bits” that say that the rule node's set of rules (the rules on the path to the root) specify nothing non-inherited for the struct. style data cached in rule...
...And 3 more matches
Menu - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Menu
features can also create new menus and attach them almost anywhere, chrome or content, as popup menus or context menus. ...
...e, so you may want to start by reading through some examples. because it is still under development, the api currently lives in the future and must be imported before it is used: jetpack.future.import("menu"); menus all menus in jetpack are jetpack.menu objects, including both built-in firefox menus and menus that features create. to create a new menu, use one of the jetpack.menu constructors below. constructors jetpack.menu() creates an empty menu. jetpack.menu(menuitems) creates a menu with the given items. parameters menuitems an array of menuitems. jetpack.menu(properties) creates a menu with specific properties. parameters properties an object defining any of the properties below. the items property may be used to define an array of menuitems. properties...
... this node, which may be either a raw dom node or a dom node wrapped by jquery. menuitems menus in jetpack contain menuitem objects, including both built-in firefox menus and menus that features create. no menuitem constructor is exposed, because jetpack automatically boxes simple javascript objects into menuitem objects. creating menuitems to pass a new menuitem into the api, pass one of the following types: null a simple menu separator. (note that any falsey value will suffice, including undefined, null, and the empty string. null is recommended because it stands out.) function a menuitem that will update itself when its menu is shown. the function is invoked just before the item's menu is shown and when the items array of the item's menu is retrieved. it must return a non-function menuite...
...And 3 more matches
Mozilla Crypto FAQ - Archive of obsolete content
zilla 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 was the fact that rsa security, inc., held a u.s. patent on the rsa public key algorithm. in february 2000 iplanet e-commerce solutions (a sun-netscape alliance) released source code through mozilla.org for the personal security manager and network security serv...
...evelopment, but may not be available in mozilla until after the 1.0 release. version 3.1 of the network security services library will include a complete open source implementation of the cryptographic algorithms needed for mozilla ssl support, including the rsa public key algorithm (now in the public domain). nss 3.1 will be available in beta form in september 2000, with the final release to follow in october 2000. nss 3.1 will be used in the 1.3 release of psm, which will provide a complete open source implementation of ssl for mozilla. psm 1.3 will also provide support for mozilla users to obtain personal digital certificates and perform other pki-related functions. note that due to various implementation issues, psm support for mozilla on the macintosh is lagging somewhat behind psm sup...
...eleased source code is dual-licensed under the mpl and the gpl. the mozilla ssl, s/mime, and pki source code is licensed under the mozilla public license (version 1.1), with the gnu general public license (version 2.0 or later) available as an alternate license. you may choose to use the code either under the terms of the mpl or under the terms of the gpl. this form of licensing was chosen to allow the released personal security manager and network security services source code to be used in as many contexts as possible; for example, the psm and nss code can be used in mozilla under mpl terms, and can also be used in gnu and other projects under gpl terms. if you create and distribute modifications to the original psm and nss code, we ask that you in turn make such modifications available u...
...And 3 more matches
How to Write and Land Nanojit Patches - Archive of obsolete content
rg/showbuilds.cgi?tree=nanojit commit log: http://hg.mozilla.org/projects/nanojit-central/shortlog/ irc channel: irc.mozilla.org #nanojit procedure the first thing to understand is that there are now three copies of nanojit in public mozilla.com repositories: one in nanojit-central, one in tracemonkey, one in tamarin-redux. ...
...central/shortlog/ irc channel: irc.mozilla.org #nanojit procedure the first thing to understand is that there are now three copies of nanojit in public mozilla.com repositories: one in nanojit-central, one in tracemonkey, one in tamarin-redux. we land patches initially in nanojit-central, and those landings are followed up with semi-automated landings on tracemonkey and tamarin-redux. ...
... in tamarin-redux. we land patches initially in nanojit-central, and those landings are followed up with semi-automated landings on tracemonkey and tamarin-redux. these follow-up landings on tracemonkey and tamarin-redux will overwrite any changes made to nanojit in tracemonkey and tamarin-redux! so, do not land nanojit changes directly to the tracemonkey and tamarin-redux repositories! the following files in tracemonkey are from nanojit: everything in js/src/nanojit/ everything in js/src/vprof/ scenario 0: a common prefix for all scenarios make private clones of all three repositories: nanojit-central, tracemonkey and tamarin-redux. here's how to clone and build nanojit-central: $ hg clone ssh://hg.mozilla.org/projects/nanojit-central $ cd nanojit-central $ autoconf $ mkdir build $ cd...
...And 3 more matches
Table Layout Strategy - Archive of obsolete content
ecommendations: html 4.01 (chapter 11) and css2.1 (chapter 17).in css2 a distinction between fixed and auto layout of tables has been introduced. the auto-layout mechanism is implemented in basictablelayoutstrategy.cpp the fixed-layout in fixedtablelayoutstrategy.cpp. all these files are in the layout/html/table/src subdirectory. the code the layout strategies are invoked from nstableframe::reflow. the overload of the initialize and balancecolumnwidths routines depends on the table style and is decided at runtime. on the first reflow nstableframe::balancecolumnwidths is called. inside this routine the corresponding table layout strategy is created and initialized (basictablelayoutstrategy::initialize). later the column widths are balanced by basictablelayoutstrategy::balancecolumnwidths or...
...cecolumnwidths routines depends on the table style and is decided at runtime. on the first reflow nstableframe::balancecolumnwidths is called. inside this routine the corresponding table layout strategy is created and initialized (basictablelayoutstrategy::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. ...
...d initialized (basictablelayoutstrategy::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 withou...
...And 3 more matches
Tamarin Build System Documentation - Archive of obsolete content
o my test repository) (next line) buildsdir=~/hg/builds (a directory to store downloaded builds) always set current working directory to the scripts directory when running a script run a script (e.g.) ../all/run-acceptance-release.sh <optional hg revision number like 1902> how do i navigate the build status page? ...
...ent working directory to the scripts directory when running a script run a script (e.g.) ../all/run-acceptance-release.sh <optional hg revision number like 1902> how do i navigate the build status page? the page is divided into the phase table at the top and the waterfall table below the phase table shows all phases at the top of the page, each slave is shown as a box with a red,green, or yellow color: red means failed, green passed, and yellow has warnings. ...
... waterfall table below the phase table shows all phases at the top of the page, each slave is shown as a box with a red,green, or yellow color: red means failed, green passed, and yellow has warnings. the phase state is idle or active click on the phase (e.g. ...
...And 3 more matches
Tamarin mercurial commit hook - Archive of obsolete content
it is highly recommended that all developers enable the mercurial commit hook for tamarin. the hook is located in the tamarin-redux repository in the file utils/hooks/tamarin-commit-hook.py this is a simple mercurial hook that checks the following filetypes ('.cpp', '.h', '.as', '.abs', '.py') for the following: tabs anywhere in the line trailing whitespace windows line endings (\r\n) "mark_security_change" - looks for this text and warns user as security changes should not be checked into the public tamarin-redux repository. ...
...pes ('.cpp', '.h', '.as', '.abs', '.py') for the following: tabs anywhere in the line trailing whitespace windows line endings (\r\n) "mark_security_change" - looks for this text and warns user as security changes should not be checked into the public tamarin-redux repository. installing the commit hook the easiest way to implement the hook is to sync to the tip of tamarin-redux then add the following to your tamarin-redux/.hg/hgrc file (or to ~/.hgrc to implement for all local repos): [hooks] pretxncommit.commit = python:/path/to/tamarin-redux/utils/hooks/tamarin-commit-hook.py:master_hook once added, all commits will run the commit hook. hook use on every commit to your local repository, the hook will only check for violations in any new / changed code. any untouched lines of code that ...
...or all local repos): [hooks] pretxncommit.commit = python:/path/to/tamarin-redux/utils/hooks/tamarin-commit-hook.py:master_hook once added, all commits will run the commit hook. hook use on every commit to your local repository, the hook will only check for violations in any new / changed code. any untouched lines of code that violate the check will be ignored. ...
...And 3 more matches
Treehydra Manual - Archive of obsolete content
bie documentation to be had. callbacks and gcc intermediate representations like dehydra, treehydra sends program representations to the user javascript via callbacks. there are 3 treehydra callbacks. note that the callbacks interact with other treehydra options. to make things easier, we will first present recipes for accessing specific gcc intermediate representations. treehydra provides the following callbacks to analysis scripts: process_tree_decl, process_tree, process_tree_type, and process_cp_pre_genericize. fixme document all these callbacks. c++ asts c++ asts are provided via the process_cp_pre_genericize callback. this is called just before gcc converts the c++-specific ast to the generic (language-independent) representation. example treehydra script: function process_cp_pre_gener...
...d just before gcc converts the c++-specific ast to the generic (language-independent) representation. example treehydra script: function process_cp_pre_genericize(fn) { // fn is a function_decl, decl_saved_tree(fn) is ast print(fn); } gimple asts gimple asts are provided via the process_tree callback. by default, this is called just after gcc converts the ast to gimple, before any further lowering or optimization. example: function process_tree(fn) { // fn is a function_decl, decl_saved_tree(fn) is ast print(fn); } gimple cfgs process_tree can also provide gimple cfgs. to get cfgs, you must instruct treehydra to call process_tree after cfg construction. in this case, gimple asts will not be available, as gcc does not save earlier intermediate representations--they are modifi...
...require({ after_gcc_pass: "einline" + (isgcc42 ? "" : "_ipa")}); include('gcc_util.js'); ...
...And 3 more matches
Elements - Archive of obsolete content
re other namespace prefixes used in your binding. bindings contains zero or more binding elements as children. each binding child element defines a unique binding that can be attached to elements in other documents. an element can have only one binding attached (explicitly or inherited) at one moment. from several bindings only the last in the sequence will be used (like with any css rule). ...
... next: bindings > binding element. notes in the current stable releases of mozilla products (e.g. firefox 2) it is impossible to attach bindings to table sub-elements (rows, cells etc.) you can attach binding only to the table element itself. this has been fixed for future versions of mozilla pr...
... next: bindings > binding element. ...
...And 3 more matches
Additional Navigation - Archive of obsolete content
that such a triple exists in the datasource. the triple doesn't exist for the first result since the title for the first photo is 'palace from above', so the potential result will be removed from the data. for the second result, such an arc does exist, so the result is kept. like the first result, there is no arc for the third photo, so it is also removed. the resulting data will look like the following: (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/canal.jpg) here is the example. naturally, we will need to add a binding for the ?title variable if we wish to display it, or we could just hardcode it since we know the value will be 'canal'. usually you won't be filtering on a title though--you would instead filter on a value that acts li...
...iable used in a triple in either the subject or the object attributes, or both. you can't have a triple with no variables. that's not an issue though, since it wouldn't be particularly useful. also, you cannot use a variable in the predicate. only the subject and object attributes may have variables. another thing that you cannot have is a triple where both variables would be unknown as in the following: <query> <content uri="?start"/> <member container="?start" child="?photo"/> <triple subject="?category" predicate="http://purl.org/dc/elements/1.1/title" object="?title"/> </query> in this case when the template builder gets to the triple, neither the ?category nor the ?title variables can be filled in so the builder doesn't know what to generate. the builder won't...
...he ?category nor the ?title variables can be filled in so the builder doesn't know what to generate. the builder won't generate any output in this situation. the member tag must have variables for both the container and child attributes. it wouldn't be very common to filter for a specific child anyway. source navigation triples may also be used to navigate up the graph as well as downwards, following the graph arrows in the reverse direction. for instance, in the original example, we could start at node d and navigate upwards to a and c. the syntax for the triple is the same except that the known variable should be placed in the triple's object attribute and the unknown variable should be placed in the triple's subject variable. <query> <content uri="?start"/> <triple subject="?relate...
...And 3 more matches
Multiple Rules - Archive of obsolete content
content is generated for it. note that only the first rule, in the order that the rules appear in the template, that matches for a result is used, not all of them that match. thus, you can assume that earlier rules handled earlier matches. for instance, if the first rule matched all folders, then the remaining rules can assume that any results that get past the first rule are not folders. ...
...he first rule, in the order that the rules appear in the template, that matches for a result is used, not all of them that match. thus, you can assume that earlier rules handled earlier matches. for instance, if the first rule matched all folders, then the remaining rules can assume that any results that get past the first rule are not folders. this allows the conditions can be simpler. ...
... for a result is used, not all of them that match. thus, you can assume that earlier rules handled earlier matches. for instance, if the first rule matched all folders, then the remaining rules can assume that any results that get past the first rule are not folders. this allows the conditions can be simpler. it also allows a common technique where the last rule in a template has no conditions, allowing all remaining results that didn't match earlier rules to match this last rule. ...
...And 3 more matches
Result Generation - Archive of obsolete content
is a labeled directed graph. that means that rdf is a graph of nodes and arrows between them where each node and arrow has some label. since it's a graph, arrows can point all over the place and nodes can have any number of arrows pointing out of them and pointing at them. and also because it is a graph, there is no real starting point or root node so you can just start anywhere. in the picture below, you can see that node a at the top has arcs pointing to b, c and d. similarly, c has an arc pointing to d. you could have arcs pointing elsewhere--for example, node d could have an arc pointing back to a. to navigate around, you could start at node a and navigate around the graph following the arrows to b, c or d. or you could start at b and go to a and then go to c and d, etc. no requirement ex...
...ee that node a at the top has arcs pointing to b, c and d. similarly, c has an arc pointing to d. you could have arcs pointing elsewhere--for example, node d could have an arc pointing back to a. to navigate around, you could start at node a and navigate around the graph following the arrows to b, c or d. or you could start at b and go to a and then go to c and d, etc. no requirement exists to follow the arrows in the direction they point; you can easily go the other way (though in only one direction within a given series of iterations). the picture was generated from the w3c's rdf validator, a good place to go to check if your rdf is valid. the text in red are the labels for the arrows, called predicates. in this example, all the arrows have the same label. usually, this won't be the case. ...
... once you have selected a starting point, you use a number of statements which indicate where to go next when navigating the graph. eventually, you will end up with a set of nodes you consider the endpoints of your query. these become the results and content 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 com...
...And 3 more matches
Template and Tree Listeners - Archive of obsolete content
nsixultreebuilderobserver - used to listen to particular tree operations. nsirdfobserver - for rdf datasources, used to listen to changes in the underlying rdf datasource. listening for template rebuilds the first of these is the simplest and involves two methods, willrebuild and didrebuild. ...
...velistener method. listening for tree changes the second type of listener is used to handle particular actions related to trees. the tree builder implements the nsitreeview interface, so handles the gathering of data and passing it on to the tree. the tree widget informs the view when certain operations are performed that might affect the data. the tree view handles all of these operations, but allows an observer to be attached which is invoked during these operations. for instance, the observer may have an ontoggleopenstate method which will be called when the user opens or closes a row. the tree builder will handle the adding or removing of rows, but will call the observer so that it can perform some task. the tree builder observer implements the nsixultreebuilderobserver interface and may ...
...er. some useful functions of the observer are the drag and drop related callbacks to handle when an item is dragged onto the tree. this makes handling dragging onto a tree fairly simple. all you need to do is implement three methods, candropon, candropbeforeafter and ondrop. the tree observer receives drag related events in three places: over a container row, before a row, and after a row. this allows you to handle dragging with more flexibility. for example, in some situations you may want to require dragging onto a folder type of row. in other situations, you may wish to allow items to be dragged between (before or after) rows. this would be the situation if you were dragging items from that tree around, for instance dragging a bookmark from one location to another. the tree widget will dra...
...And 3 more matches
Adding Properties to XBL-defined Elements - Archive of obsolete content
ed to hold a value but may have code execute when an attempt is made to retrieve or modify the value. methods are functions which may be executed. all three are defined within an implementation element, which should be a child of the binding element. within the implementation, you define individual field, property, and method elements, one for each one that you want. the general syntax is as follows: <binding id="element-name"> <content> -- content goes here -- </content> <implementation> <field name="field-name-1"/> <field name="field-name-2"/> <field name="field-name-3"/> <property name="property-name-1"/> <property name="property-name-2"/> <property name="property-name-3"/> . . . <method name="method-name-1"> -- method content goes...
...-- </method> . . . </implementation> </binding> fields each field is defined using the field element. often, fields would correspond to an attribute placed on the element such as label or disabled, but they do not have to. the name attribute on the field element is used to indicate the name of the field. you can use the name from a script to get and set the value. the example below creates a button which generates and stores a random number. you can retrieve this same number multiple times by getting the number property from the button. most of the work here is done in the oncommand handlers. later, we'll find out how to move this to xbl. xul: <box id="random-box" class="randomizer"/> <button label="generate" oncommand="document.getelementbyid('random-box').num...
...is not assigned a default value. to do this, add the default value as the content of the field tag. for example: <field name="number"> 25 </field> this will assign the value 25 as the default value of the number field. actually, you can instead place a script inside the field tag that evaluates to the default value. that might be necessary if the value needs to be computed. for example, the following field is given a default value equal to the current time: <field name="currenttime"> new date().gettime(); </field> properties sometimes you will want to validate the data that is assigned to a property. or, you may want the value to be calculated dynamically as it's asked for. for example, if you want a property that holds the current time, you would want to have its value generated as nee...
...And 3 more matches
Creating a Skin - Archive of obsolete content
« previousnext » this documentation has not updated for firefox quantum. modifying userchrome.css is not guaranteed to work between versions of firefox and may lead to hard-to-diagnose bugs. use at your own risk! this section describes how to create a simple skin. for simplicity, we'll only apply it to the find files dialog. a simple skin the image below shows the current find files dialog. let's create a skin that we can apply to it. normally, a skin would apply to the entire application, but we'll focus on just the find files dialog to make it easier. for this reason, we'll modify only the file findfile.css rather than the global.css file. this section assumes that you are starting with the classic skin. you may wish to make a copy of the files used by the find files ...
...used by the find files dialog before editing. you need to create a file 'findfile.css' in a custom skin. or, you can temporarily place it in the content directory and refer to it using a stylesheet directive. you can modify the existing findfile.css directly to see what it looks like, or you can create a custom skin and link to that. creating a custom skin package to create a skin, do the following: (if you are using firefox 1.5 or later, see manifest files instead of below) create a directory somewhere where you want to place the skin files. copy a manifest file (contents.rdf) from the classic or modern skin into this new directory. modify the references in the manifest file to a custom name for your skin. for example, change references of 'classic/1.0' to 'blueswayedshoes/1.0'. a...
...make sure to add a slash at the end. copy the original findfile.css into the new directory. we'll use this as a basis for the new skin. we can then refer to it using the url 'chrome://findfile/skin/findfile.css'. ...
...And 3 more matches
Install Scripts - Archive of obsolete content
script. creating an install script note: for firefox extensions, install.js are no longer used. you should create a install.rdf instead. you will usually want some form of control over your install process. for example, you may wish to check versions of files and only install updated files, or perhaps you wish to apply patches to existing files. the install script is even flexible enough to allow you to uninstall files. for this reason, installers include an install script to handle the installation process. the installer script must be called install.js and must be placed at the top level of the installer archive. the script will contain javascript code which calls a number of install functions. in an html document, or a xul document, the window object is the root global object. that mea...
...bal object. that means that you can call the methods of the window object with the qualifier before it, which means that window.open() can simply be written open(). in an install script, there is no associated window, however the global object will be an install object which contains a number of functions to customize the install process. some of the install object's functions will be described below. the install script should take the following steps: initialize the installation by specifying what package and version is being installed. use the install functions to indicate what files and directories need to be installed. you can also set files to be moved and deleted. start the process of installing the necessary files. it is important to note that during step two, you only indicate...
...s unless you are creating your own xpcom components. what you do need to know for an installation is that the registry stores a set of information about your application, such as the file list and versions. all of this information is stored in a key (and within subkeys) that you provide in the installation script (in step 1 mentioned above). this key is structured as directory-like path of the following form: /author/package name replace the word author with your name and replace the package name with the name of the package that you are installing. for example: /xulplanet/find files /netscape/personal security manager the first example is what we'll use for the find files dialog. the second is the key used for the personal security manager. install initialization the install object has a ...
...And 3 more matches
More Event Handlers - Archive of obsolete content
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 button or checkbox, that was activated. example 1 : source view <vbox oncommand="alert(event.currenttarget.tagname);"> <button label="ok"/> <checkbox label="show images"/> </vbox> stop event propagation once you handle an event, regardless of where in the propagation the event is, you will likely want...
... that the capturing phase occurs before the bubbling phase, so any capturing listeners will trigger before any bubbling listeners. if a capturing event stops the event propagation, none of the later capturing listeners, nor any of the bubbling listeners will ever receive notification about the events. to manually stop event propagation, call the event object's stoppropagation method, as in the following example. example 2 : source view <hbox id="outerbox"> <button id="okbutton" label="ok"/> </hbox> <script> function buttonpressed(event){ alert('button was pressed!'); } function boxpressed(event){ alert('box was pressed!'); event.stoppropagation(); } var button = document.getelementbyid("okbutton"); button.addeventlistener('command',buttonpressed,true); var outerbox = document.gete...
...handle the event in a default way. what will happen depends on the event and the type of element. for example, the 'popupshowing' event is sent to a popup just before it is displayed. the default action is to display the popup. if the default action is prevented, the popup will not be displayed. the default action can be prevented with the event object's preventdefault method, as in the example below. example 3 : source view <button label="types" type="menu"> <menupopup onpopupshowing="event.preventdefault();"> <menuitem label="glass"/> <menuitem label="plastic"/> </menupopup> </button> alternatively, for attribute event listeners, you can just return false from the code. note that preventing the default action is not the same as stopping event propagation with the stoppropagatio...
...And 3 more matches
Splitters - Archive of obsolete content
have two sections of a window where the user can resize the sections. an example is the mozilla browser window, where you can change the size of the sidebar panel by dragging the bar in-between the two frames. you can also hide the sidebar by clicking the notch. splitter element this feature is accomplished using an element called a splitter. it creates a skinny bar between two sections which allows these sections to be resized. you can place a splitter anywhere you want and it will allow resizing of the elements that come before it and the elements that come after it in the same box. when a splitter is placed inside a horizontal box, it will allow resizing horizontally. when a splitter is placed inside a vertical box, it will allow resizing vertically. the syntax of a splitter is as foll...
... state indicates the state of the splitter. set this to open, the default, to have the split panel initially open, or set it to collapsed to have one of the panels shrunk down (collapsed) and the other occupying all of the space. ...
...ve) resize. this attribute indicates which element should resize. set this to closest to have the element immediately to the left of the splitter resize. set this to farthest to have the element that is the farthest away from the splitter to the left resize. (the first element in the box). the default value is closest. resizeafter when the splitter is dragged, the elements to the right (or below) resize. this attribute indicates which element should resize. set this to closest to have the element immediately to the right of the splitter resize. set this to farthest to have the element that is the farthest away from the splitter to the right resize. (the last element in the box). this attribute can also be set to grow, in which case the elements to the right of the splitter do not change ...
...And 3 more matches
XPCOM Examples - Archive of obsolete content
t » this section provides some examples of using xpcom along with some additional interfaces. window management this example contains rdf datasource that will be seen in the later section. you might skip this example for the time being, except when you have already had that knowledge. creating a window menu the list of currently open mozilla windows can be used as an rdf datasource. ...
... in the later section. you might skip this example for the time being, except when you have already had that knowledge. creating a window menu the list of currently open mozilla windows can be used as an rdf datasource. this allows you to create a window menu with a list of the currently open windows in the application. the datasource for this is rdf:window-mediator. ...
...this example by opening a number of browser windows and you'll see that they are all listed on the menu. window mediator component this is fine for displaying a list of open windows, but we would like to enhance this so that clicking on the menu item will switch to that window. this is accomplished by using the window mediator component. it implements the interface nsiwindowdatasource. the code below shows how to get a component which implements it: var wmdata = components.classes["@mozilla.org/rdf/datasource;1?name=window-mediator"].getservice(); wmdata.queryinterface(components.interfaces.nsiwindowdatasource); this code retrieves a window mediator data source component. the component used here is the same one that handles the window-mediator rdf datasource. you can also get this component ...
...And 3 more matches
Using the Editor from XUL - Archive of obsolete content
hat causes the editoronload() javascript function to get executed when the xul is done loading. the xul contains an <editor> tag, e.g.: <editor type="content-primary" id="content-frame" src="about:blank" flex="1"/> the attribute type="content-primary" identifies this as the window content element, i.e. that which you get from window._content. having an id attribute, id="content-frame", allows us to find this element with document.getelementbyid("content-frame"), and to style it from css. editoronload() is called. it does some getting of window.arguments (which is a way callers can pass parameters to new windows -- we use this to get the url to be loaded), then it calls editorstartup(), where the real work happens. it passes two parameters; the first indicates whether we want...
.... note: these callbacks also fire for every subdocument that loads as a result of the parent document load, for example with frameset documents, or html documents with their own embedded <iframe>s. in this case, we need to be careful to instantiate the editor on the correct document. we are currently only able to have one editor per composer window; in future, relaxing this restriction would allow us to edit all the subdocuments in a frameset at the same time. we detect that the document we want to edit has loaded successfully in nseditorshell::onenddocumentload(). after checking that we can actually edit this document, we go ahead and instantiate an editor on it (in nseditorshell::preparedocumentforediting()). as well as making the editor (which happens via nseditorshell::doeditormo...
...ia nseditorshell::doeditormode()) we also hook up various listeners and observers for ui updating and user interaction, and store a file specifier for the document we opened. the editor is now set up, and ready to go. one thing to note about editor initialization is that we pass into the editor's init() method an nsicontent* that corresponds to the root of the content tree that the editor is allowed to work with. when initializing the editor from the nseditorshell, we pass null here (which tells the editor that it can edit everything under the <body> of the document). this parameter is more important when the editor is in a text widget, where it points to the the subtree of the parent document that corresponds to widget content. editor teardown window destruction, and hence editor tea...
...And 3 more matches
XUL controls - Archive of obsolete content
for a step-by-step guide on how to use these controls, see the xul tutorial. for more reference information, see the xul reference. <button> a button that can be pressed by the user. <button label="save" accesskey="s"/> more information about the button element. button reference <button type="menu"> a button that has a drop down menu attached to it. pressing the button opens the menu. <button type="menu" label="view"> <menupopup> <menuitem label="list"/> <menuitem label="details"/> </menupopup> </button> more information about this type of menu button element. ...
...icker color="#ff0000"/> colorpicker reference <colorpicker type="button"> a specialized type of color picker which shows only a button. pressing the button displays a color picker popup window. <colorpicker type="button" color="#cc0080"/> colorpicker reference <datepicker> a set of textboxes which may be used to allow the entry of a date. <datepicker value="2007/03/26"/> datepicker reference <datepicker type="grid"> a datepicker which displays a calendar grid for selecting a date. <datepicker type="grid" value="2007/02/20"/> datepicker reference <datepicker type="popup" > a datepicker which displays a set of textboxes f...
... more information about the description element. description reference <groupbox> a groupbox displays a labelled box around other user interface controls. <groupbox> <caption label="network"/> </groupbox> more information about the groupbox element. groupbox reference related elements: caption <filefield> allows the user to select a file. <filefield/> filefield reference <image> an image specified by a url. <image src="start.png"/> more information about the image element. image reference <label> adds a text label to a nearby control. <label control="volume" value="volume:"/> more information ...
...And 3 more matches
iframe - Archive of obsolete content
.value; // note the firstchild is the menupopup element document.getelementbyid('myframe').setattribute('src', url); } </script> attributes showcaret type: boolean whether or not to cause a typing caret to be visible in the content area. default is false. src type: uri the uri of the content to appear in the element. type type: one of the values below. the type of browser, which can be used to set access of the document loaded inside the browser. if this is not set, the loaded document has the same access as the window containing the browser. more precisely: the document loaded into a chrome window is always of chrome type. subdocuments of chrome documents are of chrome type, unless the container element (one of iframe, browser or editor) has...
..., and preventing documents from inheriting the principal of the parent document. the type attribute on all frames in content documents is ignored; subdocuments of content documents are always content documents. warning: the type attribute must be set before the element is inserted into the document. content a browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. content-primary the primary browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. for instance, in a web browser, this would be the element that displays the web page. the window for the primary content can be retrieved more conveniently using window.content. content-targetable one browser among ma...
...this is the preferred value for any browser element in an application, which will use multiple browsers of equal privileges, and is unselected at the moment. chrome (default behaviour): a browser, intended to be used for loading privileged content using a chrome:// uri. ...
...And 3 more matches
menu - Archive of obsolete content
Archive › Mozilla › XUL › menu
« xul reference home [ examples | attributes | properties | methods | related ] an element, much like a button, that is placed on a menubar. when the user clicks the menu element, the child menupopup of the menu will be displayed. this element is also used to create submenus. more information is available in the xul tutorial. ...
...key (accelerator key) to use to invoke the command. if this value is set, it overrides an assigned key set in the key attribute. this attribute does not apply to menus directly on the menubar. 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. allowevents type: boolean if true, events are passed to children of the element. otherwise, events are passed to the element only. 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 dire...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (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; } disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is disabled. disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, an...
...And 3 more matches
menuseparator - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] used to create a separator between menu items. typically drawn as a thin line. more information is available in the xul tutorial. ...
...y (accelerator key) to use to invoke the command. if this value is set, it overrides an assigned key set in the key attribute. this attribute does not apply to menus directly on the menubar. 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. ...
...an ellipsis will be used in place of the cropped text. if the box direction is reversed, the cropping is reversed. ...
...And 3 more matches
notificationbox - Archive of obsolete content
| properties | methods | related ] the notificationbox element is used to display notifications above an element. typically the element will be a browser, but any element may be used. the notification element is used for each notification, and will be created automatically for each item. each notification will slide in and out as needed. this element is used, for example, to implement the yellow information bar in various firefox windows. the notification box is a vertical box which may have children. the notifications appear at the top of the box. the notifications may be placed at the bottom by setting the dir attribute to reverse. finding the current notification box within a firefox extension, you can retrieve the current notification box for a specific tab by calling the global...
...mozilla.org"/> </notificationbox> there is a more complex code available in the code snippets area. ...
...> </notificationbox> there is a more complex code available in the code snippets area. ...
...And 3 more matches
scale - Archive of obsolete content
Archive › Mozilla › XUL › scale
set the orient attribute to vertical to use a vertical scale. ...
...set the orient attribute to vertical to use a vertical scale. ...
...set the orient attribute to vertical to use a vertical scale. ...
...And 3 more matches
XULRunner 2.0 Release Notes - Archive of obsolete content
mac os x, and linux, in english. the releases directory can be found here. specific runtimes can be found at: download xulrunner for windows download xulrunner for mac os x download xulrunner for 32-bit linux download xulrunner for 64-bit linux (warning: links may become out-of-date at times). windows unpack the zip file to a new directory using an archive tool (7zip is recommended). the following directory is recommended: c:\program files\mozilla xulrunner\2.0 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. xulrunner 2.0 is a universal binary containing i386 and ...
...-register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. xulrunner 2.0 is a universal binary containing i386 and x86_64 architectures. xulrunner 1.9.2 and earlier versions had powerpc (ppc) and i386 architectures. linux (32-bit) unpack the tarball to a new directory using tar -xjf xulrunner-2.0.en-us.linux-i686.tar.bz2. the following directory is recommended: /opt/xulrunner/2.0 . register xulrunner with the system by running xulrunner --register-global (to install for all users, must be run as root) or xulrunner --register-user (to install for one user only). ...
...register xulrunner with the system by running xulrunner --register-global (to install for all users, must be run as root) or xulrunner --register-user (to install for one user only). ...
...And 3 more matches
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
this is by far the simplest approach. in some cases, however, you may want to use the mozilla build system to create your application. the only obvious reason for this would be if you need to implement part of your application in c++, as described in the introduction to the now classic creating custom firefox extensions with the mozilla build system. for the purposes of this article i'm using dave townsend's mccoy as an example. it's a straightforward xulrunner app that nonetheless uses most of the features any given application is likely to need. ...
...rm fuzzy feeling from mastering the complex but very powerful mozilla build system. and all that furniture you smash in the meantime makes great kindling to get you through those cold winter nights. let's face it, it was probably time for you to get some new furniture anyway. everything you ever wanted to know about building mozilla (and thus xulrunner) can be found in the build documentation. follow the instructions for meeting build requirements and getting the source, then come back here since the build process itself will be slightly different. got source? now you need to set up a special .mozconfig file to tell mozilla to build both xulrunner and your application. here's a sample .mozconfig for building xulrunner and mccoy: # options for client.mk. mk_add_options moz_build_projects="xulr...
... creating a debug build, so you'd have to change the relevant options if you want a release build instead. you can find out more about which options to use in configuring build options. the third section contains options for building xulrunner. you shouldn't have to change this. finally, the final section contains options specific to your application. make sure you change the application name (following ac_add_app_options to that of your app. do the same with the name that follows --enable-application. you shouldn't have to change the value of --with-libxul-sdk if you are building your own xulrunner. you can also add other options to this section if you want them to apply to your app only. building your application if you decided that you needed a custom-built xulrunner and read the previous ...
...And 3 more matches
Debugging a XULRunner Application - Archive of obsolete content
the easiest way to debug a xulrunner application is to get the system to tell you what's wrong! there are two different consoles available and various preferences which will ensure that the information you need to know is displayed on them. see also debugging javascript prefs setting the following prefs will make your debugging life much easier! preferences should be in a .js file in the directory %appname%/defaults/preferences/. it doesn't matter what the file is called (as long as the extension is .js), so debug.js is as good as any! /* debugging prefs */ pref("browser.dom.window.dump.enabled", true); pref("javascript.options.showinconsole", true); pref("javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload...
...environment variable xre_console_log to the path to the filename. i.e. export xre_console_log=/path/to/logfile or set xre_console_log=c:\path\to\logfile. to output messages to the javascript console there are two ways to output messages to the js console: components.utils.reporterror(str) will output str as an "error" (i.e. with the red stop icon next to it). jsdump(str) (function defined below) will output str as a "message" with a speech bubble icon next to it: function jsdump(str) { components.classes['@mozilla.org/consoleservice;1'] .getservice(components.interfaces.nsiconsoleservice) .logstringmessage(str); } for more information about the error console see the error console and browser console article. browser debugger as of gecko 44, it is no long...
...erfaces.nsiconsoleservice) .logstringmessage(str); } for more information about the error console see the error console and browser console article. browser debugger as of gecko 44, it is no longer possible to start the devtools server from xul apps. see bug 1244163. starting with xulrunner 24, you should use the firefox browser debugger to debug your xulrunner apps. add the following code to your xul app: components.utils.import('resource://gre/modules/devtools/dbg-server.jsm'); if (!debuggerserver.initialized) { debuggerserver.init(); // don't specify a window type parameter below if "navigator:browser" // is suitable for your app. debuggerserver.addbrowseractors("myxulrunnerappwindowtype"); } debuggerserver.openlistener(6000); for xulrunner version 37+ the cod...
...And 3 more matches
Archive of obsolete content
ve it here. in general, it may be best to discuss it in the mdn web docs room on matrix before moving content here. .htaccess ( hypertext access ) file accessing : htaccess files can be opened using any text editor, like windows notepad, vin, sublime text editor or any other. syntax highliting support for .htaccess files less. 2015 mdn fellowship program add-ons archived add-ons documentation. adding preferences to an extension this article takes the creating a dynamic status bar extension sample to the next level, adding a popup menu that lets you quickly switch between multiple stocks to watch. it also adds a preference dialog that lets you switch to a stock other than one ...
...erface conventions we've come to expect from web pages. api archived documentation about obsolete web standards apis. archived mozilla and build documentation these articles are archived, obsolete documents about mozilla, gecko, and the process of building mozilla projects. archived open web documentation the documentation listed below is archived, obsolete material about open web topics. beginner tutorials this page includes archived beginners tutorials, from various places around mdn. case sensitivity in class and id names creating a dynamic status bar extension concepts covered in the previous sample won't be reiterated here; instead, refer to the downloadable sample code or t...
...his conversion, but some conventions begin to appear on the web. 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. list of former mozilla-based applications the following is a list of all known applications that at one point used mozilla technologies or that are no longer being actively maintained. list of mozilla-based applications the following is a list of all known active applications that are built using mozilla technologies. this list is likely to be incomplete since we think there are many dark matter projects ...
...And 3 more matches
Index - Game development
avascript, 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 have a whole lot of options to chose from with most of them being free, so it's only about your enthusiasm and available time. sometimes you have to spend more time promoting a game than actually developing it. remember that it's no use to have t...
...g no rotation. the algorithm works by ensuring there is no gap between any of the 4 sides of the rectangles. any gap means a collision does not exist. 13 3d collision detection 3d, games, javascript, bounding boxes, collision detection 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. 14 bounding volume collision detection with three.js 3d, games, javascript, webgl, bounding boxes, collision detection, three.js this article shows how to implement collision detection between bounding boxes and spheres using the three.js library. it is assumed that before reading this you have read our 3d collis...
...that is hardware accelerated. 16 building up a basic demo with a-frame 3d, a-frame, vr, virtual reality, web, webgl the webxr and webgl apis already enable us to start creating virtual reality (vr) experiences inside web browsers, but the community is still waiting for tools and libraries to appear, to make this easier. mozilla's a-frame framework provides a markup language allowing us to build 3d vr landscapes using a system familiar to web developers, which follows game development coding principles; this is useful for quickly and successfully building prototypes and demos, without having to write a lot of javascript or glsl. this article explains how to get up and running with a-frame, and how to use it to build up a simple demo. 17 building up a basic demo ...
...And 3 more matches
Building up a basic demo with PlayCanvas editor - Game development
this by giving it an x position value of -2. adding other shapes involves a very similar process to adding the box. click on the root folder in the hierarchy panel (to make sure that the new shape appears in the root, and not as a child of the box) then click on the big add entity (plus) button and select cylinder from the dropdown list — it will add a new cylinder shape to the scene. now follow the same steps as we did before when coloring the cube: create a new material using the add asset (plus) button. make sure the new material in the assets panel is selected, to bring up the entity inspector. give the material a new name, along the lines of cylindermaterial. click diffuse, then click the color picker — give it an orange color (we used ff9500.) drag and drop the cylindermat...
...ial using the add asset (plus) button. make sure the new material in the assets panel is selected, to bring up the entity inspector. give the material a new name, along the lines of cylindermaterial. click diffuse, then click the color picker — give it an orange color (we used ff9500.) drag and drop the cylindermaterial icon onto the cylinder object on the sceene to apply that color. follow the same approach again to add a cone to the scene, giving it a grayish color (we used eaeff2.) you should now have three shapes on your scene, something like the below screenshot. animating our scene animating 3d models might be considered an advanced thing to do, but all we want to do is to control a few properties of a given object — we can use a script component to do that. click on the...
...ed once after all resources are loaded and before the first update initialize: function () { }, // called every frame, dt is time in seconds since last update update: function (dt) { } }; return boxanimation; }); the most interesting part is the update() function, which is where we can put any code that we want repeated on every frame. add the following line inside this function, to rotate the cube on every frame: this.entity.rotate(dt*10, dt*20, dt*30); in the line above this.entity refers to the object to which the script will be attached (the box); using the dt variable, which contains the delta time passed since the previous frame, we can rotate the box by a different amount around all three axes. save the changes using the save butt...
...And 3 more matches
Tiles and tilemaps overview - Game development
about any game that uses regularly repeating squares of background, and you'll probably find it uses tilemaps. the tile atlas the most efficient way to store the tile images is in an atlas or spritesheet. this is simply all of the required tiles grouped together in a single image file. when it's time to draw a tile, only a small section of this bigger image is rendered on the game canvas. the below images shows a tile atlas of 8 x 4 tiles: using an atlas also has the advantage of naturally assigning every tile an index. this index is perfect to use as the tile identifier when creating the tilemap object. the tilemap data structure it is common to group all the information needed to handle tilemaps into the same data structure or object. these data objects (map object example) should in...
...e a collision grid, a path-finding grid, etc., depending on the type of game. note: for the visual grid, a special value (usually a negative number, 0 or null) is needed to represent empty tiles. square tiles square-based tilemaps are the most simple implementation. a more generic case would be rectangular-based tilemaps — instead of square — but they are far less common. square tiles allow for two perspectives: top-down (like many rpg's or strategy games like warcraft 2 or final fantasy's world view.) side-view (like platformers such as super mario bros.) static tilemaps a tilemap can either fit into the visible screen area screen or be larger. in the first case, the tilemap is static — it doesn't need to be scrolled to be fully shown. this case is very common in arcade ga...
... for (var row = 0; row < map.rows; row++) { var tile = map.gettile(column, row); var x = column * map.tilesize; var y = row * map.tilesize; drawtile(tile, x, y); } } you can read more about this and see an example implementation in square tilemaps implementation: static maps. scrolling tilemaps scrolling tilemaps only show a small portion of the world at a time. they can follow a character — like in platformers or rpgs — or allow the player to control the camera — like in strategy or simulation games. positioning and camera in all scrolling games, we need a translation between world coordinates (the position where sprites or other elements are located in the level or game world) and screen coordinates (the actual position where those elements are rendered on the...
...And 3 more matches
Collision detection - Game development
n detection: function collisiondetection() { for(var c=0; c<brickcolumncount; c++) { for(var r=0; r<brickrowcount; r++) { var b = bricks[c][r]; // calculations } } } if the center of the ball is inside the coordinates of one of our bricks, we'll change the direction of the ball. for the center of the ball to be inside the brick, all four of the following statements need to be true: the x position of the ball is greater than the x position of the brick. the x position of the ball is less than the x position of the brick plus its width. the y position of the ball is greater than the y position of the brick. the y position of the ball is less than the y position of the brick plus its height. let's write that down in code: function collis...
...ion of the brick plus its height. let's write that down in code: function collisiondetection() { for(var c=0; c<brickcolumncount; c++) { for(var r=0; r<brickrowcount; r++) { var b = bricks[c][r]; if(x > b.x && x < b.x+brickwidth && y > b.y && y < b.y+brickheight) { dy = -dy; } } } } add the above block to your code, below the keyuphandler() function. making the bricks disappear after they are hit the above code will work as desired and the ball changes its direction. the problem is that the bricks are staying where they are. we have to figure out a way to get rid of the ones we've already hit with the ball. we can do that by adding an extra parameter to indicate whether we want to paint each brick on the screen ...
...changes its direction. the problem is that the bricks are staying where they are. we have to figure out a way to get rid of the ones we've already hit with the ball. we can do that by adding an extra parameter to indicate whether we want to paint each brick on the screen or not. in the part of the code where we initialize the bricks, let's add a status property to each brick object. ...
...And 3 more matches
Finishing up - Game development
make a mistake or two and still be able to finish the game. we could also improve our code rendering. giving the player some lives implementing lives is quite straightforward. let's first add a variable to store the number of lives in the same place where we declared our other variables: var lives = 3; drawing the life counter looks almost the same as drawing the score counter — add the following function to your code, below the drawscore() function: function drawlives() { ctx.font = "16px arial"; ctx.fillstyle = "#0095dd"; ctx.filltext("lives: "+lives, canvas.width-65, 20); } instead of ending the game immediately, we will decrease the number of lives until they are no longer available. we can also reset the ball and the paddle positions when the player begins with their...
...ion: function drawlives() { ctx.font = "16px arial"; ctx.fillstyle = "#0095dd"; ctx.filltext("lives: "+lives, canvas.width-65, 20); } instead of ending the game immediately, we will decrease the number of lives until they are no longer available. we can also reset the ball and the paddle positions when the player begins with their next life. ...
...ease the number of lives until they are no longer available. we can also reset the ball and the paddle positions when the player begins with their next life. so, in the draw() function replace the following three lines: alert("game over"); document.location.reload(); clearinterval(interval); // needed for chrome to end game with this, we can add slightly more complex logic to it as given below: lives--; if(!lives) { alert("game over"); document.location.reload(); clearinterval(interval); // needed for chrome to end game } else { x = canvas.width/2; y = canvas.height-30; dx = 2; dy = -2; paddlex = (canvas.width-paddlewidth)/2; } now, when the ball hits the bottom edge of the screen, we're subtracting one life from the lives variable. if there are no liv...
...And 3 more matches
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
xml inclusions (xinclude) is a w3c recommendation to allow inclusion of xml more different sources in a more convenient fashion than xml external entities. when used in conjunction with xpointer (firefox supports a subset of it, and is used in the code sample below), xinclude can also target just specific portions of a document for inclusion. firefox does not support it natively, but the following function aims to allow its use with documents passed into it. code sample the following code aims to let <xi:include> and <xi:fallback> tags (the two elements in the language) with all of the attributes of <xi:include> be included in an xml document so as to be resolvable into a single xml document. (note that this has not been thoroughly tested for all circumstances and may not necessari...
...e the following code aims to let <xi:include> and <xi:fallback> tags (the two elements in the language) with all of the attributes of <xi:include> be included in an xml document so as to be resolvable into a single xml document. (note that this has not been thoroughly tested for all circumstances and may not necessarily reflect the standard behavior completely.) note also that if you wish to allow xml:base, you will need the xml:base function, and the line beginning var href = ... should become: var href = getxmlbaselink (/* xlink sans xml:base */ xinclude.getattribute('href'), /* element to query from */ xinclude); function resolvexincludes(docu) { // http://www.w3.org/tr/xinclude/#xml-included-items var xincludes = docu.getelementsbytagnamens('http://www.w3.org/2001/xinclude', ...
...n/xml or matches text/*+xml or application/*+xml" before encoding (then utf-8) var accept = xinclude.getattribute('accept'); // header "accept: "+x var acceptlanguage = xinclude.getattribute('accept-language'); // "accept-language: "+x var xifallback = xinclude.getelementsbytagnamens('http://www.w3.org/2001/xinclude', 'fallback')[0]; // only one such child is allowed if (href === '' || href === null) { // points to same document if empty (null is equivalent to empty string) href = null; // set for uniformity in testing below if (parse === 'xml' && xpointer === null) { alert('there must be an xpointer attribute present if "href" is empty an parse is "xml"'); return false; ...
...And 3 more matches
Debugging CSS - Learn web development
l become most familiar with the tools included in that browser, it is worth knowing how to access them in other browsers. this will help if you are seeing different rendering between multiple browsers. you will also find that browsers have chosen to focus on different areas when creating their devtools. for example in firefox there are some excellent tools for working visually with css layout, allowing you to inspect and edit grid layouts, flexbox, and shapes. however, all of the different browsers have similar fundamental tools, e.g. for inspecting the properties and values applied to elements on your page, and making changes to them from the editor. in this lesson we will look at some useful features of the firefox devtools for working with css. in order to do so i'll be using an example ...
... and shapes. however, all of the different browsers have similar fundamental tools, e.g. for inspecting the properties and values applied to elements on your page, and making changes to them from the editor. in this lesson we will look at some useful features of the firefox devtools for working with css. in order to do so i'll be using an example file. load this up in a new tab if you want to follow along, and open up your devtools as described in the article linked above. the dom versus view source something that can trip up newcomers to devtools is the difference between what you see when you view the source of a webpage, or look at the html file you put on the server, and what you can see in the html pane of the devtools. while it looks roughly similar to what you can see via view sourc...
...e — if you hold your mouse over it checkboxes will appear. uncheck a rule's checkbox, for example border-radius, and the css will stop applying. you can use this to do an a/b comparison, deciding if something looks better with a rule applied or not, and also to help debug it — for example if a layout is going wrong and you are trying to work out which property is causing the problem. the following video provides some useful tips on debugging css using the firefox devtools: editing values in addition to turning properties on and off, you can edit their values. perhaps you want to see if another color looks better, or wish to tweak the size of something? devtools can save you a lot of time editing a stylesheet and reloading the page. with box1 selected, click on the swatch (the small...
...And 3 more matches
Pseudo-classes and pseudo-elements - Learn web development
down on excess classes in your markup, and giving you more flexible, maintainable code. pseudo-classes are keywords that start with a colon: :pseudo-class-name simple pseudo-class example let's look at a simple example. if we wanted to make the first paragraph in an article larger and bold, we could add a class to that paragraph and then add css to that class, as shown in the first example below: however, this could be annoying to maintain — what if a new paragraph got added to the top of the document? we'd need to move the class over to the new paragraph. instead of adding the class, we could use the :first-child pseudo-class selector — this will always target the first child element in the article, and we will no longer need to edit the html (this may not always be possible anyw...
...ically wrapped around that first formatted line, and updated each time the line length changed. you can see that this selects the first line of both paragraphs. combining pseudo-classes and pseudo-elements if you wanted to make the first line of the first paragraph bold you could chain the :first-child and ::first-line selectors together. try editing the previous live example so it uses the following css. we are saying that we want to select the first line, of the first <p> element, which is inside an <article> element. article p:first-child::first-line { font-size: 120%; font-weight: bold; } generating content with ::before and ::after there are a couple of special pseudo-elements, which are used along with the content property to insert content into your document using css. you c...
...t <p> element, which is inside an <article> element. article p:first-child::first-line { font-size: 120%; font-weight: bold; } generating content with ::before and ::after there are a couple of special pseudo-elements, which are used along with the content property to insert content into your document using css. you could use these to insert a string of text, such as in the live example below. try changing the text value of the content property and see it change in the output. you could also change the ::before pseudo-element to ::after and see the text inserted at the end of the element instead of the beginning. inserting strings of text from css isn't really something we do very often on the web however, as that text is inaccessible to some screen readers and might be hard for so...
...And 3 more matches
CSS selectors - Learn web development
in this article and its sub-articles we'll run through the different types in great detail, seeing how they work. ...
... .special, i could write this as two separate rules. h1 { color: blue; } .special { color: blue; } i could also combine these into a selector list, by adding a comma between them. h1, .special { color: blue; } white space is valid before or after the comma. you may also find the selectors more readable if each is on a new line. h1, .special { color: blue; } in the live example below try combining the two selectors which have identical declarations. the visual display should be the same after combining them. when you group selectors in this way, if any selector is invalid the whole rule will be ignored. in the following example, the invalid class selector rule will be ignored, whereas the h1 would still be styled. h1 { color: blue; } ..special { color: blue; } wh...
... includes pseudo-classes, which style certain states of an element. the :hover pseudo-class for example selects an element only when it is being hovered over by the mouse pointer: a:hover { } it also includes pseudo-elements, which select a certain part of an element rather than the element itself. ...
...And 3 more matches
Test your skills: floats - Learn web development
the aim of this task is to get you working with the css float and clear properties covered in our lesson on floats. you will be working through three small tasks which use different elements of the material you have just covered. note: you can try out solutions in the interactive 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. ...
...he 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. floats one in this task you need to float the two elements with a class of float1 and float2 left and right respectively. the text should then appear between the two boxes as in the image below. ...
...s 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. floats one in this task you need to float the two elements with a class of float1 and float2 left and right respectively. the text should then appear between the two boxes as in the image below. ...
...And 3 more matches
How CSS works - Learn web development
y introduction 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...
...on. based on the selectors it finds, it works out which rules should be applied to which nodes in the dom, and attaches style to them as required (this intermediate step is called a render tree). the render tree is laid out in the structure it should appear in after the rules have been applied to it. the visual display of the page is shown on the screen (this stage is called painting). the following diagram also offers a simple view of the process. about the dom a dom has a tree-like structure. each element, attribute, and piece of text in the markup language becomes a dom node in the tree structure. the nodes are defined by their relationship to other dom nodes. some elements are parents of child nodes, and child nodes have siblings. understanding the dom helps you design, debug and...
... design, debug and maintain your css because the dom is where your css and the document's content meet up. when you start working with browser devtools you will be navigating the dom as you select items in order to see which rules apply. a real dom representation rather than a long, boring explanation, let's look at an example to see how a real html snippet is converted into a dom. take the following html code: <p> let's use: <span>cascading</span> <span>style</span> <span>sheets</span> </p> in the dom, the node corresponding to our <p> element is a parent. its children are a text node and the three nodes corresponding to our <span> elements. the span nodes are also parents, with text nodes as their children: p ├─ "let's use:" ├─ span | └─ "cascading" ├─ span |...
...And 3 more matches
How do I use GitHub Pages? - Learn web development
github is a "social coding" site. it allows you to upload code repositories for storage in the git version control system. you can then collaborate on code projects, and the system is open-source by default, meaning that anyone in the world can find your github code, use it, learn from it, and improve on it. you can do that with other people's code too! this article provides a basic guide to publishing content using github's gh-pages feature. publishing content github is a very important and useful community to get involved in, and git/github is a very popular version control system — most tech companies now use it in their workflow. github has a very useful feature called github pages, which allows you to publish website code live on the web. basic github setup first of all, ...
...epository. to do this: point the command line to your test-site directory (or whatever you called the directory containing your website). for this, use the cd command (i.e. "change directory"). here's what you'd type if you've put your website in a directory called test-site on your desktop: cd desktop/test-site when the command line is pointing inside your website directory, type the following command, which tells the git tool to turn the directory into a git repository: git init an aside on command line interfaces the best way to upload your code to github is via the command line — this is a window where you type in commands to do things like create files and run programs, rather than clicking inside a user interface. it will look something like this: note: you could a...
...ing a git graphical user interface to do 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 e...
...And 3 more matches
Example 1 - Learn web development
padding : 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */ width : 10em; /* 100px */ border : 0.2em solid #000; /* 2px */ border-radius : 0.4em; /* 4px */ box-shadow : 0 0.1em 0.2em rgba(0,0,0,.45); /* 0 1px 2px */ background : #f0f0f0; background : linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display : inline-block; width : 100%; overflow : hidden; white-space : nowrap; text-overflow : ellipsis; vertical-align: top; } .select:after { content : "▼"; position: absolute; z-index : 1; height : 100%; width : 2em; /* 20px */ top : 0; right : 0; padding-top : .1em; -moz-box-sizing : border-box; box-sizing : border-box; text-align : center; border-left : .2em solid #000; border-radius: 0...
...order-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">lemon</li> <li class="option">banana</li> <li class="...
...padding : 0.1em 2.5em 0.2em 0.5em; /* 1px 25px 2px 5px */ width : 10em; /* 100px */ border : 0.2em solid #000; /* 2px */ border-radius : 0.4em; /* 4px */ box-shadow : 0 0.1em 0.2em rgba(0,0,0,.45); /* 0 1px 2px */ background : #f0f0f0; background : linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display : inline-block; width : 100%; overflow : hidden; white-space : nowrap; text-overflow : ellipsis; vertical-align: top; } .select:after { content : "▼"; position: absolute; z-index : 1; height : 100%; width : 2em; /* 20px */ top : 0; right : 0; padding-top : .1em; -moz-box-sizing : border-box; box-sizing : border-box; text-align : center; border-left : .2em solid #000; border-radius: 0...
...And 3 more matches
Tips for authoring fast-loading HTML pages - Learn web development
inimal 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 been modified since the last time it was downloaded. too much time spent querying the l...
...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 modified. most web servers automatically append the last-modified header to static pages (e.g. .html, .css), based on the last-modified date stored in the file system. with dynamic pages (e.g. .php, .aspx), this, of course, can't be done, and th...
...f modern css reduces the amount of markup, can reduce the need for (spacer) images, in terms of layout, and can very often replace images of stylized text -- that "cost" much more than the equivalent text-and-css. using valid markup has other advantages. first, browsers will have no need to perform error-correction when parsing the html (this is aside from the philosophical issue of whether to allow format variation in user input and then programmatically "correct" or normalize it; or whether, instead, to enforce a strict, no-tolerance input format). moreover, valid markup allows for the free use of other tools which can pre-process your web pages. for example, html tidy can remove whitespace and optional ending tags; however, it will refuse to run on a page with serious markup errors. chu...
...And 3 more matches
Test your skills: Conditionals - Learn web development
the aim of this skill test is to assess whether you've understood our making decisions in your code — conditionals article. note: you can try out solutions in the interactive 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. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). conditionals 1 in this task you are provided with two variables: season — contains a string that says wha...
...r", and if so assigns a string to response that gives the user an appropriate message about the season. if not, it should assign a generic string to response that tells the user we don't know what season it is. to finish off, you should then add another test that checks whether season contains the string "winter", and again assigns an appropriate string to response. 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. conditionals 2 for this task you are given three variables: machineactive — contains an indicator of whether the answer machine is switched on or not (true/false) score — contains your score in an imaginary game. this score is fed into the answer machine, w...
...ecks whether the machine is switched on and puts a message into the response variable if it isn't, telling the user to switch the machine on. inside the first, you need to nest an if...else if...else that puts appropriate messages into the response variable depending on what the value of score is — if the machine is turned on. the different conditional tests (and resulting responses) are as follows: score of less than 0 or more than 100 — "this is not possible, an error has occurred." score of 0 to 19 — "that was a terrible score — total fail!" score of 20 to 39 — "you know some things, but it's a pretty bad score. needs improvement." score of 40 to 69 — "you did a passable job, not bad!" score of 70 to 89 — "that\'s a great score, you really know your stuff." score of ...
...And 3 more matches
Test your skills: Events - Learn web development
this aim of this skill test is to assess whether you've understood our introduction to events article. note: you can try out solutions in the interactive 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. ...
...ther you've understood our introduction to events article. note: you can try out solutions in the interactive 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. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). ...
... us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript. we haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into wh...
...And 3 more matches
Test your skills: Functions - Learn web development
this aim of this skill test is to assess whether you've understood our functions — reusable blocks of code, build your own function, and function return values articles. note: you can try out solutions in the interactive 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. ...
...ld your own function, and function return values articles. note: you can try out solutions in the interactive 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. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). ...
... us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript. we haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into wh...
...And 3 more matches
Accessibility/LiveRegionDevGuide
s. 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 specification. the later method will be explained in detail below. event types the table for web page mutation event types lists the two major event types associated with live regions, namely text-changed and object changed events. both will be discussed in detail below. object changed the object changed events are slightly different in at-spi and iaccessible2. in at-spi, the object changed event are called object:children-changed events because the even...
...anged 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 significant difference between at-spi and iaccessible2 is that at-spi is an inter-process communication service while iaccessible2 runs in process. as ...
...ased 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 potential filtering techniques: the "event-from-input" object attribute can be used to filter events that were triggered by user action. the ":system" (or lack thereof) can be used to filter events that are system generated. (at-spi only) a global variable can be set in a document:load:complete event listener and reset in a object:state-changed:busy listener. this variable can...
...And 3 more matches
Creating a spell check dictionary add-on
this page describes how to package a hunspell spell check dictionary as a firefox add-on, or how to update your existing add-on, so that it can be installed, uninstalled and updated without a restart. parts needed to create a dictionary add-on, you first need two things: a spell check dictionary in hunspell or myspell format, with a license which allows you to use it. such a dictionary consists of two files, one with a .dic and one with an .aff file extension. a locale code to describe the language of the dictionary. for example en-us, de-de or da. it is important to choose the right locale code, or the spell checker will not be able to match the language of your dictionary against the language of a web page in order to select the right dictionary to use. if you are creating a...
...e sure that there is not already a dictionary available for your locale. if there already is one, try contacting the author to get it updated, or contact amo editors if the author does not respond. packaging a firefox add-on is a zip file renamed to use an .xpi file extension instead of the normal .zip file extension. to create a dictionary add-on, simply create a zip file which contains the following files and folders: my-dictionary.xpi install.rdf dictionaries/ locale-code.dic locale-code.aff the .dic and .aff files must be placed in a subfolder named dictionaries within the zip file. both files must have the locale code as their file name. you also have to add a file named install.rdf to the root of the zip file. this file contains information about your add-on such ...
...ary.xpi install.rdf dictionaries/ locale-code.dic locale-code.aff the .dic and .aff files must be placed in a subfolder named dictionaries within the zip file. both files must have the locale code as their file name. you also have to add a file named install.rdf to the root of the zip file. this file contains information about your add-on such as name and version number (see below). in addition to these required files, you may add optional files, for example to give your add-on an icon or to describe the license of the dictionary. here is an example of the install.rdf file. you can create and edit it with a plain text editor such as notepad. <?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#...
...And 3 more matches
Creating reftest-based unit tests
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). ...
...on 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). ...
...ke that your current directory (i.e. move to that directory). ...
...And 3 more matches
HTTP logging
loper has asked you for a log). 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. at any point during while your browser is running, you can turn logging on and off. this allows you to capture only the "interesting" part of the browser's behavior (i.e. your bug), which makes the http log much smaller and easier to analyze. launch the browser and get it into whatever state you need to be in just before your bug occurs. open a new tab and type in "about:networking" into the url bar. go to the "logging section" adjust the location of the log file if you don't like th...
... analyze. launch the browser and get it into whatever state you need to be in just before your bug occurs. open a new tab and type in "about:networking" into the url bar. go to the "logging section" adjust the location of the log file if you don't like the default adjust the list of modules that you want to log: this list has the exact same format as the moz_log environment variable (see below). generally the default list is ok, unless a mozilla developer has told you to modify it. click on start logging. reproduce the bug (i.e. go to the web site that is broken for you and make the bug happen in the browser) make a note of the value of "current log file". click on stop logging. go to the folder containing the specified log file, and gather all the log files. you will see several...
...ff; it's not hard at all! windows if firefox is already running, exit out of it. open a command prompt. on windows xp, you can find the "run..." command in the start menu's "all programs" submenu. on all newer versions of windows, you can hold down the windows key and press "r". type cmd and press enter, a new command prompt window with a black background will appear. copy and paste the following lines one at a time into the command prompt window. press the enter key after each one.: for 64-bit windows: set moz_log=timestamp,rotate:200,nshttp:5,cache2:5,nssockettransport:5,nshostresolver:5,cookie:5 set moz_log_file=%temp%\log.txt "c:\program files\mozilla firefox\firefox.exe" for 32-bit windows: set moz_log=timestamp,rotate:200,nshttp:5,cache2:5,nssockettransport:5,nshostreso...
...And 3 more matches
Simple SeaMonkey build
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. ...
...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 tools if your system is not listed below, see the build prerequisites page. debian linux: # this one-liner should install all necessary build deps sudo aptitude install zip mercurial libasound2-dev libcurl4-openssl-dev libnotify-dev libxt-dev libiw-dev libidl-dev mesa-common-dev autoconf2.13 yasm libgtk2.0-dev libdbus-1-dev libdbus-glib-1-dev python-dev libgstreamer0.10-dev libgstreamer-plugins-base0.10-dev libpulse-de...
...tall all necessary build deps sudo aptitude install zip mercurial libasound2-dev libcurl4-openssl-dev libnotify-dev libxt-dev libiw-dev libidl-dev mesa-common-dev autoconf2.13 yasm libgtk2.0-dev libdbus-1-dev libdbus-glib-1-dev python-dev libgstreamer0.10-dev libgstreamer-plugins-base0.10-dev libpulse-dev ubuntu linux # for ubuntu 12.04 lts (precise pangolin), replace the following line with: sudo apt-get build-dep thunderbird sudo apt-get build-dep seamonkey sudo apt-get install zip unzip mercurial g++ make autoconf2.13 yasm libgtk2.0-dev libglib2.0-dev libdbus-1-dev libdbus-glib-1-dev libasound2-dev libcurl4-openssl-dev libnotify-dev libgstreamer0.10-dev libgstreamer-plugins-base0.10-dev libiw-dev libxt-dev mesa-common-dev libpulse-dev fedora linux cent...
...And 3 more matches
Cross Process Object Wrappers
process object wrappers (cpows), which enable chrome code to synchronously access content in multiprocess firefox. note that from firefox 47 onwards, unsafe cpow usage is no longer permitted in browser code. if browser code tries an unsafe cpow operation, the browser will throw an exception and you'll see an "unsafe cpow usage forbidden” error in the browser console. add-on code is still allowed to use cpows "unsafely". however, if an add-on passes a cpow into a platform api, and that platform api then attempts an unsafe operation on it, this will throw an exception. so as a general rule, add-ons should avoid passing cpows into non-addon code. in multiprocess firefox, chrome code runs in a different process from web content. so chrome code can't directly interact with web content: in...
...scripts. chrome code can load frame scripts into the content process using the message manager, and can then communicate with them using a message-passing api. to learn more about this, see the documentation on using the message manager. 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 seri...
...", handlemessage); function handlemessage(message) { let wrapper = message.objects.clicked; console.log(wrapper.innerhtml); wrapper.innerhtml = "<h2>modified by chrome!</h2>" wrapper.setattribute("align", "center"); } auto-generated cpows add-ons that have not declared themselves multiprocess compatible are set up with a number of compatibility shims. one of these shims provides the following behavior: whenever chrome code tries to access content directly (for example, through window.content or browser.contentdocument), it is given back a cpow that wraps the content object. 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, t...
...And 3 more matches
Frame script loading and lifetime
he loadframescript() function. this line of code loads a frame script into the currently selected tab. the script just writes "foo" to the command line: // chrome script var mm = gbrowser.selectedbrowser.messagemanager; mm.loadframescript('data:,dump("foo\\n")', true); loadframescript() takes two mandatory parameters: a url that points to the frame script you want to load a boolean flag, allowdelayedload note: if the message manager is a global frame message manager or a window message manager, loadframescript() may load the script multiple times, once in each applicable frame. chrome: urls extension developers usually use a chrome:// url to refer to the frame scripts. to define the mapping between a chrome:// url and a frame script packaged with an extension, use a "chrome.manife...
...hrome: urls extension developers usually use a chrome:// url to refer to the frame scripts. to define the mapping between a chrome:// url and a frame script packaged with an extension, use a "chrome.manifest" file to register a chrome url: // chrome.manifest content my-e10s-extension chrome/content/ // chrome script mm.loadframescript("chrome://my-e10s-extension/content/content.js", true); allowdelayedload if the message manager is a global frame message manager or a window message manager then: if allowdelayedload is true, the frame script will be loaded into any new frame, which has opened after the loadframescript() call. for example: var mm = window.messagemanager; mm.loadframescript("chrome://my-e10s-extension/content/frame-script.js", true); the script will be loaded i...
...e manager then: if allowdelayedload is true, the frame script will be loaded into any new frame, which has opened after the loadframescript() call. for example: var mm = window.messagemanager; mm.loadframescript("chrome://my-e10s-extension/content/frame-script.js", true); the script will be loaded into all tabs currently open in this window, and all new tabs opened afterwards. if allowdelayedload is false, the script will only be loaded into frames which are open when the call was made. if the message manager is a browser message manager, you should always pass true here. because a browser message manager only corresponds to a single browser tab, its loadframescript() function will only ever load the frame script into that one tab. ...
...And 3 more matches
Localization and Plurals
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 entry in the following list of plural rules. list of plural rules this section contains a list of plural rules ordered by their plural rule number. each entry indicates how many plural forms are needed when localizing a word. for each entry, there is a list of families and languages in those families, to help you figure out if it's the rule you should pick for pluralrule. additionally, there is a brief description...
... list of plural rules this section contains a list of plural rules ordered by their plural rule number. each entry indicates how many plural forms are needed when localizing a word. for each entry, there is a list of families and languages in those families, to help you figure out if it's the rule you should pick for pluralrule. additionally, there is a brief description of each plural form, followed by some sample numbers that fall into that particular form. for a given plural rule, the order in which the plural forms are listed is the same order you need to localize a word, separated by semi-colons. for example, english uses plural rule 1, and localizing plurals would require a string of "plural;plurals" where the first word is the singular form and the second is the general plural form.
... 84, 92, 93, 94, 102, 103, 104, 122, 123, 124, 132, 133, 134, 142, 143, 144, 152, 153, 154, 162, 163, 164, 172, 173, 174, 182, 183, … everything else: 0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 26, 27, 28, 29, 30, 35, 36, 37, 38, 39, 40, 45, 46, 47, 48, 49, 50, 55, 56, 57, 58, 59, 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 locali...
...And 3 more matches
Translation phase
ociated 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 links to tutorials outlining their workflows. mozilla applications so you're interested in localizing mozilla applications. each l10n tool follows a different workflow for localizing mozilla application projects. we've linked a...
... these are the l10n tools we use to localize mozilla applications: pootle a user-friendly web portal built on the translate toolkit api. this tool includes workspaces for translating strings, reviewing string submissions, and project dashboards. ...
... these are the l10n tools we use to localize mozilla applications: pootle a user-friendly web portal built on the translate toolkit api. this tool includes workspaces for translating strings, reviewing string submissions, and project dashboards. ...
...And 3 more matches
BloatView
es that can be used. xpcom_mem_bloat_log if set, this causes a bloat log to be printed on program exit, and each time nstracerefcnt::dumpstatistics is called. this log contains data on leaks and bloat (a.k.a. usage). xpcom_mem_leak_log this is similar to xpcom_mem_bloat_log, but restricts the log to only show data on leaks. you can set these environment variables to any of the following values. 1 - log to stdout. 2 - log to stderr. filename - write log to a file. reading individual bloat logs full bloatview output contains per-class statistics on allocations and refcounts, and provides gross numbers on the amount of memory being leaked broken down by class. here's a sample of the bloatview output. == bloatview: all (cumulative) leak and bloat statistics, tab process ...
...o look for: are your classes in the list? - look! if they aren't, then you're not using the ns_impl_addref and ns_impl_release (or ns_impl_isupports which calls them) for xpcom objects, or moz_count_ctor and moz_count_dtor for non-xpcom objects. not having your classes in the list is not ok. that means no one is looking at them, and we won't be able to tell if someone introduces a leak. (see below for how to fix this.) the bytes leaked for your classes should be zero! - need i say more? if it isn't, you should use the other tools to fix it. the number of objects remaining might not be equal to the total number of objects. this could indicate a hand-written release method (that doesn't use the ns_log_release macro from nstracerefcnt.h), or perhaps you're just not freeing any of the instan...
...ces you've allocated. these sorts of leaks are easy to fix. the total number of objects might be 1. this might indicate a global variable or service. usually this will have a large number of refcounts. if you find leaks, you can use refcount tracing and balancing to discover the root cause. combining and sorting bloat logs you can view one or more bloat logs in your browser by running the following program. perl tools/bloatview/bloattable.pl log1 log2 ... logn > htmlfile this will produce an html file that contains a table similar to the following (but with added javascript so you can sort the data by column). byte bloats name file date blank blank.txt tue aug 29 14:17:40 2000 mozilla mozilla.txt tue aug 29 14:18:42 2000 yahoo ...
...And 3 more matches
Refcount tracing and balancing
d balancing are advanced techniques for tracking down leak of refcounted objects found with bloatview. the first step is to run firefox with refcount tracing enabled, which produces one or more log files. refcount tracing logs calls to addref and release, preferably for a particular set of classes, including call-stacks in symbolic form (on platforms that support this). refcount balancing is a follow-up step that analyzes the resulting log to help a developer figure out where refcounting went wrong. how to build for refcount tracing build with --enable-debug or --enable-logrefcnt. how to run with refcount tracing on there are several environment variables that can be used. first, you select one of three environment variables to choose what kind of logging you want. you almost certainly w...
...riable to the name of a file, the log will be output to that file. you can also set it to 1 to log to stdout or 2 to log to stderr, but these logs are large and expensive to capture, so you probably don't want to do that. ...
...e logging will be completely useless due to how slow the browser 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...
...And 3 more matches
powermetrics
bination with rapl via the mach power command. this document describes the version of powermetrics that comes with mac os 10.10. the one that comes with 10.9 is less powerful. 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. quick start powermetrics provides a vast number of measurements. the following command encompasses the most useful ones: sudo powermetrics --samplers tasks --show-process-coalition --show-process-gpu -n 1 -i 5000 --samplers tasks tells it to just do per-process measurements. --show-process-coalition tells it to group coalitions of related processes, e.g. the firefox parent process and child processes. --show-process-gpu tells it to show per-process gpu measurements...
... per-process measurements. --show-process-coalition tells it to group coalitions of related processes, e.g. the firefox parent process and child processes. --show-process-gpu tells it to show per-process gpu measurements. -n 1 tells it to take one sample and then stop. -i 5000 tells it to use a sample length of 5 seconds (5000 ms). change this number to get shorter or longer samples. ...
... name: coalitio...
...And 3 more matches
L20n Javascript API
iator: function) register a function which will be used to negotiate the locales supported by the context instance. if you don't call this function, l20n will use the built-in intl.prioritizelocales negotiator. ctx.registerlocalenegotiator(function(available, requested, deflocale) { return intl.prioritizelocales(available, requested, deflocale); }); negotiator is a function which takes the following arguments: available - all locales available to the context instance, requested - locales preferred by the user, deflocale - the default locale to be used as the ultimate fallback, callback - the function to call when the negotiation completes (useful for asynchronous negotiators). it must return an array which is the final fallback chain of locales, or if the negotiation is asynchrono...
...be negotiated 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 r...
...is unable to parse the syntax of a resource; this might result in entities being broken which in turn can lead to above error being emitted. warning - fired when a less serious error occurs from which the context instance can recover gracefully and try to fetch a translations from a fallback locale. the error object is passed as the first argument to callback and can be one of the following: context.error, when there are problems with setting up resources (e.g. a 404 error when fetching a resource file, or recursive import statements in resource files), context.translationerror, when there is a missing translation in one of supported locales; the context instance will try to retrieve a fallback translation from the next locale in the fallback chain, ...
...And 3 more matches
Localization Use Cases
this article documents a few opportunities to improve the localization of gaia (the ui layer of firefox os) by using l20n. in all presented examples, we try to show the existing code, explain the problem from the localizers' or developers' perspective, and suggest a solution. declensions in gaia's browser app, there's an about-browser string defined as follows in apps/browser/locales/browser: about-browser=about {{browserbrandshortname}} problem definition in many inflected languages (e.g. german, finnish, hungarian, all slavic languages), the about preposition governs the grammatical case of the complement. it might be the accusative (german), ablative (latin) or locative (slavic languages). let's take slovenian as an example. in slovenian, the ideal string would inflect the no...
...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 about preposition: <aboutbrowser "o {{ browserbrandshortname.locative }}"> for the official branding, we get: o firefoxu and for the unofficial branding, we end up with: o brskalniku genders in the system app's apps/system...
...first, there is devicestoragehelper.showformatedsize (sic): function showformatedsize(element, l10nid, size) { if (size === undefined || isnan(size)) { element.textcontent = ''; return; } // kb - 3 kb (nearest ones), mb, gb - 1.2 mb (nearest tenth) var ...
...And 3 more matches
NSS 3.12.4 release notes
nss 3.12.4 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1. distribution information this release is built from the source, at the cvs repository rooted at cvs.mozilla.org:/cvsroot, with the cvs tag nss_3_12_4_rtm. nss 3.12.4 requires nspr 4.8. this is not a hard requirement. ...
...12.4 is in the "review pending" state in the fips 140-2 pre-validation list at http://csrc.nist.gov/groups/stm/cmvp/documents/140-1/140inprocess.pdf added crl distribution point support (see cert.h). cert_decodecrlissuingdistributionpoint cert_findcrlissuingdistpointexten the old documentation of the expression matching syntax rules was incorrect, and the new corrected documentation is as follows for public nssutil functions (see portreq.h): port_regexpvalid port_regexpsearch port_regexpcasesearch these functions will match a string with a shell expression. the expressions accepted are based loosely on the expressions accepted by zsh. expected return values: non_sxp if exp is a standard string invalid_sxp if exp is a shell expression, but invalid valid_sxp if exp is a valid shell ...
...atches one occurence of a, b, or c. [^abc] matches any character except a, b, or c. to be matched between [ and ], these characters must be escaped: \ ] no other characters need be escaped between brackets. unnecessary escaping is permitted. [a-z] matches any character between a and z, inclusive. the two range-definition characters must be alphanumeric ascii. if one is upper case and the other is lower case, then the ascii non-alphanumeric characters between z and a will also be in range. [^a-z] matches any character except those between a and z, inclusive. these forms cannot be combined, e.g [a-gp-z] does not work. exclusions: as a top level, outter-most expression only, the expression foo~bar will match the expression foo, provided it does not also match the expression bar. either expressio...
...And 3 more matches
NSS 3.12.5 release_notes
nss 3.12.5 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1. distribution information the cvs tag for the nss 3.12.5 release is nss_3_12_5_rtm. nss 3.12.5 requires nspr 4.8. ...
... standardized by the ietf. if an application depends on renegotiation feature, it can be enabled by setting the environment variable nss_ssl_enable_renegotiation to 1. by setting this environmental variable, the fix provided by these patches will have no effect and the application may become vulnerable to the issue. this default setting can also be changed within the application by using the following existing api functions: secstatus ssl_optionset(prfiledesc *fd, print32 option, prbool on) secstatus ssl_optionsetdefault(print32 option, prbool on) there is now a new value for "option", which is: ssl_enable_renegotiation the corresponding new values for ssl_enable_renegotiation are: ssl_renegotiate_never: never renegotiate at all (default). ssl_reneg...
...gotiate without restriction, whether or not the peer's client hello bears the renegotiation info extension (as we always did in the past). unsafe. tls compression enable tls compression with: ssl_enable_deflate: enable tls compression with deflate. off by default. (see ssl.h) error codes: ssl_error_decompression_failure (see sslerr.h) ssl_error_renegotiation_not_allowed (see sslerr.h) new context initialization and shutdown functions see nss.h for details. the 2 new functions are: nss_initcontext nss_shutdowncontext parameters for these functions are used to initialize softoken. these are mostly strings used to internationalize softoken. memory for the strings are owned by the caller, who is free to free them once nss_contextinit ret...
...And 3 more matches
PKCS11 FAQ
Mozilla › Projects › NSS › PKCS11 › FAQ
if your token is read/write and has only one session, nss will open that one initial session read/write. what permanent pkcs #11 objects are used by nss or read from the token? example: rsa private key, ca certificate, user's own certificate, user's name. private keys (rsa and dsa) and the corresponding certificates 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.
...f 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 looking up all private keys. by looking up all certificates. certificates may be looked up by label. by convention, all certificates making up a single personality should have the same label (that is, a pair of certificates, one for signing and one for key exchange, should have the same label). s/mime-capable certificates are also looked up by issuer/serial number. ...
...r that key is loaded. this case is interesting only for read/write tokens. what labels does nss use to identify certificates? nss can use the cka_label attribute to identify user certificates (see previous question) and presents this label to the user. therefore, each user certificate must have some label associated with it. the label for a token certificate is presented to the user as follows:token label :certificate label . this implies that eachtoken label should be unique and meaningful to the user, and that eachcertificate label should be unique to the token. nss gets the value of the cka_label attribute from the token. labels should not have any trailing blank characters. will nss use the random number generation features of pkcs #11? only if you identify your token as the de...
...And 3 more matches
NSS tools : ssltab
n the ssl debugging tool ssltap 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 options -v print a version string for the tool. -h turn on hex/ascii printing. instead of outputting raw data, the command interprets each record as a numbered line of hex values, followed by the same data as ascii characters. the two parts are separated by a vertical bar. nonprinting characters are replaced by dots. -f turn on fancy printing. output is printed in colored html. data sent from the client to the server is in blue; the server's reply is in red. when used with looping mode, the different connections are separated with horizontal lines. you can use this option to uplo...
...output, and the parsed ssl output. -x turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the same output format as the -h option. -l prefix turn on looping; that is, continue to accept connections rather than stopping after the first connection is complete. -p port change the default rendezvous port (1924) to another port. the following are well-known port numbers: * http 80 * https 443 * smtp 25 * ftp 21 * imap 143 * imaps 993 (imap over ssl) * nntp 119 * nntps 563 (nntp over ssl) usage and examples you can use the ssl debugging tool to intercept any connection information. 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 w...
...sage and examples you can use the ssl debugging tool to intercept any connection information. 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 i...
...And 3 more matches
NSS tools : ssltap
n the ssl debugging tool ssltap 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 options -v print a version string for the tool. -h turn on hex/ascii printing. instead of outputting raw data, the command interprets each record as a numbered line of hex values, followed by the same data as ascii characters. the two parts are separated by a vertical bar. nonprinting characters are replaced by dots. -f turn on fancy printing. output is printed in colored html. data sent from the client to the server is in blue; the server's reply is in red. when used with looping mode, the different connections are separated with horizontal lines. you can use this option to uplo...
...output, and the parsed ssl output. -x turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the same output format as the -h option. -l prefix turn on looping; that is, continue to accept connections rather than stopping after the first connection is complete. -p port change the default rendezvous port (1924) to another port. the following are well-known port numbers: * http 80 * https 443 * smtp 25 * ftp 21 * imap 143 * imaps 993 (imap over ssl) * nntp 119 * nntps 563 (nntp over ssl) usage and examples you can use the ssl debugging tool to intercept any connection information. 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 w...
...sage and examples you can use the ssl debugging tool to intercept any connection information. 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 i...
...And 3 more matches
NSS Tools pk12util
availability see the release notes for the platforms this tool is available on. ...
...three of the options, -i, -o, and -l, should be considered commands of the pk12util invocation. each command takes several options. options may take zero or more arguments. to see a usage string, issue the pkcs12util command without any options. options and arguments options specify an action. option arguments modify an action. the options and arguments for the pk12util comman...
...f the options, -i, -o, and -l, should be considered commands of the pk12util invocation. each command takes several options. options may take zero or more arguments. to see a usage string, issue the pkcs12util command without any options. options and arguments options specify an action. option arguments modify an action. the options and arguments for the pk12util command are defined as follows: options -i p12file import a certificate and private key from from the p12file into the database. -o p12file export certificate and private key, specified by the -n option, from the database to the p12 file. -l p12file list certificate and private key from from the p12file file. arguments -n certname specify the nickname of the cert and private key to export. -d dir specif...
...And 3 more matches
NSS Tools ssltap
art of the handshake procedure, before the secure connection is established. syntax to run the ssl debugging tool, type this command in a command shell: ssltap [-vhfsxl] [-p port] hostname:port options the command does not require any options other than hostname:port, but you normally use them to control the connection interception and output. the options for the command are the following: -v print a version string for the tool. -h turn on hex/ascii printing. instead of outputting raw data, the command interprets each record as a numbered line of hex values, followed by the same data as ascii characters. the two parts are separated by a vertical bar. nonprinting characters are replaced by dots. -f turn on fancy printing. output is printed in colored html. data sent from t...
...cii output, and the parsed ssl output. -x turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the same output format as the -h option. -l turn on looping; that is, continue to accept connections rather than stopping after the first connection is complete. -p port change the default rendezvous port (1924) to another port. the following are well-known port numbers: http 80 https 443 smtp 25 ftp 21 imap 143 imaps 993 (imap over ssl) nntp 119 nntps 563 (nntp over ssl) examples you can use the ssl debugging tool to intercept any connection information. 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 t...
... examples you can use the ssl debugging tool to intercept any connection information. 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: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 da...
...And 3 more matches
NSS tools : ssltap
Mozilla › Projects › NSS › tools › ssltap
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 options -v print a version string for the tool. -h turn on hex/ascii printing. instead of outputting raw data, the command interprets each record as a numbered line of hex values, followed by the same data as ascii characters. the two parts are separated by a vertical bar. nonprinting characters are replaced by dots. -f turn on fancy printing. output is printed in colored html. data sent from the client to the server is in blue; the server's reply is in red. when used with looping mode, the different connections ...
... data inside parsed ssl records. used only with the -s option. this option uses the same output format as the -h option. -l prefix turn on looping; that is, continue to accept connections rather than stopping after the first connection is complete. -p port change the default rendezvous port (1924) to another port. the following are well-known port numbers: * http 80 * https 443 * smtp 25 * ftp 21 * imap 143 * imaps 993 (imap over ssl) * nntp 119 * nntps 563 (nntp over ssl) usage and examples you can use the ssl debugging tool to intercept any connection information. although you can run the tool at its most basic b...
... you can use the ssl debugging tool to intercept any connection information. 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 b...
...And 3 more matches
Rhino overview
introduction most people who have used javascript before have done so by adding scripts to their html web pages. however, rhino is an implementation of the core language only and doesn't contain objects or methods for manipulating html documents. rhino contains all the features of javascript 1.7 allows direct scripting of java a javascript shell for executing javascript scripts a javascript compiler to transform javascript source files into java class files a javascript debugger for scripts executed with rhino language the javascript language itself is standardized by standard ecma-262 ecmascript: a general purpose, cross-platform programming language. rhino 1.3 and greater conform to edition 3 of the standard. rhino 1.6 and greater implement ecma-357 ecmascript for xml (...
...262 ecmascript: a general purpose, cross-platform programming language. 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 any java class with a javascript 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 featu...
...script to implement any java interface or extend any java class with a javascript 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 in...
...And 3 more matches
GCIntegration - SpiderMonkey Redirect 1
store it in the js representation. never store gc things in a jsobject's private pointer (i.e., via js_setprivate()). it's better to store them in reserved slots, since those will automatically be traced if the object is native. as much as possible, avoid trace hooks. if objects are structured as described above, there should be no need for them. this should be obvious by now, but never ever allow a gc thing point to a gc thing in a different compartment unless it's a wrapper that's registered in the cross-compartment wrapper map. now, on to the details... gc/cc interaction <to be done later.> incremental gc incremental gc divides gc marking into time slices. in between these slices, non-gc code is allowed to run. done naively, this technique can lead to reachable object not being ma...
... gc thing in a different compartment unless it's a wrapper that's registered in the cross-compartment wrapper map. now, on to the details... gc/cc interaction <to be done later.> incremental gc incremental gc divides gc marking into time slices. in between these slices, non-gc code is allowed to run. done naively, this technique can lead to reachable object not being marked. consider the following example. {{ svg{source: "http://people.mozilla.org/~wmccloskey/incremental1.svg", embedding: "iframe", height:"130"} }} assume object b is already marked, as in the leftmost frame, while objects a and c have not been marked yet. in the middle frame some code creates a pointer from b to c and destroys the pointer from a to c. in the last frame, a gets marked by the gc. the problem is that c i...
... in common areas of firefox: if a pointer is never changed after it's initialized, then there's no need for a write barrier. initializing a pointer never requires a write barrier because there was nothing being destroyed that might have part of the initial snapshot. if a pointer is not traced via js_call_tracer or any similar mechanism, then there's no need for a write barrier (although see below about read barriers). the initial snapshot only contains objects reachable via traced pointers, so there's no danger that overwriting an untraced pointer will disrupt the snapshot. some pointers are guaranteed to be marked in the first slice of the gc. therefore, it's not possible for code to modify them between when the initial snapshot is taken and when the pointer is marked, so no write barri...
...And 3 more matches
Getting SpiderMonkey source code
you can get the spidermonkey source code in gzipped form or directly from the mercurial repository. downloading gzipped spidermonkey source code you can download gzipped spidermonkey source code from the following urls: http://ftp.mozilla.org/pub/spidermonkey/releases/ http://ftp.mozilla.org/pub/spidermonkey/prereleases/ here is a command-line example of downloading and unzipping spidermonkey source code version 59.0: mkdir mozilla cd mozilla wget http://ftp.mozilla.org/pub/spidermonkey/prereleases/59/pre1/mozjs-59.0a1.0.tar.bz2 tar xvf mozjs-59.0a1.0.tar.bz2 these commands should work on most platforms including windows, as long as on windows you are using the mozillabuild bash shell. getting the latest spidermonkey source code from mercurial the mercurial repository at https://hg.m...
.../59/pre1/mozjs-59.0a1.0.tar.bz2 tar xvf mozjs-59.0a1.0.tar.bz2 these commands should work on most platforms including windows, as long as on windows you are using the mozillabuild bash shell. getting the latest spidermonkey source code from mercurial the mercurial repository at https://hg.mozilla.org/mozilla-central/ hosts the latest spidermonkey sources. mercurial is also known as hg. the following command line downloads the entire mozilla repository, including the full change history and a lot of gecko and firefox source code that isn't part of spidermonkey. it also changes to the spidermonkey directory (js/src). hg clone https://hg.mozilla.org/mozilla-central/ cd js/src to avoid getting the full change history, click the zip or gz links at https://hg.mozilla.org/index.cgi/mozilla-ce...
...g.mozilla.org/index.cgi/mozilla-central/file/tip. this fetches a snapshot of the current mozilla tree. if you have problems with the instructions above, you can read the full details of using mercurial to get mozilla code here. that page also contains links to several bundles, which can be useful if you have a poor network connection. ...
...And 3 more matches
64-bit Compatibility
this article focuses on hacking tracemonkey code generation (jstracer.cpp, jsregex.cpp) in ways that will work on both 32-bit and 64-bit jit backends. what widths are the random typedefs everywhere? the following types or typedefs are always 64-bit on 64-bit platforms, and 32-bit on 32-bit platforms: pointers uintptr_t, intptr_t, ptrdiff_t, (probably) size_t jsval jsuword, jsword length of a string, though the actual length cannot exceed 30 bits jsuintptr, jsintptr, jsptrdiff, jsuptrdiff, jssize, jsuword, jsword (let's not use these, kthx) the following types are 32-bit on 32-bit platforms. 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 poi...
.... to help form well-typed lir, there is a special opcode called lir_float which specifies that the associated constant value is definitely floating-point. tracemonkey uses this to decide whether arbitrary constants in lir are pointers or doubles. you should never use lirwriter::insimmq() to inject a floating point value. use lirwriter::insimmf() instead. ...
...use lirwriter::insimmf() instead. mucking with native integers in lir the following opcodes can be used to safely load, modify, and compare native integers. for such opcodes there are two forms, an "undecorated" form which is 32-bit, and a form decorated with a "q" or "qi" that is 64-bit. to make it easier to generate platform specific code, these opcodes have aliases decorated with a "p". ...
...And 3 more matches
Property cache
shape integers do not exist anymore. the property cache still exists, but it is simpler now. spidermonkey mainly uses type inference to determine which properties 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. ...
...ash table with no chaining. collisions simply cause old entries to be overwritten. the hash table entries are key-value pairs. the keys describe the context in which a property lookup occurs. the values consist of two word-sized members. entry->vcap caches the results of part 1 above, telling which object contains the desired property. entry->vword is described in the section entry value words below. it caches the results of part 2, if the property is simple enough for optimized access, or a pointer to the js::shape if not. the opcodes that take advantage of the property cache, as of june 2009, are: getprop, get{x,this,arg,local}prop, and length; name; setprop, bindname, and setname; callprop and callname; and {inc,dec}name and name{inc,dec}. elem opcodes do not use it. nor do {inc,dec}pro...
...getprop, get{x,this,arg,local}prop, and length; name; setprop, bindname, and setname; callprop and callname; and {inc,dec}name and name{inc,dec}. elem opcodes do not use it. nor do {inc,dec}prop or prop{inc,dec}. nor do operations such as add that only need to look up a property (.tostring) in unusual cases. throughout this article, phrases such as "own property" should be taken to refer to the low-level representation of properties in scopes and shape chains. in the case of shared permanent properties, this differs from the notion of "own property" seen by scripts via object.prototype.hasownproperty. shape native objects have a shape, a 24-bit unsigned integer such that: basic layout guarantee — if at time t0 the object x has shape s and at time t1 the object y has shape s, and n...
...And 3 more matches
Introduction to the JavaScript shell
legacy features. running the javascript shell the shell offers two modes of operation. you can use it as an interactive shell, in which you type javascript code at a prompt and get instant gratification, which is handy for experimenting or testing new features. you can also pass in, on the command line, a javascript program file to run, in which case the program is run automatically. after following the build documentation and installing the built shell using make install, you can run the shell in interactive mode using the command: js [ if you get " symbol lookup error: ./js: undefined symbol: pr_setcurrentthreadname" e.g. from a bash console when using a pre-compiled binary, try <path to your firefox's run-mozilla.sh>/run-mozilla.sh ./js -- that worked for me] if you'd like to r...
... command: js foo.js to run foo.js then drop into the interactive shell, do this: js -f foo.js -i reference note: because the javascript shell is used as a test environment for the javascript engine, the available options and built-in functions can change over time. command line options there are a number of command line options you can specify to control the shell. these are summarized below. be sure to use -h with your own jsshell to see if there is anything undocumented. -c, --compileonly tells the shell to compile the program but not run it. this is a convenient way to quickly check for syntax errors in your program without actually running it. -e script runs the specified script, which is a literal string containing the code to execute. -f filename runs the javascript pro...
...cparam() sets gc parameter name to value. for more information, see the c/c++ functions js_getgcparameter and js_setgcparameter. gczeal(level) added in spidermonkey 1.8 debug only. set the level of gc zeal, a debugging feature. this can be 0 for normal periodic garbage collection, 1 for very frequent gc, or 2 for extremely frequent gc. anything other than 0 will make javascript run extremely slow but may help reveal or reproduce gc-related bugs. for more information, see the c/c++ version of this function, js_setgczeal. getpda(object) returns the property descriptors for the specified object. getslx(object) returns the script line extent, which is the number of lines of code comprising the specified object. help([command ...]) displays brief help information about the specified comm...
...And 3 more matches
TPS Bookmark Lists
's value. for example: var bookmarks_after_second_modify = { "menu": [ { uri: "http://www.getfirefox.com/", title: "get firefox" } ], "menu/foldera": [ { uri: "http://mozilla.com", title: "mozilla" }, ] }; this describes two bookmarks, one in the "menu" folder, and the other in the "folder1" subfolder of "menu". all bookmark paths must begin with one of the following: "menu": the normal bookmarks menu "toolbar": the bookmarks toolbar "tags": the tags folder "unfiled": the unfiled bookmarks folder "places": the places root folder ("menu", "toolbar", and "unfiled" are all children of this) sub-folders are preceded with forward slashes, so "menu/folder1" denotes that "folder1" is a sub-folder of "menu". tps does not support forward slashes as part of a fold...
...er "places": the places root folder ("menu", "toolbar", and "unfiled" are all children of this) sub-folders are preceded with forward slashes, so "menu/folder1" denotes that "folder1" is a sub-folder of "menu". tps does not support forward slashes as part of a folder name. folder contents the contents for a folder are given as an array of objects, representing various bookmark types, described below. bookmark objects valid properties are: uri: the bookmark uri. required. title: the bookmark title. optional. defaults to the bookmark uri. loadinsidebar: true or false. optional. toggles the "load in sidebar" property. description: the bookmark description. optional. tags: an array of tags for the bookmark. optional. keyword: the keyword for the bookmark. optional. after: the title of the bookm...
...required. siteuri: the livemark's uri. optional. feeduri: the livemark's feed uri. required. after: the title of the bookmark item expected to be found after this livemark; used onl...
...And 3 more matches
Places Developer Guide
folders: int64 getchildfolder(afolderid, asubfoldertitle) - returns the id of the first subfolder matching the given title. int64 getidforitemat(afolderid, aposition) - returns the id of the item at the given position (throws if there's no item there). bool getfolderreadonly(afolderid) accessing folder contents queries in places are executed through the main history service. the example below shows how to enumerate a bookmark folder's contents, and how to access the properties of the items themselves. var history = cc["@mozilla.org/browser/nav-history-service;1"] .getservice(ci.nsinavhistoryservice); var query = history.getnewquery(); query.setfolders([myfolderid], 1); var result = history.executequery(query, history.getnewqueryoptions()); // the root property of a query result is a...
..._uri) { var uri = childnode.uri; } else if (type == ci.nsinavhistoryresultnode.result_type_folder) { childnode.queryinterface(ci.nsinavhistorycontainerresultnode); childnode.containeropen = true; // now you can iterate over a subfolder's children } } ther available node types are documented in the idl. searching bookmarks queries are executed through the history service. the example below shows how to search through all bookmarks, and to iterate over the results. var bookmarks = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); var history = cc["@mozilla.org/browser/nav-history-service;1"] .getservice(ci.nsinavhistoryservice); var query = history.getnewquery(); // specify folders to be searched var folders = ...
...balhistory2 - simple page detection and addition nsiglobalhistory3 - for adding document redirects adding to history places provides a couple of interfaces for adding to, and editing the browsing history. the main interface is nsinavhistoryservice. other interfaces that provide specialized abilities are nsibrowserhistory and nsiglobalhistory. examples of the capabilities of each are provided below. // places deals in uris, so here's a helper for creating them. function uri(spec) { return cc["@mozilla.org/network/io-service;1"]. getservice(ci.nsiioservice). newuri(spec, null, null); } // adding a basic visit via the core places history service. var history = cc["@mozilla.org/browser/nav-history-service;1"]. getservice(ci.nsinavhistoryservice); var oururi =...
...And 3 more matches
Avoiding leaks in JavaScript XPCOM components
uld 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 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, t...
...e 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 multiple owners to influence the lifetime of an object. in this strategy, the object has a member that is the number of other objects that "own" it. when this count goes to zero, the object destroys itself. this is the strategy used by xpcom, partly because it can be used through a very simple api, addref and release. in c++, we use nscomptr to help manage ownership, and we use macros to impl...
...y management models. javascript uses garbage collection. xpcom uses reference counting. authors of javascript code that uses xpcom objects can't depend on all of the benefits of garbage collection. they face some of the disadvantages of reference counting. understanding how memory management works in xpconnect helps understand why this is the case. xpconnect basically provides two features. it allows javascript code to access xpcom objects (i.e., it wraps native xpcom objects for javascript) and it allows javascript code to implement xpcom interfaces (i.e., it wraps javascript objects for xpcom). for javascript objects that implement xpcom interfaces, the interface between reference counting and garbage collection is quite simple. (the implementation is slightly more complicated, but only t...
...And 3 more matches
NS_ConvertASCIItoUTF16
ubstring 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 appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
NS_ConvertUTF16toUTF8
ubstring 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 appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
NS_ConvertUTF8toUTF16
ubstring 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 appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
NS_LossyConvertUTF16toASCII
ubstring 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 appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsACString_internal
eloper.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 appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutab...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsAString_internal
eveloper.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 appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutab...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsAdoptingCString
ar 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(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsAdoptingString
ar 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(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsAutoString
ubstring 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 appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsCAutoString
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 appendliteral(const char appendliteral(char operator+= insert cut ...
... 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. ...
...lsascii(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. ...
...And 3 more matches
nsCString
ubstring 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 appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsDependentCSubstring
entsubstring for wide characters nsdependentcsubstring for narrow characters method overview constructors rebind 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 appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutab...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsDependentSubstring
entsubstring for wide characters nsdependentcsubstring for narrow characters method overview constructors rebind 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 appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutab...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsFixedCString
ubstring 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 appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsFixedString
ubstring 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 appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsPromiseFlatCString
ubstring 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 appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsPromiseFlatString
ubstring 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 appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsString
ubstring 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 appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsXPIDLCString
ar 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(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsXPIDLString
ar 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(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata set...
...ameters 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. ...
...en 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. ...
...And 3 more matches
nsIAbCard
properties aren't stored anymore on the card, except for a handful of them. complex properties are expected to be accessed through a call to getproperty. see //github.com/realityripple/uxp/blob/master//mailnews/addrbook/public/nsiabcard.idl for more details. ...
...irthday astring custom1 astring custom2 astring custom3 astring custom4 astring notes astring lastmodifieddate unsigned long popularityindex unsigned long popularityindex is bumped every time e-mail is sent to this recipient . ...
...d long popularityindex unsigned long popularityindex is bumped every time e-mail is sent to this recipient . prefermailformat unsigned long allowed values are stored in nsiabprefermailformat. ismaillist boolean maillisturi string if ismaillist is true then maillisturi will contain the uri of the associated mailing list. allowremotecontent boolean allow remote content to be displayed in html mail received from this contact methods getcardvalue() astring getcardvalue(in string name) parameters name the attribute you want the value for. return value the value of the attribute asked for. setcardvalue() void setcardvalue(in string attrname, in astring value) parameters attrname the attrib...
...And 3 more matches
nsIChannel
netwerk/base/nsichannel.idlscriptable this interface allows clients to construct 'get' requests for specific protocols, and manage them in a uniform way. inherits from: nsirequest last changed in gecko 19.0 (firefox 19.0 / thunderbird 19.0 / seamonkey 2.16) once a channel is created (via nsiioservice.newchannel()), parameters for that request may be set by using the channel attributes, or by calling queryinterface() to retrieve a subclass of nsichannel for protocol-specific parameters. then, the uri can be fetched by calling open() or asyncopen(). after a request has been completed, the channel is still valid for accessing protocol-specific results. for example, queryinterfacing to nsihttpchannel allows response headers to be retrieved for the corresponding http transaction. ...
...his 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 parameter is given, then its value will replace the the contentcharset attribute of the channel. the stripped contenttype will be lowercased. any implementation of nsichannel must follow these rules. ...
...nnel. this means that: the stream listener this channel will be notifying was initially passed to the asyncopen() method of some other channel this channel's uri is a better identifier of the resource being accessed than this channel's originaluri. this flag can be set, for example, for redirects or for cases when a single channel has multiple parts to it (and thus can follow onstoprequest with another 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...
...And 3 more matches
nsIDroppedLinkHandler
dom/base/nsidroppedlinkhandler.idlscriptable please add a summary to this article. 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 candroplink(in nsidomdragevent aevent, in prbool aallowsamedocument); astring droplink(in nsidomdragevent aevent, out astring aname, [optional] in boolean adisallowinherit); void droplinks(in nsidomdragevent aevent, [optional] in boolean adisallowinherit, [optional] out unsigned long acount, [retval, array, size_is(acount)] out nsidroppedlinkitem alinks); methods candroplink() determines if a link being dragged can be dropped. boolean candroplink( in nsidomdragevent aevent, in prbool aal...
...this check includes any parent, sibling and child frames in the same content tree. if true, the source is not checked. ...
...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. ...
...And 3 more matches
nsIEffectiveTLDService
etldservice = components.classes["@mozilla.org/network/effective-tld-service;1"] .getservice(components.interfaces.nsieffectivetldservice); the name "effective tld service" is a historical one; today, the items this interface manipulates are called public suffixes, and the list of them is the public suffix list, or psl. see publicsuffix.org for more information. the methods below implement the public suffix algorithm in full, including the implicit "*" 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 f...
... 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 copy of the psl you are working with. the tld space is currently expanding at a fairly great rate, and the copy of the psl firefox has may not be totally up to date (because it's not dynamically updated data). method overview acstring getbasedomain(in nsiuri auri, [optional] in pruint32 aadditionalparts); ...
...i is empty. ns_error_insufficient_domain_levels this exception is thrown if there were insufficient subdomain levels in the hostname to satisfy the requested aadditionalparts value. ns_error_host_is_ip_address this exception is thrown if auri is a numeric ipv4 or ipv6 address. ns_error_unexpected or other error returned by nsiidnservice.normalize() when the hostname contains characters disallowed in uris. getbasedomainfromhost() returns the base domain of a host string. otherwise identical to getbasedomain(). note: it is strongly recommended that you use getbasedomain() if a suitable nsiuri is available. only use this method if this is not the case. acstring getbasedomainfromhost( in autf8string ahost, in pruint32 aadditionalparts optional ); parameters ahost the host st...
...And 3 more matches
nsIProtocolHandler
netwerk/base/nsiprotocolhandler.idlscriptable this interface is used to implement protocol handlers. if you wish to create a new protocol handler, you need to implement this interface. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview boolean allowport(in long port, in string scheme); nsichannel newchannel(in nsiuri auri); nsiuri newuri(in autf8string aspec, in string aorigincharset, in nsiuri abaseuri); attributes attribute type description defaultport long the default port is the port the protocol uses by default. if the protocol doesn't need a port (for example, the "about" protocol), this attribute is -1. read only. protocolflags un...
...ity_context 1<<4 uris for this protocol have no inherent security context, so documents loaded using this protocol should inherit the security context of the document that loads them. uri_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_anyo...
... uris for this protocol refer to resources that are part of the application's user interface. there are cases in which such resources may be made accessible to untrusted content such as web pages, so this is less restrictive than uri_dangerous_to_load but more restrictive than uri_loadable_by_anyone. uri_is_local_file 1<<9 uris for this protocol from other origins should only be allowed if those origins should have access to the local file system. it's up to the application to decide what origins should have such access. protocols like file that point to local data should set this flag. uri_loadable_by_subsumers 1<<14 the uris for this protocol can be loaded only by callers with a principal that subsumes this uri. for example, privileged code and websites that ...
...And 3 more matches
nsIWebContentHandlerRegistrar
e thrown. this string must also be of either the http or https schemes. title the title of the handler presented to the user as a string. contentwindow the dom content window from which the method has been called. note: script must execute from same domain as uri or else it will throw permission error. can bypass this by opening about:config and setting preference of gecko.handlerservice.allowregisterfromdifferenthost to true. examples register a webmail service as mailto handler the following code aims to add "outlook.com live mail" to list of webservice handlers. in the image below "gmail" and "yahoo! mail" already exist as webservice handlers. cu.import('resource://gre/modules/services.jsm'); var nsiwchr = cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1...
...ompose&to=%s as a content or protocol handler'permission denied to add http://mail.live.com/secure/start?action=compose&to=%s as a content or protocol handler' when calling method: [nsiwebcontenthandlerregistrar::registerprotocolhandler] if the host names do match then a confirmation like this will be seen: this domain check can be bypassed by setting the preference of gecko.handlerservice.allowregisterfromdifferenthost to true as in this code here: var {classes: cc, interfaces: ci, utils: cu} = components; cu.import("resource://gre/modules/services.jsm"); var nsiwchr = cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"] .getservice(ci.nsiwebcontenthandlerregistrar); var allowregisterfromdifferenthost = services.prefs.getboolpref('gecko.handlerservic...
...sterfromdifferenthost to true as in this code here: var {classes: cc, interfaces: ci, utils: cu} = components; cu.import("resource://gre/modules/services.jsm"); var nsiwchr = cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"] .getservice(ci.nsiwebcontenthandlerregistrar); var allowregisterfromdifferenthost = services.prefs.getboolpref('gecko.handlerservice.allowregisterfromdifferenthost'); if (!allowregisterfromdifferenthost) { services.prefs.setboolpref('gecko.handlerservice.allowregisterfromdifferenthost', true); } var htmlcontentwindow = services.wm.getmostrecentwindow('navigator:browser'); //because we set the preference to true above, we need any window that has a browser, just pass the domwindow and the registerprotocolhandler will get the conte...
...And 3 more matches
nsIXPConnect
currentnativecallcontext nsaxpcnativecallcontextptr read only. deferreleasesuntilaftergarbagecollection prbool ...
.... void initclasses( in jscontextptr ajscontext, in jsobjectptr aglobaljsobj ); parameters ajscontext missing description aglobaljsobj missing description exceptions thrown missing exception missing description initclasseswithnewwrappedglobal() creates a new global object using the given acomobj as the global object. the object will be set up according to the flags (defined below). if you do not pass init_js_standard_classes, then acomobj must implement nsixpcscriptable so it can resolve the standard classes when asked by the js engine. nsixpconnectjsobjectholder initclasseswithnewwrappedglobal( in jscontextptr ajscontext, in nsisupports acomobj, in nsiidref aiid, in nsiprincipal aprincipal, in nsisupports aextraptr, in pruint32 aflags ); parameters ajsc...
...ject. acomobj the native object that represents the global object. aiid the iid used to wrap the global object. aprincipal the principal of the code that will run in this compartment. can be null if not on the main thread. aextraptr must be passed if aprincipal is null. used to separate code from the same principal into different compartments, as for sandboxes. aflags one of the flags below specifying what options this global object wants. return value missing description exceptions thrown missing exception missing description jstovariant() nsivariant jstovariant( in jscontextptr ctx, in jsval value ); parameters ctx missing description value missing description return value missing description exceptions thrown missing exception missing description ...
...And 3 more matches
nsIXULTemplateBuilder
would be used to generate output for their child nodes and so forth. a template builder is attached to a single dom node; this node is called the root node and is expected to contain a xul template element as a direct child. different template builders may be specialized in the manner in which they generate and display the resulting content from the template. the structure of a template is as follows: <rootnode datasources="" ref=""> <template> <queryset> <query></query> <rule> <conditions>...</conditions> <bindings>...</bindings> <action>...</action> </rule> </queryset> </template> </rootnode> the datasources attribute on the root node is used to identify the source of data to be used. the ref attribute is used t...
...ibute on the root node is used to identify the source of data to be used. the ref attribute is used to specify the reference point for the query. the <queryset> element contains a single query and one or more <rule> elements. ...
...query is needed -- in that case the <query> and <rule>s are allowed to be children of the <template> node. the contents of the query are processed by a separate component called a query processor. this query processor is expected to use this query to generate results when asked by the template builder. the template builder then generates output for each result based on the <rule> elements. this allows the query processor to be specific to a particular kind of input data or query syntax, while the template builder remains independent of the kind of data being used. due to this, the query processor will be supplied with the datasource and query which the template builder handles in an opaque way, while the query processor handles these more specifically. results implement the nsixultemplateresu...
...And 3 more matches
Using the clipboard
copy and paste any type of data from your application to the clipboard. three xpcom objects are needed to handle clipboard operations. the first is an object that holds the data to put on the clipboard. the second is the clipboard object. the third is an object which is used to transfer the data from the first object to the clipboard. the clipboard model in mozilla requires you to perform the following steps to copy data: create an xpcom wrapper for the data which you want to put on the clipboard. this is needed because you can put anything on the clipboard from text to images. create a transferring object. this object can be the component @mozilla.org/widget/transferable;1 which implements the interface nsitransferable. initialize the transferring object with the nsiloadcontext obtaine...
... same data. for example, a piece of html can be represented in both its original html form and in plain text. if an application wants to get the data from the clipboard and doesn't understand html, it can use the plain text version. if it does understand html, it can grab that version. the transferring object will hold the clipboard contents until the application has decided what it needs. ...
... // import the services module for future use, if we're not in // a browser window where it's already loaded. components.utils.import('resource://gre/modules/services.jsm'); // create a constructor for the built-in supports-string class. ...
...And 3 more matches
Weak reference
sures. there are less severe situations. a naive design for an observer/observable relationship would require the observable to hold a owning reference to the observer. after all, the observable must send messages to each observer, notifying it of the appropriate state changes. to do that, it will call a method on the observer, so it needs a pointer. and the call would fail if the pointer were allowed to dangle, therefore, the pointer should be a owning reference. this design, however, is flawed, as it holds the observer in existence longer than would otherwise be necessary. the observer may only need a short life compared to the thing being observed. it might go away after the first interesting event, even. but in this design, by hitching its life to the observable, it is kept on life-suppo...
... the thing being observed. it might go away after the first interesting event, even. but in this design, by hitching its life to the observable, it is kept on life-support long past any need or use. what is actually needed in this case, is either out-of-band signaling, where when the observer wants to go away, it unregisters itself from the observable, which then releases its owning reference, allowing the observer to die, or else a new kind of reference. this document describes an implementation ofweak references. a weak reference does not hold its referent in existence, but also will not dangle. when the referent is destroyed, the weak reference automatically becomes nsnull. this technique can significantly simplify certain relationships, and you should consider it when an owning reference...
...o_getweakreference(afooptr); // ... { // ...but to use my weak reference, i'll need a (short-lived) owning reference nscomptr<nsifoo> tempfooptr = do_queryreferent(weakptr); if ( tempfooptr ) tempfooptr->somefoomethod(...); // else, the `real' object has gone away } in a real world example, however, you are more likely to be holding a weak reference in a member variable. in the following example, an nsobservable must keep some kind of a reference to each observer, in order to report events. the nsobservable doesn't want to keep the observers alive just to prevent a dangling pointer, however. so, instead of holding an owning reference to an nsiobserver, it holds a weak reference. the weak reference doesn't artificially extend the life of the observer, and yet, it can never dang...
...And 3 more matches
Int64
e 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 value cannot be...
...'s not a number, string, or 64-bit integer object, or it's a string that is incorrectly formatted or contains a value outside the range that can be represented in 64 bits. this will also be thrown if the source value is a floating-point number that can't be precisely represented as a 64-bit integer. method overview number compare(a, b); number hi(a); int64 join(high, low); number lo(a); string tosource(); string tostring([radix]); methods compare() compares two 64-bit integer values. number compare( a, b ); parameters a the first value to compare. b the second value to compare. return value the returned value is: -1 if a < b, 0 if a == b, and 1 if a > b. exceptions thrown typeerror one or both of the s...
... of the specified values is not a 64-bit integer (either signed or unsigned). hi() returns the high 32 bits of the specified value. number hi( num ); parameters num the value whose high 32 bits are to be returned. return value the high 32 bits of num are returned. this is essentially num >> 32. exceptions thrown typeerror num is not a 64-bit integer object. ...
...And 3 more matches
UInt64
gers 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 value cannot be...
...s not a number, string, or 64-bit integer object, or it's a string that is incorrectly formatted or contains a value outside the range that can be represented in 64 bits. this will also be thrown if the source value is a floating-point number that can't be precisely represented as a 64-bit integer. method overview number compare(a, b); number hi(a); uint64 join(high, low); number lo(a); string tosource(); string tostring([radix]); methods compare() compares two 64-bit integer values. number compare( a, b ); parameters a the first value to compare. b the second value to compare. return value the returned value is -1 if a < b, 0 if a == b, and 1 if a > b. exceptions thrown typeerror one or both of the specifi...
...the specified values is not a 64-bit integer (either signed or unsigned). hi() returns the high 32 bits of the specified value. number hi( num ); parameters num the value whose high 32 bits are to be returned. return value the high 32 bits of num are returned. this is essentially num >> 32. exceptions thrown typeerror num is not a 64-bit integer object. ...
...And 3 more matches
DOM Inspector internals - Firefox Developer Tools
the inspected document, and the other panel reacts to changes to the selection in the first panel. these are the document panel and the object panel, respectively. (internally, a panel may be loosely referred to as a "pane", but a panelset is always referred to as a "panelset".) a panel's purpose is to manage available viewers. at the top of each panel is a toolbar which contains a menu button allowing you to choose which viewer to display from the viewer list, a label displaying the name of the currently active viewer, and another menu button allowing you to issue viewer-specific commands. viewers are dynamically loaded; when the panel is made to switch from one viewer to another, the old viewer is destroyed, and the new viewer is loaded in its place. in this way, the panelset and panels f...
... when the panel is made to switch from one viewer to another, the old viewer is destroyed, and the new viewer is loaded in its place. in this way, the panelset and panels function like a frameset and frames. this comparison turns out to be quite apt, since each panel actually contains an anonymous browser, and individual viewers exist in separate documents loaded in the browser. this separation allows for viewers to be self-contained, with a viewer's xul defined in its own document and loaded in its own scope, without fear of collisions in the xul, css, or js. another convenient consequence of this is that if you use a properly set up development profile, then for the most part, the effects of development changes can be seen by simply switching away from the current viewer and back. knowing ...
.../ js/ inspector-cmdline.js makefile.in build/ install.js makefile.in resources/ content/ … locale/ … skin/ … makefile.in install.rdf jar.mn makefile.in makefiles.sh almost all the interesting stuff is in resources/content/. ...
...And 3 more matches
Set a breakpoint - Firefox Developer Tools
oint that can be set in the debugger; this article covers standard (unconditional) breakpoints and conditional breakpoints. breakpoints in brief breakpoints are very useful when debugging javascript — you basically set a point in your code where you would like execution of the code to pause. ...
... add log: add a log point, which logs a value to your console rather than pausing execution as a breakpoint does. ...
... add log: add a log point, which logs a value to your console rather than pausing execution as a breakpoint does. continue to here: when stepping through code, this option tells the debugging to continue execution through to this point. unconditional breakpoints an unconditional breakpoint is one where the code will always pause execution when it is reached. ...
...And 3 more matches
Debugger.Source - Firefox Developer Tools
ed 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 code”, respectively. if...
...vascript 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 code”, respectively. if the behavior does not differ, no such emphasized headings will appear. accessor properties of the debugger.source prototype object a debugger.source instance inherits the following accessor properties from its prototype: text if the instance refers to javascript source, the javascript source code, as a string. the value satisfies the program, functiondeclaration, or functionexpression productions in the ecmascript standard. if the instance refers to webassembly code, the serialized text representation. the format is yet to be specified in the webassembly standard...
...t source code, as a string. the value satisfies the program, functiondeclaration, or functionexpression productions in the ecmascript standard. if the instance refers to webassembly code, the serialized text representation. the format is yet to be specified in the webassembly standard. currently, the text is an s-expression based syntax. the text generation is disabled if the debugger has the allowwasmbinarysource property set, the "[wasm]" value will be returned in this case. binary if the instance refers to webassembly code and the debugger has the allowwasmbinarysource property set, a uint8array that contains the webassembly bytecode. url if the instance refers to javascript source, the filename or url from which this script’s code was loaded. for scripts created by eval or the...
...And 3 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. 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 me...
... 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 objects, and retain about 21% and 8% of the total size of the memory snapshot, respectively. you can also see that these ob...
... 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 objects, and retain about 21% and 8% of the total size of the memory snapshot, respectively. you can also see that these objects have a relatively tiny "shallow size", so almost all of the retained size is in the objects that they dominate. immediately under each gc root, you'll see all the nodes for which this root is the immediate dominator. these nodes are also ordered by their retained size. for example, if we click on the first window object: we can see that this window dominates a css2properties object, whose retained size is 2% of the total s...
...And 3 more matches
Responsive Design Mode - Firefox Developer Tools
r not responsive design mode simulates touch events. while touch event simulation is enabled, mouse events are translated into touch events; this includes (starting in firefox 79) translating a mouse-drag event into a touch-drag event. (note that when touch simulation is enabled, this toolbar icon is blue; when simulation is disabled, it is black. ...
...use-drag event into a touch-drag event. (note that when touch simulation is enabled, this toolbar icon is blue; when simulation is disabled, it is black. on the right end of the screen, three buttons allow you to: camera button - take a screenshot settings button - opens the rdm settings menu close button - closes rdm mode and returns to regular browsing the settings menu includes the following commands: left-align viewport - when checked moves the rdm viewport to the left side of the browser window show user agent - when checked displays the user agent string the final two options define when the page is reloaded: reload when touch simulation is toggled: when this option is enabled, the page is reloaded whenever you toggle touch support. reload when user agent is cha...
...an show or hide the developer tools toolbox independently of toggling responsive design mode itself: while responsive design mode is enabled, you can continue browsing as you normally would in the resized content area. device selection just above the viewport there is a label "no device selected"; click this to see a list of device names. select a device, and responsive design mode sets the following properties to match the selected device: screen size device pixel ratio (the ratio of device physical pixels to device-independent pixels) touch event simulation additionally, firefox sets the user-agent http request header to identify itself as the default browser on the selected device. for example, if you've selected an iphone, then firefox identifies itself as safari. the navigator.
...And 3 more matches
about:debugging - Firefox Developer Tools
on the this firefox tab, but instead of displaying information for your computer, it displays the information for the remote device with the addition of a tabs section with an entry for each of the tabs open on the remote device. note: if the version of firefox on your remote device is more than one major version older than the version running on your computer, you may see a message like the following: in firefox 76 and above, the message can look like the following: see connection for firefox for android 68 for more information. in the image above, there are three tabs open: network or cache recipe, nightly home, and about nightly. to debug the contents of one of these tabs, click the inspect button next to its title. when you do, the developer tools open in a new tab. above the ...
...he browsing history with the back and forward buttons. connecting over the network you can connect to a firefox debug server on your network, or on your debugging machine using the network location settings of the about:debugging page. enter the location and port on which the debugger server is running. when you do, it is added to the network locations list along with the devices, as shown below: this firefox the this firefox tab combines the features of extensions, tabs, and workers into a single tab with the following sections: temporary extensions displays a list of the extensions that you have loaded using the load temporary add-on button. extensions this section lists information about the extensions that you have installed on your system. service workers, shared workers,...
... firefox. the major advantages of this method, compared with installing an add-on from an xpi, are: you don't have to rebuild an xpi and reinstall when you change the add-on's code; you can load an add-on without signing it and without needing to disable signing. once you have loaded a temporary extension, you can see information about it and perform operations on it. you can use the following buttons: inspect loads the extension in the debugger. reload reloads the temporary extension. this is handy when you have made changes to the extension. remove unloads the temporary extension. other information about the extension is displayed: location the location of the extension's source code on your local system. extension id the temporary id assigned to the extension. in...
...And 3 more matches
CSS Painting API - Web APIs
you can then apply these values to properties like background-image to set complex custom backgrounds on an element. for example: aside { background-image: paint(mypaintedimage); } the api defines paintworklet, a worklet that can be used to programmatically generate an image that responds to computed style changes. ...
...ary providing a subset of canvasrenderingcontext2d settings. examples to draw directly into an element's background using javascript in our css, we define a paint worklet using the registerpaint() function, tell the document to include the worklet using the paintworklet addmodule() method, then include the image we created using the css paint() function. ...
...s to draw directly into an element's background using javascript in our css, we define a paint worklet using the registerpaint() function, tell the document to include the worklet using the paintworklet addmodule() method, then include the image we created using the css paint() function. ...
...And 3 more matches
Constraint validation API - Web APIs
however, you may want to impose more complex constraints, or to provide clearer reporting of validation failures than the defaults. this can be done using the constraint validation api. ...
... form control element can have, with respect to its defined constraints. together, they help explain whether and why an element's value fails to validate. invalid event this event type is fired at a form control element if the element does not satisfy its constraints. ...
... custom error message string to be shown to the user upon submitting the form, explaining why the value is not valid — when a message is set, the validity state is set to invalid. to clear this state, invoke the function with an empty string passed as its argument. in this case the custom error message is cleared, the element is considered valid, and no message is shown. examples take the following form: <form> <label for="name">enter username (upper and lowercase letters): </label> <input type="text" name="name" id="name" required pattern="[a-za-z]+"> <button>submit</button> </form> the basic html form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the pattern. i...
...And 3 more matches
Element.scrollWidth - Web APIs
the scrollwidth value is equal to the minimum width the element would require in order to fit all the content in the viewport without using a horizontal scrollbar. 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. ...
...tal scrollbar, its scrollwidth is equal to clientwidth this property will round the value to an integer. if you need a fractional value, use element.getboundingclientrect(). syntax var xscrollwidth = element.scrollwidth; xscrollwidth is the width of the content of element in pixels. ...
...ty will round the value to an integer. if you need a fractional value, use element.getboundingclientrect(). syntax var xscrollwidth = element.scrollwidth; xscrollwidth is the width of the content of element in pixels. ...
...And 3 more matches
Using the Frame Timing API - Web APIs
nce 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 specified when the observer was created. creating an observer to observe "frame" performance entry types, the application first creates a performanceobserv...
...nce 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 specified when the observer was created. creating an observer to observe "frame" performance entry types, the application first creates a performanceobserver object with a specific frame observer callback. in the following example, two observers for the "frame" performance entry type are created and the first observer constructor uses inline function syntax. function create_frame_observer() { if (window.performanceobserver === undefined) return; // register the performance observer var observe_frame = new performanceobserver(function(list) { // log the frame entries var perfentries = list.getentr...
....log("obs #2: [" + i + "] = " + perfentries[i].name); } } <body onload="init(event)"> when the browser adds a new "frame" entry to the performance timeline, both of the observer callbacks will be invoked. registering for notifications after an observer is created, the next step is to use the performanceobserver.observe() method to specify the set of performance events to observe. ...
...And 3 more matches
Using the Gamepad API - Web APIs
e 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 be returned if there are no gamepads connected.) this can then be used to get the same information. for example, the first code example above you be rewritten as shown below: window.addeventlistener("gamepadconnected", function(e) { var gp = navigator.getgamepads()[e.gamepad.index]; console.log("gamepad connected at index %d: %s. %d buttons, %d axes.", gp.index, gp.id, gp.buttons.length, gp.axes.length); }); the gamepad object's properties are as follows: id: a string containing some information about the controller. this is not strictly specified, b...
... index: an integer that is unique for each gamepad currently connected to the system. this can be used to distinguish multiple controllers. note that disconnecting a device and then connecting a new device may reuse the previous index. ...
...n many modern gamepads. the values are normalized to the range 0.0..1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed. axes: 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 tha...
...And 3 more matches
HTMLFormElement - Web APIs
the htmlformelement interface represents a <form> element in the dom. it allows access to—and, in some cases, modification of—aspects of the form, as well as access to its component elements. ...
... the htmlformelement interface represents a <form> element in the dom. it allows access to—and, in some cases, modification of—aspects of the form, as well as access to its component elements. ...
...bmitted. also available via the onsubmit property. usage notes obtaining a form element object to obtain an htmlformelement object, you can use a css selector with queryselector(), or you can get a list of all of the forms in the document using its forms property. document.forms returns an array of htmlformelement objects listing each of the forms on the page. 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...
...And 3 more matches
HTMLImageElement.alt - Web APIs
be able to replace the image without altering the meaning of the page. you should never use alt for text that could be construed as a caption or title. there are separate attributes and elements designed for those purposes. examples beyond that, there are additional guidelines for using alt appropriately which vary depending on what the image is being used for. these are shown in the examples below. ...
...s beyond that, there are additional guidelines for using alt appropriately which vary depending on what the image is being used for. these are shown in the examples below. decorative images images with no semantic meaning—such as those which are solely decorative—or of limited informational value, should have their alt attributes set to the empty string (""). this is shown in the example below. html in the html for this example, shown below, the <img> element includes the alt property, which will prevent the image from having any alternate text, since it's simply a decorational detail. <div class="container"> <div class="left-margin"> <img src="/files/16861/margin-flourish.svg" alt=""> </div> <div class="contents"> <p>lorem ipsum dolor sit amet, consectetur adipiscing ...
...r rhoncus elit eget porta. etiam pulvinar ex id sapien laoreet, quis aliquet odio lobortis. nam ac mauris at risus laoreet cursus vitae et sapien. etiam molestie auctor eros, ac porta risus scelerisque sit amet. ut nunc neque, porta eu auctor at, tempor et arcu.</p> </div> </div> css the css for this example simply sets up the styles for the layout as shown in the result below. they're not crucial to the concept shown in the html above, but you may expand the view below if you wish to read the css used. view the css editors: if you change the css below, please be sure to close the details box using the toggle at the top of the css view before saving. otherwise, readers will find it open by default, which is not the intent here. body { margin: 0; padding: 0; } p...
...And 3 more matches
HTMLTableCellElement - Web APIs
element interface provides special properties and methods (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of table cells, either header or data cells, in an html document. ...
... header cells can be configured, using the scope property, the apply to a specified row or column, or to the not-yet-scoped cells within the current row group (that is, the same ancestor <thead>, <tbody>, or <tfoot> element). if no value is specified for scope, the header is not associated directly with cells in this way. ...
... this way. permitted values for scope are: col the header cell applies to the following cells in the same column (or columns, if colspan is used as well), until either the end of the column or another <th> in the column establishes a new scope. colgroup the header cell applies to all cells in the current column group that do not already have a scope applied to them. this value is only allowed if the cell is in a column group. row the header cell applies to the following cells in the same row (or rows, if rowspan is used as well), until either the end of the row or another <th> in the same row establishes a new scope. ...
...And 3 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
e javascript runtime operates under the hood that may be useful to understand. that's what this section covers introduction javascript is an inherently single-threaded language. ...
...uld be handled by javascript was relatively low at that time. as time passed, of course, we know that computers have evolved into powerful multi-core systems, and javascript has become one of the most prolifically-used languages in the computing world. a vast number of the most popular applications are based at least in part on javascript code. to support this, it was necessary to find ways to allow for projects to escape the limitations of a single-threaded language. starting with the addition of timeouts and intervals as part of the web api (settimeout() and setinterval()), the javascript environment provided by web browsers has gradually advanced to include powerful features that enable scheduling of tasks, multi-threaded application development, and so forth. to understand where queuemi...
...n execution context. this is frequently referred to as a "local context." using the ill-advised eval() function also creates a new execution context. each context is, in essence, a level of scope within your code. as one of these code segments begins execution, a new context is constructed in which to run it; that context is then destroyed when the code exits. ...
...And 3 more matches
Recommended Drag Types - Web APIs
d to refer to the first valid link within data for the text/uri-list type. do not add data with the url type — attempting to do so will set the value of the text/uri-list type instead. var url = event.datatransfer.getdata("url"); you may also see data with the mozilla-specific type text/x-moz-url. if it appears, it should appear before the text/uri-list type. it holds the urls of links followed by their titles, separated by a linebreak. for example: http://www.mozilla.org mozilla http://www.example.com example dragging html and xml html content may use the text/html type. the data for this type should be serialized html source code. for example, it would be suitable to set its data to the value of the innerhtml property of an element. xml content may use the text/xml type, but en...
...x-moz-file", file, 0); if possible, include the file url of the file using both the text/uri-list and text/plain types. these types should be added afterward so that the more specific application/x-moz-file type has higher priority. multiple files will be received during a drop as multiple items in the data transfer. see dragging and dropping multiple items for more details about this. ...
... and added a non-file for this type. updates to datatransfer.types the latest spec dictates that datatransfer.types should return 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...
...And 3 more matches
IDBDatabase.transaction() - Web APIs
"durability" -- the durability constrints for the transction. valid values are: "default", "strict", and "relaxed". storenames the names of object stores that are in the scope of the new transaction, declared as an array of strings. specify only the object stores that you need to access. if you need to access only one object store, you can specify its name as a string. therefore the following lines are equivalent: var transaction = db.transaction(['my-store-name']); var transaction = db.transaction('my-store-name'); if you need to access all object stores in the database, you can use the property idbdatabase.objectstorenames: var transaction = db.transaction(db.objectstorenames); passing an empty array will throw an exception. mode optional the types of access that can ...
...ction(db.objectstorenames); passing an empty array will throw an exception. mode optional the types of access that can be performed in the transaction. transactions are opened in one of three modes: readonly, readwrite and readwriteflush (non-standard, firefox-only.) versionchange mode can't be specified here. if you don't provide the parameter, the default access mode is readonly. ...
...s: readonly, readwrite and readwriteflush (non-standard, firefox-only.) versionchange mode can't be specified here. if you don't provide the parameter, the default access mode is readonly. to avoid slowing things down, don't open a readwrite transaction unless you actually need to write into the database. if you need to open the object store in readwrite mode to change data, you would use the following: var transaction = db.transaction('my-store-name', "readwrite"); as of firefox 40, indexeddb transactions have relaxed durability guarantees to increase performance (see bug 1112702), which is the same behaviour as other indexeddb-supporting browsers. previously in a readwrite transaction idbtransaction.oncomplete was fired only when all data was guaranteed to have been flushed to disk. in ...
...And 3 more matches
IDBIndexSync - Web APIs
hin the index; if false, a key can have duplicate values. methods add() stores the given value into this index, optionally with the specified key. if a record already exists with the given key, an exception is raised. any add( in any value, in optional any key ) raises (idbdatabaseexception); parameters returns exceptions this method can raise a idbdatabaseexception with the following code: value the value to store into the index. key a key to use for identifying the record. any the key for the stored record. constraint_err if a record exists in this index with a key corresponding to the key parameter or the index is auto-populated, or if no record exists with a key corresponding to the value parameter in the index's referenced object store. get() retrieves the...
...arameter in the index's referenced object store. get() retrieves the value from this index for the record that corresponds to the given key. any get ( in any key ) raises (idbdatabaseexception); parameters key the key that identifies the record to be retrieved. returns any the retrieved value from the index. exceptions this method can raise an idbdatabaseexception with the following code: not_found_err if no record exists in this index for the given key. getobject() retrieves and returns the value from this index's referenced object store that corresponds to the given key. any getobject ( in any key ) raises (idbdatabaseexception); parameters key the key that identifies the record to be retrieved. returns any the retrieved value from the referenced o...
...etobject() retrieves and returns the value from this index's referenced object store that corresponds to the given key. any getobject ( in any key ) raises (idbdatabaseexception); parameters key the key that identifies the record to be retrieved. returns any the retrieved value from the referenced object store. exceptions this method can raise a idbdatabaseexception with the following code: not_found_err if no record exists in this index for the given key. opencursor() creates a cursor over the records of this index. the range of the new cursor matches the specified key range; if the key range is not specified or is null, then the range includes all the records. void opencursor ( in optional idbkeyrange range, in optional unsigned short direction ) raises (idbda...
...And 3 more matches
IDBKeyRange.includes() - Web APIs
includes() method of the idbkeyrange interface returns a boolean indicating whether a specified key is inside the key range. note: this feature is available in web workers. syntax var isincluded = mykeyrange.includes(key) parameters key the key you want to check for in your key range. this can be any type. return value a boolean. exceptions this method may raise a domexception of the following type: attribute description dataerror the supplied key was not a valid key. example var keyrangevalue = idbkeyrange.bound('a', 'k', false, false); var myresult = keyrangevalue.includes('f'); // returns true var myresult = keyrangevalue.includes('w'); // returns false polyfill the includes() method was added in the second edition of the indexed db specifica...
... dataerror the supplied key was not a valid key. example var keyrangevalue = idbkeyrange.bound('a', 'k', false, false); var myresult = keyrangevalue.includes('f'); // returns true var myresult = keyrangevalue.includes('w'); // returns false polyfill the includes() method was added in the second edition of the indexed db specification. ...
...yresult = keyrangevalue.includes('f'); // returns true var myresult = keyrangevalue.includes('w'); // returns false polyfill the includes() method was added in the second edition of the indexed db specification. for browsers that do not support it, the following polyfill can be used. ...
...And 3 more matches
IDBObjectStore.createIndex() - Web APIs
the createindex() method of the idbobjectstore interface creates and returns a new idbindex object in the connected database. it creates a new field/column defining a new data point for each database record to contain. bear in mind that indexeddb indexes can contain any javascript data type; indexeddb uses the structured clone algorithm to serialize stored objects, which allows for storage of simple and complex objects. note that this method must be called only from a versionchange transaction mode callback. note: this feature is available in web workers. syntax var myidbindex = objectstore.createindex(indexname, keypath); var myidbindex = objectstore.createindex(indexname, keypath, objectparameters); parameters indexname the name of the index to create. note that it is possible...
...ypath, objectparameters); parameters indexname the name of the index to create. note that it is possible to create an index with an empty name. keypath the key path for the index to use. note that it is possible to create an index with an empty keypath, and also to pass in a sequence (array) as a keypath. objectparameters optional an idbindexparameters object, which can include the following properties: attribute description unique if true, the index will not allow duplicate values for a single key. multientry if true, the index will add an entry in the index for each array element when the keypath resolves to an array. if false, it will add one single entry containing the array. locale currently firefox...
...any sorting operations performed on the data via key ranges will then obey sorting rules of that locale (see locale-aware sorting.) you can specify its value in one of three ways: string: a string containing a specific locale code, e.g. en-us, or pl. ...
...And 3 more matches
KeyboardEvent - Web APIs
eyboardevent objects describe a user interaction with the keyboard; each event describes a single interaction between the user and a key (or combination of a key with modifier keys) on the keyboard. the event type (keydown, keypress, or keyup) identifies what kind of keyboard activity occurred. note: keyboardevent events just indicate what interaction the user had with a key on the keyboard at a low level, providing no contextual meaning to that interaction. when you need to handle text input, use the input event instead. keyboard events may not be fired if the user is using an alternate means of entering text, such as a handwriting system on a tablet or graphics tablet. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.66666666...
... to that interaction. when you need to handle text input, use the input event instead. keyboard events may not be fired if the user is using an alternate means of entering text, such as a handwriting system on a tablet or graphics tablet. ...
... stroke-width="2px" /><text x="296" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">keyboardevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor keyboardevent() creates a new keyboardevent object. constants the keyboardevent interface defines the following constants. keyboard locations the following constants identify which part of the keyboard the key event originates from. they are accessed as keyboardevent.dom_key_location_standard and so forth. keyboard location identifiers constant value description dom_key_location_standard 0x00 the key described by the event is not identified as being located in ...
...And 3 more matches
MediaTrackConstraints - Web APIs
for each constraint, you can typically specify an exact value you need, an ideal value you want, a range of acceptable values, and/or a value which you'd like to be as close to as possible. ...
...n typically specify an exact value you need, an ideal value you want, a range of acceptable values, and/or a value which you'd like to be as close to as possible. the specifics vary somewhat depending on the type of the constrainable property. to learn more about how constraints work, see capabilities, constraints, and settings. properties some combination—but not necessarily all—of the following properties will exist on the object. this may be because a given browser doesn't support the property, or because it doesn't apply. for example, because rtp doesn't provide some of these values during negotiation of a webrtc connection, a track associated with a rtcpeerconnection will not include certain values, such as facingmode or groupid. properties of all media tracks deviceid a cons...
...es which are acceptable and/or required. height a constrainlong specifying the video height or range of heights which are acceptable and/or required. width a constrainlong specifying the video width or range of widths which are acceptable and/or required. resizemode a constraindomstring object specifying a mode or an array of modes the ua can use to derive the resolution of a video track. allowed values are none and crop-and-scale. none means that the user agent uses the resolution provided by the camera, its driver or the os. crop-and-scale means that the user agent can use cropping and downscaling on the camera output in order to satisfy other constraints that affect the resolution. properties of shared screen tracks these constraints apply to mediatrackconstraints objects specifi...
...And 3 more matches
PaymentRequest.PaymentRequest() - Web APIs
equest object which will be used to handle the process of generating, validating, and submitting a payment request. syntax var paymentrequest = new paymentrequest(methoddata, details, [options]); parameters methoddata contains an array of identifiers for the payment methods the merchant web site accepts and any associated payment method specific data. each item in the array contains the following fields: supportedmethods for early implementations of the spec, this was a sequence of identifiers for payment methods that the merchant website accepts. starting with more recent browsers, this parameter is more generic than credit cards, it is a single domstring, and the meaning of the data parameter changes with the supportedmethods. for example, the basic card payment method is selec...
...on-serializable object that provides optional information that might be needed by the supported payment methods. this has to conform to the type expected by the payment handler indicated by supportedmethods. for basic credit card services, this structure should match the basiccardrequest dictionary. details provides information about the requested transaction. this parameter contains the following fields: total the total amount of the payment request. id optional a free-form identifier for this payment request. if a value is not supplied, the browser will construct one. displayitems an array of optional line items for the payment request that the user agent may display, such as product details, tax, and shipping. shippingoptions the shipping options the user may choose...
...ax, and shipping. shippingoptions the shipping options the user may choose from. if this sequence is blank, it indicates the merchant cannot ship to the current shipping address. the default shipping option may be indicated in this sequence. modifiers modifiers for specific payment methods; for example, adjusting the total amount based on the payment method. this parameter contains the following fields: additionaldisplayitems an array of items to be appended to the details.displayitems property. this property is commonly used to add a discount or surcharge line item indicating the different amount in details.modifiers.total. data a json-serializable object that provides optional information that might be needed by the supported payment methods. this has to conform to th...
...And 3 more matches
Using the Permissions API - Web APIs
3c permissions api, which provides a programmatic way to query the status of api permissions attributed to the current context. the trouble with asking for permission... let's face it, permissions on the web are a necessary evil, and they are not much fun to deal with as developers. 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, as we'll see below). the permissions api provides the tools to allow developers to implement a better user experience as far as permissions are concerned. for example, it can query whether permission to use a particul...
...th firefox also recognizing push and webmidi. more features will be added as time progresses. a simple example for this article, we have put together a simple demo called location finder. it uses geolocation to query the user's current location and plot it out on a google map: you can run the example live, or view the source code on github. most of the code is simple and unremarkable — below we'll just be walking through the permissions api-related code, so check the code yourself if you want to study any of the other parts. accessing the permissions api the navigator.permissions property has been added to the browser to allow access to the global permissions object. this object will eventually include methods for querying, requesting, and revoking permissions, although currently i...
... querying permission state in our example, the permissions functionality is handled by one function — handlepermission(). this starts off by querying the permission status using permissions.query(). ...
...And 3 more matches
Using Pointer Events - Web APIs
rface a touch-sensitive surface. this may be a trackpad, a touch screen, or even a virtual mapping of a user's desk surface (or mousepad) with the physical screen. touch point a point of contact with the surface. this may be a finger (or elbow, ear, nose, whatever, but typically a finger), stylus, mouse, or any other method for specifying a single point on the surface. example the text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus, mouse, or other method of pointing at a location. create a canvas the touch-action property is set to none to prevent the browser from applying its default touch behavior to the application. <canvas id="canvas" width="600" height="600" style="border:solid black 1px; touch-action:none...
... default touch behavior to the application. <canvas id="canvas" width="600" height="600" style="border:solid black 1px; touch-action:none"> your browser does not support canvas element. </canvas> <br> <button onclick="startup()">initialize</button> <br> log: <pre id="log" style="border: 1px solid #ccc;"></pre> setting up the event handlers when the page loads, the startup() function shown below should be called by our <body> element's onload attribute (but in the example we use a button to trigger it, due to limitations of the mdn live example system). function startup() { var el = document.getelementsbytagname("canvas")[0]; el.addeventlistener("pointerdown", handlestart, false); el.addeventlistener("pointerup", handleend, false); el.addeventlistener("pointercancel", handlecanc...
...ntermove", handlemove, false); log("initialized."); } this simply sets up all the event listeners for our <canvas> element so we can handle the touch events as they occur. tracking new touches we'll keep track of the touches in-progress. var ongoingtouches = new array(); when a pointerdown event occurs, indicating that a new touch on the surface has occurred, the handlestart() function below is called. function handlestart(evt) { log("pointerdown."); var el = document.getelementsbytagname("canvas")[0]; var ctx = el.getcontext("2d"); log("pointerdown: id = " + evt.pointerid); ongoingtouches.push(copytouch(evt)); var color = colorfortouch(evt); ctx.beginpath(); ctx.arc(touches[i].pagex, touches[i].pagey, 4, 0, 2 * math.pi, false); // a circle at the start ctx.arc(e...
...And 3 more matches
RTCPeerConnection - Web APIs
erconnection interface represents a webrtc connection between the local computer and a remote peer. it provides methods to connect to a remote peer, maintain and monitor the connection, and close the connection once it's no longer needed. ...
...this lets you change the ice servers used by the connection and which transport policies to use.se...
...ion. this description specifies the properties of the local end of the connection, including the media format.setremotedescription()the rtcpeerconnection method setremotedescription() sets the specified session description as the remote peer's current offer or answer. the description specifies the properties of the remote end of the connection, including the media format. obsolete method the following method was obsoleted long ago and was never implemented in all major browsers. rtcpeerconnection.createdtmfsender() creates a new rtcdtmfsender, associated to a specific mediastreamtrack, that will be able to send dtmf phone signaling over the connection. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interf...
...And 3 more matches
SVGTransform - Web APIs
(0, 0), e and f will be zero. methods name & arguments return description setmatrix(in svgmatrix matrix) void sets the transform type to svg_transform_matrix, with parameter matrix defining the new transformation. note that the values from the parameter matrix are copied. ...
...eption with code no_modification_allowed_err is raised when attempting to modify a read only attribute or when the object itself is read only. settranslate(in float tx , in float ty) void sets the transform type to svg_transform_translate, with parameters tx and ty defining the translation amounts. exceptions: a domexception with code no_modification_allowed_err is raised when attempting to modify a read only attribute or when the object itself is read only. setscale(in float sx , in float sy) void sets the transform type to svg_transform_scale, with parameters sx and sy defining the scale amounts. ...
... a domexception with code no_modification_allowed_err is raised when attempting to modify a read only attribute or when the object itself is read only. setscale(in float sx , in float sy) void sets the transform type to svg_transform_scale, with parameters sx and sy defining the scale amounts. exceptions: a domexception with code no_modification_allowed_err is raised when attempting to modify a read only attribute or when the object itself is read only. setrotate(in float angle, in float cx , in float cy) void sets the transform type to svg_transform_rotate, with parameter angle defining the rotation angle and parameters cx and cy defining the optional center of rotation. exceptions: a domexception ...
...And 3 more matches
Screen Wake Lock API - Web APIs
s 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. ...
...ful. 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 applications that use voice or gesture control, rather than tactile input (the default way to keep a screen awake). you acquire a wakelocksentinel object by calling the navigator.wakelock.request() promise based method that resolves if the platform allows it. a request may be rejected for a number of reasons, including system setti...
...udience, scanning a qr/barcode or applications that use voice or gesture control, rather than tactile input (the default way to keep a screen awake). you acquire a wakelocksentinel object by calling the navigator.wakelock.request() promise based method that resolves if the platform allows it. a request may be rejected for a number of reasons, including system settings (such as power save mode or low battery level) or if the document is not active or visible. the sentinel is attached to the underlying system wake lock. it can be released by the system, again if the battery power is too low or the document is not active or visible. it can also be released manually via the wakelocksentinel.release() method. it is good practice to store a reference to the sentinel object to control release late...
...And 3 more matches
Using the User Timing API - Web APIs
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. ...
...nd bug reports are welcome. performance marks a performance mark is a named performance entry that is created by the application at some location in an application. the mark is a timestamp in the browser's performance timeline. creating a performance mark the performance.mark() method is used to create a performance mark. the method takes one argument, the name of the mark, as shown in the following example. function create_marks(ev) { if (performance.mark === undefined) { log("create marks: performance.mark not supported", 0); return; } else { log("create marks", 0); // create several performance marks including two with the same name performance.mark("mark-1"); do_work(50000); performance.mark("mark-2"); do_work(50000); performance.mark("mark-2"); var marks ...
...marks including two with the same name performance.mark("mark-1"); do_work(50000); performance.mark("mark-2"); do_work(50000); performance.mark("mark-2"); var marks = ["mark-1", "mark-2", "mark-2"]; for (var i=0; i < marks.length; i++) log("... created mark = " + marks[i], 0); } retrieving performance marks the performance interface has three methods to retrieve marks. the following examples shows how to use each of these methods (performance.getentries(), performance.getentriesbytype(entrytype), and performance.getentriesbyname(name, entrytype) ) to retrieve one or more marks. function display_marks(ev) { if (performance.getentries === undefined) { log("display marks: performance.getentries not supported", 0); return; } log("display marks", 0); // displ...
...And 3 more matches
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
t isn't adequate for the purposes of fully managing users, memberships, permissions, and so forth, but provides the basics needed for an unrestricted multi-user communication session. the very fact that rtcp is defined in the same rfc as rtp is a clue as to just how closely-interrelated these two protocols are. capabilities of rtp rtp's primary benefits in terms of webrtc include: generally low latency. packets are sequence-numbered and time-stamped for reassembly if they arrive out of order. this lets data sent using rtp be delivered on transports that don't guarantee ordering or even guarantee delivery at all. this means rtp can be — but is not required to be — used atop udp for its performance as well as its multiplexing and checksum features. rtp supports multicast; while thi...
...c. 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 does not guarantee quality-of-service (qos). while rtp is intended for use in latency-critical scenarios, it doesn't inherently offer any features that ensure qos. instead, it only offers the information necessary to allow qos to be implemented elsewhere in the stack. rtp doesn't handle allocation or reservation of resources that may be needed. where it matters for webrtc purposes, these are dealt with in a variety of places within the webrtc infrastructure. for example, rtcp handles qos monitoring. rtcpeerconnection and rtp each rtcpeerconnection has methods which provide access to the list of rtp transports ...
...andle allocation or reservation of resources that may be needed. where it matters for webrtc purposes, these are dealt with in a variety of places within the webrtc infrastructure. for example, rtcp handles qos monitoring. rtcpeerconnection and rtp each rtcpeerconnection has methods which provide access to the list of rtp transports that service the peer connection. these correspond to the following three types of transport supported by rtcpeerconnection: rtcrtpsender rtcrtpsenders handle the encoding and transmission of mediastreamtrack data to a remote peer. the senders for a given connection can be obtained by calling rtcpeerconnection.getsenders(). rtcrtpreceiver rtcrtpreceivers provide the ability to inspect and obtain information about incoming mediastreamtrack data. a connect...
...And 3 more matches
Fundamentals of WebXR - Web APIs
ortunately, 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, is that webxr supports not just virtual reality applications, but also augmented reality, which blends virtual objects with the ...
...he image on a screen. these devices include phones, which show the resulting scene on the device's screen in a 2d presentation, as well as goggles that use a pair of cameras, one for each eye, to capture the scene in stereo in order to retain the world's depth, with the webxr scene then rendered for each eye with that eye's captured background in place. devices which use transparent glasses to allow the user to see the world, while overlaying the rendered image atop the scene. the user is, thus, directly viewing the real world instead of a series of digital photos of it. both types of device should be capable of also presenting vr sessions. webxr doesn't generally care which type of device you're using, and the rendering process is almost exactly the same as for vr, except you don't erase ...
... experiences, see augmented reality with webxr. types of webxr hardware the simplest xr presentation involves rendering the scene directly to the user's screen, either in the context of a web document, or in full screen mode. this is most common when the user either doesn't have a dedicated xr device, or when the user is viewing the ar or vr app on a phone or other handheld device. simpler and lower-priced xr devices typically use an integrated computer or connect to a smartphone, essentially using the mobile cpu and gpu to run apps, render images, and display them to the user. higher-powered solutions typically offload application execution and graphics processing to an external device such as a desktop computer, and are either tethered to the computer using a cable or use a wireless netw...
...And 3 more matches
Using the Web Speech API - Web APIs
nd any future implementations that might support the features without a prefix: var speechrecognition = speechrecognition || webkitspeechrecognition var speechgrammarlist = speechgrammarlist || webkitspeechgrammarlist var speechrecognitionevent = speechrecognitionevent || webkitspeechrecognitionevent the grammar the next part of our code defines the grammar we want our app to recognise. the following variable is defined to hold our grammar: var colors = [ 'aqua' , 'azure' , 'beige', 'bisque', 'black', 'blue', 'brown', 'chocolate', 'coral' ... ]; var grammar = '#jsgf v1.0; grammar colors; public <color> = ' + colors.join(' | ') + ' ;' the grammar format used is jspeech grammar format (jsgf) — you can find a lot more about it at the previous link to its spec. however, for now let's just ...
... the lines are separated by semi-colons, just like in javascript. the first line — #jsgf v1.0; — states the format and version used. this always needs to be included first. the second line indicates a type of term that we want to recognise. public declares that it is a public rule, the string in angle brackets defines the recognised name for this term (color), and the list of items that follow the equals sign are the alternative values that will be recognised and accepted as appropriate values for the term. note how each is separated by a pipe character. you can have as many terms defined as you want on separate lines following the above structure, and include fairly complex grammar definitions. for this basic demo, we are just keeping things simple. plugging the grammar into our s...
...ar it spoken. to run the demo, you can clone (or directly download) the github repo it is part of, open the html index file in a supporting desktop browser, or navigate to the live demo url in a supporting mobile browser like chrome, or firefox os. browser support support for web speech api speech synthesis is still getting there across mainstream browsers, and is currently limited to the following: firefox desktop and mobile support it in gecko 42+ (windows)/44+, without prefixes, and it can be turned on by flipping the media.webspeech.synth.enabled flag to true in about:config. firefox os 2.5+ supports it, by default, and without the need for any permissions. chrome for desktop and android have supported it since around version 33, without prefixes. html and css ...
...And 3 more matches
Window.open() - Web APIs
Web › API › Window › open
d 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 below for documentation of each of the features that can be specified. return value a windowproxy object, which is basically a thin wrapper for the window object representing the newly created window, and has all its features available. if the window couldn't be opened, the returned value is instead null. the returned reference can be used to access properties and methods of the new window as long a...
... (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, or in most cases just omit them, to be off. example: status=yes, status=1, and status have identical results. menubar if this feature is on, then...
...indows. this is in the best interests of both the web author and the users. how do i resize a window to fit its content? you cannot reliably because the users can prevent the window from being resized by setting dom.disable_window_move_resize to true in about:config or by editing accordingly their user.js file. in general, users usually disable moving and resizing of existing windows because allowing authors' scripts to do so has been abused overwhelmingly in the past and the rare scripts that do not abuse such feature are often wrong, inaccurate when resizing the window. 99% of all those scripts disable window resizability and disable scrollbars when in fact they should enable both of these features to allow a cautious and sane fallback mechanism if their calculations are wrong. the wind...
...And 3 more matches
XRReferenceSpace - Web APIs
transform between the tracked object and another location in the world. all reference spaces—with the sole exception being bounded reference spaces—are described using the xrreferencespace type. bounded spaces are implemented as xrboundedreferencespace objects. these are special spaces which let you establish a perimeter within which it's "safe" for the viewer to move. for xr systems that allow the user to physically move around, such as those that track movement with a real-world camera, this boundary establishes the edges of the area the user is able to move around in, whether due to physical obstacles or due to limitations of the xr hardware. see the article using bounded reference spaces to protect the viewer for more on using boundaries to keep the user from colliding with obstacle...
...n to the properties inherited from xrspace (of which there are none at this time), xrreferencespace also inherits the properties of eventtarget. xrreferencespace defines no additional properties. methods in addition to the methods inherited from its parent interface, xrspace (there are none at this time), xrreferencespace inherits methods from eventtarget. xrreferencespace also provides the following methods. getoffsetreferencespace() creates and returns a new reference space object as the same type as the one on which you call the method (so, either xrreferencespace or xrboundedreferencespace). the new reference space can be used to transform a coordinate from the reference space of the object on which the method is called into a different coordinate space. this is useful for positio...
...can be used to transform a coordinate from the reference space of the object on which the method is called into a different coordinate space. this is useful for positioning objects while rendering, and to perform the needed transforms when changing the viewer's position and/or orientation in 3d space. events in addition to other events that may be sent to xrspace or eventtarget objects, the following also apply to xrreferencespace objects. reset the reset event is sent to an xrreferencespace object when the browser detects a discontinuity has occurred wherein the tracked object's origin relative to the user's environment or location. this can happen, for example, after the user recalibrates their xr device, or if the device automatically adjusts its origin after losing and regaining...
...And 3 more matches
Using the slider role - Accessibility
this technique demonstrates how to use the slider role and describes the effect it has on browsers and assistive technology. the slider role is used for markup that allows a user to select a value from within a given range. the slider role is assigned to the "thumb," the control that is adjusted to change the value. as the user interacts with the thumb, the application must programmatically adjust the slider's aria-valuenow (and possible aria-valuetext) attribute to reflect the current value. see the examples section below for more information. ...
...ication must programmatically adjust the slider's aria-valuenow (and possible aria-valuetext) attribute to reflect the current value. see the examples section below for more information. keyboard and focus the slider should be keyboard focusable and operable. when the user tabs focus to the slider, it should land on the thumb: the control a mouse user would drag. arrow keys should operate as follows (localization for right-to-left languages should reverse the direction of the arrows): key(s) action right and up arrows increase the selected value left and down arrows decrease the selected value page up and page down optionally increase and decrease the value by a set amount (e.g. by 10 on a range from 0 to 100) possible effects on u...
... optionally increase and decrease the value by a set amount (e.g. by 10 on a range from 0 to 100) possible effects on user agents and 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: 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. <label for="fader">volume</label> <input type="range" id="fader" min="1" max="100" value="50" step="1" aria-valuemin="1" aria-valuemax="100" aria-valuenow="50" oninput="outputupdate(value)"> <o...
...And 3 more matches
ARIA annotations - Accessibility
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 deletion in an editable document), and comments (e.g. an editorial comment related to a part of a document under review). below we'll introduce the new features associated with aria annotations, and have a look at some code examples that show them in action. note: you can find all the examples discussed in this article in a demo file at aria-annotations. ...
... role="insertion" and role="deletion" — semantically denote html elements whose contents represent an insertion to or deletion from the overall document. ...
...t it can support multiple ids — this makes sense, for example you can easily envisage having multiple comments relating to the same bit of text. aria annotation roles and objects are currently exposed in: firefox from version 75 onwards, on windows and linux (on macos, we are first waiting for apple to define what safari will expose as apple-dialect attributes to voiceover, and will then follow suit.) chrome from version 81 onwards, currently behind the #enable-accessibility-expose-aria-annotations flag (go to chrome://flags to enable this.) unfortunately, you won’t be able to use any of these yet, as screenreader support is currently not there. for the moment, you can see the annotations data being exposed with tools like firefox accessibility inspector. the annotations should jus...
...And 3 more matches
Accessibility: What users can do to browse more safely - Accessibility
disorders, and those who support them, by taking advantage of personalization and accessibility settings built into the operating systems. taking advantage of personalization settings can help prevent exposure to content leading to seizures and / or other physical reactions. personalization and accessibility settings from the article, "understanding success criterion 2.3.1: three flashes or below threshold" "flashing can be caused by the display, the computer rendering the image or by the content being rendered. the author has no control of the first two. they can be addressed by the design and speed 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 opera...
...alization 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 modern browers. learn personalization and accessibility settings firefox 73 and above (dekstop) firefox added support for css prefers-reduced-motion in october 2018. chrome 74 and above (desktop) chrome 74 added supp...
...rn personalization and accessibility settings firefox 73 and above (dekstop) firefox added support for css prefers-reduced-motion in october 2018. chrome 74 and above (desktop) chrome 74 added support for reduced-motion-query, it has even added support to detect whether the user has requested a reduced motion experience. the user would access this through an accessibility interface, as seen below. css transition events are now supported. examples include: transitionrun transitionstart transitionend transitioncancel edge 75 and above (desktop, in windows 10) according to eric bailey, in his april 30, 2019 article revisiting prefers-reduced-motion, the reduced motion media query, "while microsoft edge does not have support for prefers-reduced-motion, it will become chrome under ...
...And 3 more matches
font-weight - CSS: Cascading Style Sheets
the font-weight property can separately be used to set how thick or thin characters in text should be displayed. for a particular font family, authors can download various font faces which correspond to the different styles of the same font family, and then use the font-weight descriptor to explicitly specify the font face's weights. the values for the css descriptor is same as that of its corresponding font property. there are generally limited weights available for a particular font family. when a specified weight doesn't exist, a nearby weight is used. fonts lacking bold are often synthesized by the user agent. ...
...a specified weight doesn't exist, a nearby weight is used. fonts lacking bold are often synthesized by the user agent. to prevent this, use font-synthesis property. syntax /* single values */ font-weight: normal; font-weight: bold; font-weight: 400; /* multiple values */ font-weight: normal bold; font-weight: 300 500; the font-weight property is described using any one of the values listed below. values normal normal font weight. same as 400. bold bold font weight. same as 700. <number> a <number> value between 1 and 1000, inclusive. higher numbers represent weights that are bolder than (or as bold as) lower numbers. certain commonly used values correspond to common weight names, as described in the common weight name mapping section below. in earlier versions of the font-weig...
...e set values, although fine-grained values (e.g. 451) will be translated to one of these values for non-variable fonts. css fonts level 4 extends the syntax to accept any number between 1 and 1000, inclusive, and introduces variable fonts, which can make use of this much finer-grained range of font weights. ...
...And 3 more matches
@media - CSS: Cascading Style Sheets
Web › CSS › @media
aced by speech, which is similar. media features media features describe specific characteristics of the user agent, output device, or environment. media feature expressions test for their presence or value, and are entirely optional. each media feature expression must be surrounded by parentheses. name summary notes any-hover does any available input mechanism allow the user to hover over elements? added in media queries level 4. any-pointer is any available input mechanism a pointing device, and if so, how accurate is it? added in media queries level 4. aspect-ratio width-to-height aspect ratio of the viewport color number of bits per color component of the output device, or zero if the device isn't color ...
...lay mode of the application, as specified in the web app manifest's display member defined in the web app manifest spec. forced-colors detect whether user agent restricts color palette added in media queries level 5. grid does the device use a grid or bitmap screen? height height of the viewport hover does the primary input mechanism allow the user to hover over elements? added in media queries level 4. inverted-colors is the user agent or underlying os inverting colors? added in media queries level 5. light-level light level of the environment added in media queries level 5. monochrome bits per pixel in the output device's monochrome frame buffer, or zero if the device isn't monochrome ...
... inverted-colors is the user agent or underlying os inverting colors? added in media queries level 5. light-level light level of the environment added in media queries level 5. monochrome bits per pixel in the output device's monochrome frame buffer, or zero if the device isn't monochrome orientation orientation of the viewport overflow-block how does the output device handle content that overflows the viewport along the block axis? added in media queries level 4. overflow-inline can content that overflows the viewport along the inline axis be scrolled? added in media queries level 4. pointer is the primary input mechanism a pointing device, and if so, how accurate is it? added in media querie...
...And 3 more matches
Cross-browser Flexbox mixins - CSS: Cascading Style Sheets
.org/tr/css3-flexbox/ http://the-echoplex.net/flexyboxes/ http://msdn.microsoft.com/en-us/library/ie/hh772069(v=vs.85).aspx http://css-tricks.com/using-flexbox/ a complete guide to flexbox | css-tricks visual guide to css3 flexbox: flexbox playground | note: mixins are not currently supported natively in browsers. instead, you will need to use a css pre-processor to make the most of the following. however, css pre-processors simply generate valid css, so the techniques used below can be written in pure css instead, if preferred. flexbox containers using the display property's flex value causes an element to generate a block-level flex container box. the inline-flex value causes an element to generate an inline-level flex container box. values: flex | inline-flex spec: https://dra...
...rmines the direction in which the new lines are stacked in. 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. ...
...ch the new lines are stacked in. 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. ...
...And 3 more matches
Box alignment in CSS Grid Layout - CSS: Cascading Style Sheets
ld watch out for. so we will start by looking at the two axes that we deal with when aligning things in a grid. the two axes of a grid layout when working with grid layout you have two axes available to align things against – the block axis and the inline axis. the block axis is the axis upon which blocks are laid out in block layout. if you have two paragraphs on your page they display one below the other, so it is this direction we describe as the block axis. the inline axis runs across the block axis, it is the direction in which text in regular inline flow runs. we are able to align the content inside grid areas, and the grid tracks themselves on these two axes. aligning items on the block axis the align-self and align-items properties control alignment on the block axis. wh...
...he direction in which text in regular inline flow runs. we are able to align the content inside grid areas, and the grid tracks themselves on these two axes. aligning items on the block axis the align-self and align-items properties control alignment on the block axis. when we use these properties, we are changing the alignment of the item within the grid area you have placed it. in the following example, i have four grid areas within my grid. ...
...two axes. aligning items on the block axis the align-self and align-items properties control alignment on the block axis. when we use these properties, we are changing the alignment of the item within the grid area you have placed it. in the following example, i have four grid areas within my grid. ...
...And 3 more matches
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
of grid and other modern layout methods, learning a little about writing modes and logical vs. physical properties as we do so. logical and physical properties and values css is full of physical positioning keywords – left and right, top and bottom. if we position an item using absolute positioning, we use these physical keywords as offset values to push the item around. in the code snippet below, the item is placed 20 pixels from the top, and 30 pixels from the left of the container: .container { position: relative; } .item { position: absolute; top: 20px; left: 30px; } <div class="container"> <div class="item">item</div> </div> another place you might see physical keywords in use, is when using text-align: right to align text to the right. there are also physical properti...
...re looking at. left is always left, no matter what direction your text is running. this can become an issue when developing a site that has to work in multiple languages, including languages that have text starting on the right, rather than the left. browsers are pretty good at dealing with text direction, and you don’t even need to be working in a rtl language to take a look. in the example below, i have two paragraphs. one has no text-align property set, the second has text-align set to left. i have added dir="rtl" to the html element, which switches the writing mode from the default for an english language document of ltr. you can see that the first paragraph remains left to right, due to the text-align value being left . the second however, switches direction and the text runs from rig...
... can see that the first paragraph remains left to right, due to the text-align value being left . the second however, switches direction and the text runs from right to left . this is a very simple example of the problem with physical values and properties being used in css. they prevent the browser being able to do the work to switch writing mode, as they make the assumption that the text is flowing left to right and top to bottom. logical properties and values logical properties and values do not make an assumption about text direction. which is why in grid layout we use the keyword start when aligning something to the start of the container. for me, working in english, start may well be on the left, however it doesn’t have to be, and the word start infers no physical location. bloc...
...And 3 more matches
Logical properties for floating and positioning - CSS: Cascading Style Sheets
they assume a horizontal writing-mode, with a left-to-right direction. ...
...t values for the block dimension simultaneously. inset sets all four inset values simultaneously with physical mapping of multi-value. float and clear example the physical values used with the float and clear properties are left, right and both. the logical properties specification defines the values inline-start and inline-end as mappings for left and right. ...
...s specification defines the values inline-start and inline-end as mappings for left and right. in the example below i have two boxes — the first has the box floated with float: left, the second with float: inline-start. if you change the writing-mode to vertical-rl or the direction to rtl you will see that the left-floated box always sticks to the left, whereas the inline-start-floated item follows the direction and writing-mode. example: inset properties for positioned layout positioning generally allows us to position an element in a manner relative to its containing block — we essentially inset the item relative to where it would fall based on normal flow. to do this we have historically used the physical properties top, right, bottom and left. these properties take a length or a...
...And 3 more matches
Basic concepts of CSS Scroll Snap - CSS: Cascading Style Sheets
the desktop for some types of applications. basics of scroll snap the key properties of the scroll snap specification are scroll-snap-type and scroll-snap-align. the scroll-snap-type property is used on the scroll container to state the type and direction of scrolling. the scroll-snap-align property must be used on child elements in order to set the position that scrolling will snap to. the below example demonstrates scroll snapping along the y axis, with scroll-snap-align used on the section element to dictate the point the scrolling should stop. using scroll-snap-type the scroll-snap-type property needs to know the direction in which scroll snapping happens. this could be x or y, or the logical mappings block or inline. you can also use the keyword both to have scroll snapping work ...
...ves in the frustrating position of never being able to scroll and view a certain point in the content. therefore, use of mandatory should be carefully considered and only used in situations where you know how much content is on the screen at any one time. the proximity value will only snap to a position when it is close by, the exact distance being left to the browser to decide. ...
...tion when it is close by, the exact distance being left to the browser to decide. in the example below you can change the value between mandatory and proximity to see the effect this has on the scroll experience. using scroll-snap-align the scroll-snap-align property can take a value of start, end, or center — indicating the point the content should snap to in the scroll container. in the below example you can change the value of scroll-snap-align to see how this changes the scroll behavior. padding the scroll container if you do not want the content to snap right to the edge of the scroll container you can use the scroll-padding property or its equivalent longhand values to set some padding. in the below example i have set scroll-padding to 40 pixels. when we snap to the start of ...
...And 3 more matches
CSS Tutorials - CSS: Cascading Style Sheets
Web › CSS › Tutorials
es so that difficulty-based lists can be automatically built. beginner-level css tutorials getting started this guide is aimed at complete beginners: you haven't written one single line of css? — this is for you. it explains the fundamental concepts of the language and guides you in writing basic stylesheets. using multiple backgrounds backgrounds are fundamental for nice styling: css allows you to set several of them on each box. this tutorial explains how they interact and how to achieve nice effects. scaling background images css allows you to resize images used as an element's background. this tutorial describes how to achieve this in a simple way. media queries the size of the screens, or the kind of devices like touchscreens or printed sheets vary greatly nowadays. media q...
...-level css tutorials after the release of css 2 (level 1), new features have been added to css. some of them are fancy and are pretty self contained. they are easy to use for anybody with a fair knowledge of basic concepts. css counters counting items and pages is an easy task in css. learn to use counter-reset, counter-increment, counters(), and counter(). ...
...d. they are easy to use for anybody with a fair knowledge of basic concepts. css counters counting items and pages is an easy task in css. learn to use counter-reset, counter-increment, counters(), and counter(). css animations css3 animations allow you 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 type...
...And 3 more matches
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
they are set using custom property notation (e.g., --main-color: black;) and are accessed using the var() function (e.g., color: var(--main-color);). complex websites have very large amounts of css, often with a lot of repeated values. for example, the same color might be used in hundreds of different places, requiring global search and replace if that color needs to change. custom properties allow a value to be stored in one place, then referenced in multiple other places. an additional benefit is semantic identifiers. for example, --main-text-color is easier to understand than #00ff00, especially if this same color is also used in other contexts. custom properties are subject to the cascade and inherit their value from their parent. basic usage declaring a custom property is done using...
... inheritance of custom properties custom properties do inherit. this means that if no value is set for a custom property on a given element, the value of its parent is used. take this html: <div class="one"> <div class="two"> <div class="three"></div> ...
...e; very useful if you want to change the value across the entire page later. inheritance of custom properties custom properties do inherit. this means that if no value is set for a custom property on a given element, the value of its parent is used. take this html: <div class="one"> <div class="two"> <div class="three"></div> <div class="four"></div> </div> </div> ... ...
...And 3 more matches
align-items - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. ...
...values */ align-items: center; /* pack items around the center */ align-items: start; /* pack items from the start */ align-items: end; /* pack items from the end */ align-items: flex-start; /* pack flex items from the start */ align-items: flex-end; /* pack flex items from the end */ /* baseline alignment */ align-items: baseline; align-items: first baseline; align-items: last baseline; /* overflow alignment (for positional alignment only) */ align-items: safe center; align-items: unsafe center; /* global values */ align-items: inherit; align-items: initial; align-items: unset; values normal the effect of this keyword is dependent of the layout mode we are in: in absolutely-positioned layouts, the keyword behaves like start on replaced absolutely-positioned boxes, and as stretch ...
... to table cells. flex-start the cross-start margin edges of the flex items are flushed with the cross-start edge of the line. flex-end the cross-end margin edges of the flex items are flushed with the cross-end edge of the line. center the flex items' margin boxes are centered within the line on the cross-axis. if the cross-size of an item is larger than the flex container, it will overflow equally in both directions. start the items are packed flush to each other toward the start edge of the alignment container in the appropriate axis. end the items are packed flush to each other toward the end edge of the alignment container in the appropriate axis. self-start the items are packed flush to the edge of the alignment container of the start side of the item, in the appropriate ...
...And 3 more matches
flex - CSS: Cascading Style Sheets
Web › CSS › flex
orthand property sets how a flex item will grow or shrink to fit the space available in its flex container. 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. ...
... <flex-basis> value is assumed to be 0. one of the keywords: none, auto, or initial. two-value syntax: the first value must be a <number> and it is interpreted as <flex-grow>. the second value must be one of: a <number>: 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 ite...
...efaults to 1 when omitted. <'flex-shrink'> defines the flex-shrink of the flex item. negative values are considered invalid. defaults to 1 when omitted. <'flex-basis'> defines the flex-basis of the flex item. a preferred size of 0 must have a unit to avoid being interpreted as a flexibility. defaults to 0 when omitted. ...
...And 3 more matches
font-size-adjust - CSS: Cascading Style Sheets
the font-size-adjust css property sets the size of lower-case letters relative to the current font size (which 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. ...
... to use this property in a way that is compatible with browsers that do not support font-size-adjust, it is specified as a number that the font-size property is multiplied by. ...
... this property in a way that is compatible with browsers that do not support font-size-adjust, it is specified as a number that the font-size property is multiplied by. this means the value specified for the property should generally be the aspect ratio of the first choice font. for example, a style sheet that specifies: font-size: 14px; font-size-adjust: 0.5; ... ...
...And 3 more matches
hanging-punctuation - CSS: Cascading Style Sheets
the hanging-punctuation css property specifies whether a punctuation mark should hang at the start or end of a line of text. hanging punctuation may be placed outside the line box. ...
... specifies whether a punctuation mark should hang at the start or end of a line of text. hanging punctuation may be placed outside the line box. ...
...n may be placed outside the line box. /* keyword values */ hanging-punctuation: none; hanging-punctuation: first; hanging-punctuation: last; hanging-punctuation: force-end; hanging-punctuation: allow-end; /* two keywords */ hanging-punctuation: first force-end; hanging-punctuation: first allow-end; hanging-punctuation: first last; hanging-punctuation: last force-end; hanging-punctuation: last allow-end; /* three keywords */ hanging-punctuation: first force-end last; hanging-punctuation: first allow-end last; /* global values */ hanging-punctuation: inherit; hanging-punctuation: initial; hanging-punctuation: unset; syntax the hanging-punctuation property may be specified with one, two, or three values. one-value syntax uses any one of the keyword values in the list below. two-value...
...And 3 more matches
Guide to scroll anchoring - CSS: Cascading Style Sheets
this has happened because large images or some other elements have just loaded further up in the content. scroll anchoring is a browser feature that aims to solve this problem of content jumping, which happens if content loads in after the user has already scrolled to a new part of the document. ...
...her disabling scroll anchoring fixes the issue in firefox by changing layout.css.scroll-anchoring.enabled to false in about:config. if it does, you can check what node is firefox using as the anchor using the layout.css.scroll-anchoring.highlight switch. that will show a purple overlay on top of the anchor node. if one node doesn't seem appropriate to be an anchor, you can exclude it using overflow-anchor, as described below. what if i need to disable it? the specification provides a new property, overflow-anchor, which can be used to disable scroll anchoring on all or part of the document. it's essentially a way to opt out of the new behavior. the only possible values are auto or none: auto is the initial value; as long as the user has a supported browser the scroll anchoring behavio...
...or. the only possible values are auto or none: auto is the initial value; as long as the user has a supported browser the scroll anchoring behavior will happen, and they should see fewer content jumps. none means that you have explicitly opted the document, or part of the document, out of scroll anchoring. ...
...And 3 more matches
repeating-conic-gradient() - CSS: Cascading Style Sheets
preceded by the from keyterm, and taking an angle as its value, defines the gradient rotation in clockwise direction. <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 re...
...ent. <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 color stops. note: rendering of color stops in css gradients follows the same rules as color stops in svg gradients. description example repeating conic gradients include starbursts. the result of the repeating-conic-gradient() function is an object of the <gradient> data type, which is a special kind of <image>. if neither the first nor the last color stops include include a a color stop angle greater than 0deg or less than 360 degrees respectively, the ...
...s similar to the conic-gradient() and repeating-radial-gradient() syntax. like the non-repeating conic-gradient, the color-stops are placed around a gradient arc. like the repeating radial gradient, the size of the repeating section is the first color stop subtracted from the angle of the last color stop. the above gradients are defined as being one third blue, one third red, and one third yellow. repeating-conic-gradient(from 0deg, red 0deg 30deg, yellow 30deg 60deg, blue 60deg 90deg); repeating-radial-gradient(red 0 8%, yellow 8% 16%, blue 16% 24%); conic-gradient(red 120deg, yellow 120deg 240deg, blue 240deg); radial-gradient(red 33%, yellow 33% 66%, blue 66%); for a repeating gradient to repeat we define the first and last color stops. like in non-repeating gradients, the first ...
...And 3 more matches
table-layout - CSS: Cascading Style Sheets
nd col elements or by 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. 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. ...
...out 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. ...
...And 3 more matches
writing-mode - CSS: Cascading Style Sheets
ction in which blocks progress. when set for an entire document, it should be set on the root element (html element for html documents). 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 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...
...tion 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 that script, either left-to-right (ltr, like english and most other languages) or right-to-left (rtl, like hebrew or arabic). values horizontal-tb for ltr scripts, content flows horizontally from left to right. for rtl scripts, content flows horizontally from right to left. the next horizontal line is positio...
...flow direction in horizontal scripts is also affected by the directionality of that script, either left-to-right (ltr, like english and most other languages) or right-to-left (rtl, like hebrew or arabic). values horizontal-tb for ltr scripts, content flows horizontally from left to right. for rtl scripts, content flows horizontally from right to left. the next horizontal line is positioned below the previous line. vertical-rl for ltr scripts, content flows vertically from top to bottom, and the next vertical line is positioned to the left of the previous line. for rtl scripts, content flows vertically from bottom to top, and the next vertical line is positioned to the right of the previous line. ...
...And 3 more matches
Overview of events and handlers - Developer guides
ting 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 user. the displayed page remains unchanged until the browser requests a new page. with the change to dynamic page rendering, browsers loop continuously between processing, drawing, presenting content, and waiting for some new event t...
...k e.g., downloads an image that can now be drawn on the screen, the completion of parsing a resource by the browser e.g., processes the html content of a page, the interaction of a user with the contents of the page e.g., clicks a button. ...
... can now be drawn on the screen, the completion of parsing a resource by the browser e.g., processes the html content of a page, the interaction of a user with the contents of the page e.g., clicks a button. douglas crockford explains this change effectively in several lectures, notably his talk, an inconvenient api: the theory of the dom, which shows the change in flow from the original browser flow to the event driven browser. ...
...And 3 more matches
Using HTML sections and outlines - Developer guides
efer to the main content alone and can be used for comments and widgets. html section element (<section>) defines a section of a document to indicate a related grouping of semantic meaning. it makes sense to use the section element to provide extra context for the parent element. html aside element (<aside>) defines a section that, though related to the main element, doesn't belong to the main flow, like an explanation box or an advertisement. the aside element has its own outline, but doesn't belong to the main one. other semantic html elements used in sectioning html body element (<body>) defines all the content of a document. it contains all the content and html tags. html header element (<header>) defines a page area that typically contains a logo, title, and navigation. the heade...
... <aside> inside an <aside>. meaning a call out box would not have a call-out box inside. using html5 elements in non-html5 browsers sections and headings elements can be made to work in most non-html5 browsers with a couple of extra steps, and in this section we'll show you how. if a significant percentage of your particular target audience is using internet explorer 8 or older, then you can follow the below instructions to make them behave as expected. however, global usage of these browsers is now very small, so this is unlikely. 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: a...
... 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. ...
...And 3 more matches
Index - Developer guides
Web › Guide › Index
html5 media element. how would you do that? this article explains how, looking at two of the most common formats: mpeg-dash and hls (http live streaming.) 13 video player styling basics apps, guide, media, styling, video 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. ...
...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. 14 web audio playbackrate explained apps, audio, media, video, playbackrate the playbackrate property of the <audio> and <video> elements allows us to change the speed, or rate, at which a piece of web audio or video is playing 15 writing web audio api code that works in every browser api you probably have already read the announcement on the web audio api coming to firefox, and are totally excited and ready to make your until-now-webkit-only sites work with firefox, which uses the unprefixed version of the spec. ...
... used. 32 mobile web development intermediate, needsexample this page provides an overview of some of the main techniques needed to design web sites that work well on mobile devices. 33 a hybrid approach mobile, responsive design, web development no approach is a one-size-fits-all solution. web applications that want to heavily modify the content or user flow for mobile users should probably go for a separate mobile site. content-oriented pages that don’t need to modify their content for mobile users will be satisfied with responsive design. if you need to slightly alter the site’s message for mobile users, but want to reap the benefits of a responsive design, a hybrid approach may be your best bet. decisions like these are at the heart of mobile ...
...And 3 more matches
User input and controls - Developer guides
provides recommendations for managing user input and implementing controls in open web apps, along with faqs, real-world examples, and links to further information for anyone needing more detailed information on the underlying technologies. relevant apis and events include touch events, pointer lock api, screen orientation api, fullscreen api, drag & drop and more. user input and controls workflow the following diagram illustrates the typical workflow for implementing user input mechanisms: first of all, you need to decide which input mechanisms you want to cover in your application out of mouse, keyboard, finger touch and so on. once you decided the input mechanisms, you can control them using tools offered by the web platform or javascript libraries. recommendations available input...
...oving 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 want to add controls when any key gets pressed, you need to add an event listener on the window object: window.addeventlistener("keydown", handlekeydown, true); window.addeventlistener("key...
...en the user interacts with a pointing device such as a mouse are represented by the mouseevent dom interface. common mouse events include click, dblclick, mouseup, and mousedown. the list of all events using the mouse event interface is provided in the events reference. when the input device is a mouse, you can also control user input through the pointer lock api and implement drag & drop (see below). finger touch when developing web applications meant to be installed on touchscreen devices, it’s a good practice to take into consideration the different capabilities in terms of screen resolution and user input. touch events can help you implement interactive elements and common interaction gestures on touchscreen devices. if you want to use touch events, you need to add event listeners a...
...And 3 more matches
HTML attribute: accept - HTML: Hypertext Markup Language
the accept property is an attribute of the file <input> type. it was supported on the <form> element, but was removed in favor of file in html5. because a given file type may be identified in more than one manner, it's useful to provide a thorough set of type specifiers when you need files of specific type, or use the wild card to denote a type of any format is acceptable. ...
...selectable. ...
...for example: .jpg, .pdf, or .doc. a valid mime type string, with no extensions. the string audio/* meaning "any audio file". the string video/* meaning "any video file". ...
...And 3 more matches
<input type="color"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › color
color names, functional notations and a hexadecimal format with an alpha channel. ...
...ed in the proper format, or a platform-standard color picker, or some kind of custom color picker window. 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. value a 7-character domstring specifying a <color> in lower-case hexadecimal notation events change and input supported common attributes autocomplete and list idl attributes list and value methods select() value the value of an <input> element of type color is always a domstring which contains a 7-character string specifying an rgb color in hexadecimal format. while you can input the color in eith...
...ecimal notation events change and input supported common attributes autocomplete and list idl attributes list and value methods select() value the value of an <input> element of type color is always a domstring which contains a 7-character string specifying an rgb color in hexadecimal format. while you can input the color in either upper- or lower-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 m...
...And 3 more matches
<input type="date"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › date
ontrol.value); // prints "2017-06-01" console.log(datecontrol.valueasnumber); // prints 1496275200000, a unix 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...
...of the min attribute isn't a possible date string in the format yyyy-mm-dd, then the element has no minimum date value. if both the max and min attributes are set, this value must be a date string earlier than or equal to the one in the max attribute. 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 a...
... in this section, we'll look at basic and then more complex uses of <input type="date">, and offer advice on mitigating the browser support issue later (see handling browser support). hopefully, over time browser support will become ubiquitous, and this problem will fade away. basic uses of date the simplest use of <input type="date"> involves one <input> combined with its <label>, as seen below: <form action="https://example.com"> <label> enter your birthday: <input type="date" name="bday"> </label> <p><button>submit</button></p> </form> this html submits the entered date under the key bday to https://example.com — resulting in a url like https://example.com/?bday=1955-06-08. setting maximum and minimum dates you can use the min and max attributes to restrict the ...
...And 3 more matches
<script>: The Script element - HTML: Hypertext Markup Language
Web › HTML › Element › script
permitted content dynamic script such as text/javascript. tag omission none, both the starting and ending tag are mandatory. ...
...ts, if the async 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...
... 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 document has been parsed, but before firing domcontentloaded. scripts with the defer attribute will prev...
...And 3 more matches
Link types - HTML: Hypertext Markup Language
in html, link types indicate the relationship between two documents, in which one links to the other using an <a>, <area>, <form>, or <link> element. list of the defined link types and their significance in html link type description allowed in these elements not allowed in these elements alternate if the element is <link> and the rel attribute also contains the stylesheet type, the link defines an alternative style sheet; in that case the title attribute must be present and not be the empty string. if the type is set to application/rss+xml or application/atom+xml, the link defines a syndication feed. the first one defined on the page is the default. otherwise, the link defines an alternative page, of one of these types: ...
... rev attribute on <a>, <area> or<link> elements with a link type of made is incorrect and should be replaced by the rel attribute with this link type. <a>, <area>, <link> <form> bookmark indicates that the hyperlink is a permalink for the nearest ancestor <article> element. if none, it is a permalink for the section that the element is most closely associated to. this allows for bookmarking a single article in a page containing multiple articles, such as on a monthly summary blog page, or a blog aggregator. <a>, <area> <link>, <form> canonical from wikipedia, the free encyclopedia: canonical_link_element a canonical link element is an html element that helps webmasters prevent duplicate content issues by specifying the "canonical" or "preferred...
... canonical from wikipedia, the free encyclopedia: canonical_link_element a canonical link element is an html element that helps webmasters prevent duplicate content issues by specifying the "canonical" or "preferred" version of a web page as part of search engine optimization. <link> <a>, <area>, <form> dns-prefetch hints to the browser that a resource is needed, allowing the browser to do a dns lookup and protocol handshaking before a user clicks the link. <link> <a>, <area>, <form> external indicates that the hyperlink leads to a resource outside the site of the current page; that is, following the link will make the user leave the site. <a>, <area>, <form> <link> first indicates that the hyperlink leads to the first reso...
...And 3 more matches
CSP: font-src - HTTP
the http content-security-policy (csp) font-src directive specifies valid sources for fonts loaded using @font-face. csp version 1 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the font-src policy: content-security-policy: font-src <source>; content-security-policy: font-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as the port number, indicatin...
... mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a schema such as 'http:' or 'https:'. the colon is required, single quotes shouldn't be used. you can also specify data schemas (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin fr...
...urce. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows to enable specific inline event handlers. ...
...And 3 more matches
CSP: frame-ancestors - HTTP
nt-security-policy (csp) frame-ancestors directive specifies valid parents that may embed a page using <frame>, <iframe>, <object>, <embed>, or <applet>. setting this directive to 'none' is similar to x-frame-options: deny (which is also supported in older browsers). csp version 2 directive type navigation directive default-src fallback no. ...
...tive type navigation directive default-src fallback no. not setting this allows anything. this directive is not supported in the <meta> element. syntax one or more sources can be set for the frame-ancestors policy: content-security-policy: frame-ancestors <source>; content-security-policy: frame-ancestors <source> <source>; sources <source> can be one of the following: the frame-ancestors directive’s syntax is similar to a source list of other directives (e.g. default-src), but doesn't allow 'unsafe-eval' or 'unsafe-inline' for example. it will also not fall back to a default-src setting. ...
...ty-policy: frame-ancestors <source>; content-security-policy: frame-ancestors <source> <source>; sources <source> can be one of the following: the frame-ancestors directive’s syntax is similar to a source list of other directives (e.g. default-src), but doesn't allow 'unsafe-eval' or 'unsafe-inline' for example. it will also not fall back to a default-src setting. only the sources listed below are allowed: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number, separated by spaces. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as the port number, indicating that all legal ports are valid for the source. single quotes surrounding the host are not al...
...And 3 more matches
CSP: frame-src - HTTP
y (csp) frame-src directive specifies valid sources for nested browsing contexts loading using elements such as <frame> and <iframe>. csp version 1 directive type fetch directive fallback if this directive is absent, the user agent will look for the child-src directive (which falls back to the default-src directive). syntax one or more sources can be allowed for the frame-src policy: content-security-policy: frame-src <source>; content-security-policy: frame-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wil...
... mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a schema such as 'http:' or 'https:'. the colon is required, single quotes shouldn't be used. you can also specify data schemas (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin fr...
...urce. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows to enable specific inline event handlers. ...
...And 3 more matches
CSP: manifest-src - HTTP
the http content-security-policy: manifest-src directive specifies which manifest can be applied to the resource. csp version 3 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the manifest-src policy: content-security-policy: manifest-src <source>; content-security-policy: manifest-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as the port number, ...
... mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a schema such as 'http:' or 'https:'. the colon is required, single quotes shouldn't be used. you can also specify data schemas (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin fr...
...urce. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows to enable specific inline event handlers. ...
...And 3 more matches
CSP: media-src - HTTP
the http content-security-policy (csp) media-src directive specifies valid sources for loading media using the <audio> and <video> elements. csp version 1 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the media-src policy: content-security-policy: media-src <source>; content-security-policy: media-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as...
... mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a schema such as 'http:' or 'https:'. the colon is required, single quotes shouldn't be used. you can also specify data schemas (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin fr...
...urce. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows to enable specific inline event handlers. ...
...And 3 more matches
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. ...
...tion manifest files. media-src specifies valid sources for loading media using the <audio> , <video> and <track> elements. object-src specifies valid sources for the <object>, <embed>, and <applet> elements. elements controlled by object-src are perhaps coincidentally considered legacy html elements and are not receiving new standardized features (such as the security attributes sandbox or allow for <iframe>). therefore it is recommended to restrict this fetch-directive (e.g., explicitly set object-src 'none' if possible). prefetch-src specifies valid sources to be prefetched or prerendered. script-src specifies valid sources for javascript. script-src-elem specifies valid sources for javascript <script> elements. script-src-attr specifies valid sources for javascript inline e...
... any assets using http when the page is loaded using https. referrer used to specify information in the referer (sic) header for links away from a page. use the referrer-policy header instead. require-sri-for requires the use of sri for scripts or styles on the page. require-trusted-types-for enforces trusted types at the dom xss injection sinks. trusted-types used to specify an allow-list of trusted types policies. trusted types allows applications to lock down dom xss injection sinks to only accept non-spoofable, typed values in place of strings. upgrade-insecure-requests instructs user agents to treat all of a site's insecure urls (those served over http) as though they have been replaced with secure urls (those served over https). this directive is intended for web si...
...And 3 more matches
Feature-Policy: encrypted-media - HTTP
the http feature-policy header encrypted-media directive controls whether the current document is allowed to use the encrypted media extensions api (eme). when this policy is enabled, the promise returned by navigator.requestmediakeysystemaccess() will reject with a domexception. syntax feature-policy: encrypted-media <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
...origins should be separated by a space. ...
...origins should be separated by a space. ...
...And 3 more matches
Feature-Policy: midi - HTTP
the http feature-policy header midi directive controls whether the current document is allowed to use the web midi api. when this policy is enabled, the promise returned by navigator.requestmidiaccess() will reject with a domexception. syntax feature-policy: midi <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
...origins should be separated by a space. ...
...origins should be separated by a space. ...
...And 3 more matches
Feature-Policy: payment - HTTP
the http feature-policy header field's payment directive controls whether the current document is allowed to use the payment request api. when this policy is disabled, the paymentrequest() constructor will throw a syntaxerror. syntax feature-policy: payment <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
...origins should be separated by a space. ...
...origins should be separated by a space. ...
...And 3 more matches
Feature-Policy: publickey-credentials-get - HTTP
the http feature-policy header publickey-credentials-get directive controls whether the current document is allowed to access web authentcation api to create new public-key credentials, i.e, via navigator.credentials.get({publickey: ..., ...}). when this policy is enabled, any attempt to query public key credentials will result in an error. syntax feature-policy: publickey-credentials-get <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe...
...origins should be separated by a space. ...
...origins should be separated by a space. ...
...And 3 more matches
Feature-Policy: unsized-media - HTTP
the http feature-policy header unsized-media directive controls whether the current document is allowed to change the size of media elements after the initial layout is complete. this restriction solves "layout instability" problem caused by providing default dimensions for images whose size is not specified in advance so that image doesn't change size after loading. syntax feature-policy: unsized-media <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an...
...origins should be separated by a space. ...
...origins should be separated by a space. ...
...And 3 more matches
Feature-Policy: wake-lock - HTTP
note: this api is still actively being developed and available only behind a flag on select browsers and platforms. the http feature-policy header wake-lock directive controls whether the current document is allowed to use wake lock api to indicate that device should not enter power-saving mode. note: latest drafts of screen wake lock api defines screen-wake-lock directive. syntax feature-policy: wake-lock <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src'...
...origins should be separated by a space. ...
...origins should be separated by a space. ...
...And 3 more matches
Feature-Policy: xr-spatial-tracking - HTTP
the http feature-policy header xr-spatial-tracking directive controls whether the current document is allowed to use the webxr device api. this policy controls whether navigator.xr.requestsession() can return xrsession that requires spatial tracking and whether user agent can indicate support for sessions supporting spatial tracking via navigator.xr.issessionsupported() and devicechange event on navigator.xr object. ...
...s whether the current document is allowed to use the webxr device api. this policy controls whether navigator.xr.requestsession() can return xrsession that requires spatial tracking and whether user agent can indicate support for sessions supporting spatial tracking via navigator.xr.issessionsupported() and devicechange event on navigator.xr object. syntax feature-policy: xr-spatial-tracking <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. ...
....issessionsupported() and devicechange event on navigator.xr object. syntax feature-policy: xr-spatial-tracking <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. ...
...And 3 more matches
Set-Cookie - HTTP
alue>; samesite=none // multiple attributes are also possible, for example: set-cookie: <cookie-name>=<cookie-value>; domain=<domain-value>; secure; httponly attributes <cookie-name>=<cookie-value> a cookie begins with a name-value pair: a <cookie-name> can be any us-ascii characters, except control characters, spaces, or tabs. it also must not contain a separator character like the following: ( ) < > @ , ; : \ " / [ ] ? = { }. a <cookie-value> can optionally be wrapped in double quotes and include any us-ascii characters excluding control characters, whitespace, double quotes, comma, semicolon, and backslash. encoding: many implementations perform url encoding on cookie values, however it is not required per the rfc specification. it does help satisfying the requirements about w...
... " / [ ] ? = { }. a <cookie-value> can optionally be wrapped in double quotes and include any us-ascii characters excluding control characters, whitespace, double quotes, comma, semicolon, and backslash. encoding: many implementations perform url encoding on cookie values, however it is not required per the rfc specification. it does help satisfying the requirements about which characters are allowed for <cookie-value> though. __secure- prefix: cookies names starting with __secure- (dash is part of the prefix) must be set with the secure flag from a secure page (https). __host- prefix: cookies with names starting with __host- must be set with the secure flag, must be from a secure page (https), must not have a domain specified (and therefore aren't sent to subdomains) and the path must ...
...ber will expire the cookie immediately. if both expires and max-age are set, max-age has precedence. domain=<domain-value> optional host to which the cookie will be sent. if omitted, defaults to the host of the current document url, not including subdomains. contrary to earlier specifications, leading dots in domain names (.example.com) are ignored. multiple host/domain values are not allowed, but if a domain is specified, then subdomains are always included. path=<path-value> optional a path that must exist in the requested url, or the browser won't send the cookie header. the forward slash (/) character is interpreted as a directory separator, and subdirectories will be matched as well: for path=/docs, /docs, /docs/web/, and /docs/web/http will all match. secure optional ...
...And 3 more matches
Link prefetching FAQ - HTTP
en the user visits one of the prefetched documents, it can be served up quickly out of the browser's cache. does prefetching work with https? starting in gecko 1.9.1 (firefox 3.5), https content can be prefetched. what are the prefetching hints? the browser looks for either an html <link> or an http link: header with a relation type of either next or prefetch. an example using the link tag follows: <link rel="prefetch" href="/images/big.jpeg"> the same prefetching hint using an http link: header: link: </images/big.jpeg>; rel=prefetch the format for the link: header is described in rfc 5988 section 5. the browser observes all of these hints and queues up each unique request to be prefetched when the browser is idle. there can be multiple hints per page, as it might make sense to pr...
...ages/big.jpeg>; rel=prefetch the format for the link: header is described in rfc 5988 section 5. the browser observes all of these hints and queues up each unique request to be prefetched when the browser is idle. there can be multiple hints per page, as it might make sense to prefetch multiple documents. for example, the next document might contain several large images. some more examples follow: <link rel="prefetch alternate stylesheet" title="designed for mozilla" href="mozspecific.css"> <link rel="next" href="2.html"> are anchor (<a>) tags prefetched? no, only <link> tags with a relation type of next or prefetch are prefetched. however, if there is sufficient interest, we may expand link prefetching support to include prefetching <a> tags, which include a relation type of next or ...
...prefetching support to include prefetching <a> tags, which include a relation type of next or prefetch in the future. doing so would probably help content providers avoid the problem of stale prefetching links. is link prefetching standards compliant? yes, link prefetching as outlined in this document does not violate any existing web standards. in fact, the html 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 (...
...And 3 more matches
HTTP Messages - HTTP
Web › HTTP › Messages
ched or post means that data is pushed to the server (creating or modifying a resource, or generating a temporary document to send back). the request target, usually a url, or the absolute path of the protocol, port, and domain are usually characterized by the request context. the format of this request target varies between different http methods. it can be an absolute path, ultimately followed by a '?' and query string. this is the most common form, known as the origin form, and is used with get, post, head, and options methods. post / http/1.1 get /background.png http/1.0 head /test.html?query=alibaba http/1.1 options /anypage.html http/1.0 a complete url, known as the absolute form, is mostly used with get when connected to a proxy. get http://developer.mozil...
...ct when setting up an http tunnel. connect developer.mozilla.org:80 http/1.1 the asterisk form, a simple asterisk ('*') is used with options, representing the server as a whole. options * http/1.1 the http version, which defines the structure of the remaining message, acting as an indicator of the expected version to use for the response. headers http headers from a request follow the same basic structure of an http header: a case-insensitive string followed by a colon (':') and a value whose structure depends upon the header. the whole header, including the value, consist of one single line, which can be quite long. there are numerous request headers available. they can be divided in several groups: general headers, like via, apply to the message as a whole. request ...
...into two categories: single-resource bodies, consisting of one single file, defined by the two headers: content-type and content-length. multiple-resource bodies, consisting of a multipart body, each containing a different bit of information. this is typically associated with html forms. ...
...And 3 more matches
JavaScript data types and data structures - JavaScript
al entity and can have two values: true and false. see boolean and boolean for more details. null type the null type has exactly one value: null. see null and null for more details. undefined type a variable that has not been assigned a value has the value undefined. see undefined and undefined for more details. number type ecmascript has two built-in numeric types: number and bigint (see below). the number 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 o...
... "list" elements, then, the list is broken. an escape character can be chosen, etc. all of this requires conventions and creates an unnecessary maintenance burden. use strings for textual data. when representing complex data, parse strings, and use the appropriate abstraction. symbol type a symbol is a unique and immutable primitive value and may be used as the key of an object property (see below). in some programming languages, symbols are called "atoms". for more details see symbol and the symbol object wrapper in javascript. objects in computer science, an object is a value in memory which is possibly referenced by an identifier. properties in javascript, objects can be seen as a collection of properties. with the object literal syntax, a limited set of properties are initialized;...
...ve certain attributes: the data property and the accessor property. note: each property has corresponding attributes. attributes are used internally by the javascript engine, so you cannot directly access them. that's why attributes are listed in double square brackets, rather than single. see object.defineproperty() to learn more. data property associates a key with a value, and has the following attributes: attributes of a data property attribute type description default value [[value]] any javascript type the value retrieved by a get access of the property. undefined [[writable]] boolean if false, the property's [[value]] cannot be changed. false [[enumerable]] boolean if true, the property will be enumer...
...And 3 more matches
Assertions - JavaScript
do not forget to edit it as well, thanks! boundary-type assertions characters meaning ^ matches the beginning of input. if the multiline flag is set to true, also matches immediately after a line break character. ...
...er has a different meaning when it appears at the start of a group. $ matches the end of input. if the multiline flag is set to true, also matches immediately before a line break character. for example, /t$/ does not match the "t" in "eater", but does match it in "eat". \b matches a word boundary. this is the position where a word character is not followed or preceded by another word-character, such as between a letter and a space. note that a matched word boundary is not included in the match. in other words, the length of a matched word boundary is zero. examples: /\bm/ matches the "m" in "moon". /oo\b/ does not match the "oo" in "moon", because "oo" is followed by "n" which is a word character. /oon\b/ matches the "oo...
... and a space. note that a matched word boundary is not included in the match. in other words, the length of a matched word boundary is zero. examples: /\bm/ matches the "m" in "moon". /oo\b/ does not match the "oo" in "moon", because "oo" is followed by "n" which is a word character. /oon\b/ matches the "oon" in "moon", because "oon" is the end of the string, thus not followed by a word character. /\w\b\w/ will never match anything, because a word character can never be followed by both a non-word and a word character. to match a backspace character ([\b]), see character classes. \b matches a non-word boundary. this is a position where the previous and next character are of the same type: either both must be words, or both must be ...
...And 3 more matches
Arrow function expressions - JavaScript
actors influenced the introduction of arrow functions: the need for shorter functions and the behavior of the this keyword. ...
...e can use destructuring parameter: // notice that the `length` corresponds to the property we want to get whereas the // obviously non-special `lengthfoobarx` is just the name of a variable which can be changed // to any valid variable name you want elements.map(({ length: lengthfoobarx }) => lengthfoobarx); // [8, 6, 7, 9] // this destructuring parameter assignment can also be written as seen below. however, note that in // this example we are not assigning `length` value to the made up property. instead, the literal name // itself of the variable `length` is used as the property we want to retrieve from the object. elements.map(({ length }) => 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 cal...
...s to the `that` variable of which // the value is the expected object. that.age++; }, 1000); } alternatively, a bound function could be created so that a preassigned this value would be passed to the bound target function (the growup() function in the example above). an arrow function does not have its own this. ...
...And 3 more matches
Array.prototype.concat() - JavaScript
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 const new_array = old_array.concat([value1[, value2[, ...[, valuen]]]]) parameters valuen optional arrays and/or values to concatenate into a new array. ...
...les project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax const new_array = old_array.concat([value1[, value2[, ...[, valuen]]]]) parameters valuen optional arrays and/or values to concatenate into a new array. if all valuen parameters are omitted, concat returns a shallow copy of the existing array on which it is called. see the description below for more details. return value a new array instance. description the concat method creates a new array consisting of the elements in the object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array). it does not recurse into nested array arguments. the concat method ...
...creates a new array consisting of the elements in the object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array). it does not recurse into nested array arguments. the concat method does not alter this or any of the arrays provided as arguments but instead returns a shallow copy that contains copies of the same elements combined from the original arrays. elements of the original arrays are copied into the new array as follows: object references (and not the actual object): concat copies object references into the new array. both the original and new array refer to the same object. that is, if a referenced object is modified, the changes are visible to both the ne...
...And 3 more matches
Array.prototype.filter() - JavaScript
ts 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 in the same way they will not be visited. polyfill filter() 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.prototy...
...} } } } else{ while (++i !== len){ // checks to see if the key was set if (i in this){ kvalue = t[i]; if (func.call(thisarg, t[i], i, t)){ res[c++] = kvalue; } } } } res.length = c; // shrink down array to proper size return res; }; } examples filtering out all small values the following example uses filter() to create a filtered array that has all elements with values less than 10 removed. function isbigenough(value) { return value >= 10 } let filtered = [12, 5, 8, 130, 44].filter(isbigenough) // filtered is [12, 130, 44] find all prime numbers in an array the following example returns all prime numbers in the array: const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, ...
...me numbers in an array the following example returns all prime numbers in the array: const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; function isprime(num) { for (let i = 2; num > i; i++) { if (num % i == 0) { return false; } } return num > 1; } console.log(array.filter(isprime)); // [2, 3, 5, 7, 11, 13] filtering invalid entries from json the following example uses filter() to create a filtered json of all elements with non-zero, numeric id. let arr = [ { id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }, { }, { id: null }, { id: nan }, { id: 'undefined' } ] let invalidentries = 0 function filterbyid(item) { if (number.isfinite(item.id) && item.id !== 0) { return true } invalidentries++ return false; }...
...And 3 more matches
Array - JavaScript
t"] let pos = 1 let n = 2 let removeditems = vegetables.splice(pos, n) // this is how to remove items, n defines the number of items to be removed, // starting at the index position specified by pos and progressing toward the end of array. console.log(vegetables) // ["cabbage", "carrot"] (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...
...onsole.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 in the same way that tostring is a property (to be specific, however, tostring() is a method). nevertheless, trying to access an element of an array as follows throws a syntax error because the property name is not valid: console.log(arr.0) // a syntax error there is nothing special about javascript arrays and the properties that cause this. javascript properties that begin with a digit cannot be referenced with dot notation and must be accessed using bracket notation. for example, if you had an object with a property named 3d, it can only be refer...
...e 3d example, '3d' had to be quoted (because it begins with a digit). but it's also possible to quote the array indexes as well (e.g., years['2'] instead of years[2]), although it's not necessary. the 2 in years[2] is coerced into a string by the javascript engine through an implicit tostring conversion. as a result, '2' and '02' would refer to two different slots on the years object, and the following example could be true: console.log(years['2'] != years['02']) relationship between length and numerical properties a javascript array's length property and numerical properties are connected. several of the built-in array methods (e.g., join(), slice(), indexof(), etc.) take into account the value of an array's length property when they're called. other methods (e.g., push(), splice(), e...
...And 3 more matches
JSON - JavaScript
its own. description javascript and json differences json is a syntax for serializing objects, arrays, numbers, strings, booleans, and null. it is based upon javascript syntax but is distinct from it: some javascript is not json. objects and arrays property names must be double-quoted strings; trailing commas are forbidden. numbers leading zeros are prohibited. ...
.... numbers leading zeros are prohibited. a decimal point must be followed by at least one digit. nan and infinity are unsupported. any json text is a valid javascript expression... ...but only in javascript engines that have implemented the proposal to make all json text valid ecma-262. in engines that haven't implemented the proposal, u+2028 line separator and u+2029 paragraph separator are allowed in string literals and property keys in json; but their use in these features in javascript string literals is a syntaxerror. consider this example where json.parse() parses the string as json and eval executes the string as javascript: let code = '"\u2028\u2029"' json.parse(code) // evaluates to "\u2028\u2029" in all engines eval(code) // throws a syntaxerror in old engines other ...
...and property keys in json; but their use in these features in javascript string literals is a syntaxerror. ...
...And 3 more matches
Object.prototype.constructor - JavaScript
nstructor property that points to the fundamental object constructor type for that object. ...
...only true, 1, and "test" will not be affected (as they have read-only native constructors). ...
...of that type (thetree). the example then displays the constructor property for the object thetree. function tree(name) { this.name = name } let thetree = new tree('redwood') console.log('thetree.constructor is ' + thetree.constructor) this example displays the following output: thetree.constructor is function tree(name) { this.name = name } changing the constructor of an object the following example shows how to modify the constructor value of generic objects. only true, 1, and "test" will not be affected (as they have read-only native constructors). this example shows that it is not always safe to rely on the constructor property of an object. function type () {} let types = [ new array(), [], new boolean(), true, // remains unchanged new date(), new er...
...And 3 more matches
Object.defineProperty() - JavaScript
mdn/interactive-examples and send us a pull request. syntax object.defineproperty(obj, prop, descriptor) parameters obj the object on which to define the property. prop the name or symbol of the property to be defined or modified. descriptor the descriptor for the property being defined or modified. return value the object that was passed to the function. description this method allows a precise addition to or modification of a property on an object. normal property addition through assignment creates properties which show up during property enumeration (for...in loop or object.keys method), whose values may be changed, and which may be deleted. this method allows these extra details to be changed from their defaults. by default, values added using object.defineproperty() are ...
...scriptors present in objects come in two main flavors: data descriptors and accessor descriptors. a data descriptor is a property that has a value, which may or may not be writable. an accessor descriptor is a property described by a getter-setter pair of functions. a descriptor must be one of these two flavors; it cannot be both. both data and accessor descriptors are objects. they share the following optional keys (note: the default value is in the case of defining properties using object.defineproperty()): configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. defaults to false. enumerable true if and only if this property shows up during enumeration of the properties on the correspondin...
...ing properties using object.defineproperty()): configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. defaults to false. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. defaults to false. ...
...And 3 more matches
Object.prototype.toString() - JavaScript
ject has a tostring() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. by default, the tostring() method is inherited by every object descended from object. if this method is not overridden in a custom object, tostring() returns "[object type]", where type is the object type. the following code illustrates this: const o = new object(); o.tostring(); // returns [object object] note: starting in javascript 1.8.5, tostring() called on null returns [object null], and undefined returns [object undefined], as defined in the 5th edition of ecmascript and subsequent errata. see using tostring() to detect object class. parameters for numbers and bigints tostring() takes an optio...
...ed 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 output is "10100" some common radix are 2 for binary numbers, 8 for octal numbers, 10 for decimal numbers, 16 for hexadecimal numbers. exa...
...rs, 10 for decimal numbers, 16 for hexadecimal numbers. examples overriding the default tostring method you can create a function to be called in place of the default tostring() method. the tostring() method takes no arguments and should return a string. the tostring() method you create can be any value you want, but it will be most useful if it carries information about the object. ...
...And 3 more matches
String.prototype.normalize() - JavaScript
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 str.normalize([form]) parameters form optional one of "nfc", "nfd", "nfkc", or "nfkd", specifying the unicode normalization form. if omitted or undefined, "nfc" is used. these values have the following meanings: "nfc" canonical decomposition, followed by canonical composition. "nfd" canonical decomposition. "nfkc" compatibility decomposition, followed by canonical composition. "nfkd" compatibility decomposition. return value a string containing the unicode normalization form of the given string. errors thrown rangeerror a rangeerror is thrown if form isn't one ...
...cription unicode assigns a unique numerical value, called a code point, to each character. for example, the code point for "a" is given as u+0041. however, sometimes more than one code point, or sequence of code points, can represent the same abstract character — the character "ñ" for example can be represented by either of: the single code point u+00f1. the code point for "n" (u+006e) followed by the code point for the combining tilde (u+0303). let string1 = '\u00f1'; let string2 = '\u006e\u0303'; console.log(string1); // ñ console.log(string2); // ñ however, since the code points are different, string comparison will not treat them as equal. and since the number of code points in each version is different, they even have different lengths. let string1 = '\u00f1'; ...
... two sequences of code points have canonical equivalence if they represent the same abstract characters, and should always have the same visual appearance and behavior (for example, they should always be sorted in the same way). you can use normalize() using the "nfd" or "nfc" arguments to produce a form of the string that will be the same for all canonically equivalent strings. ...
...And 3 more matches
delete operator - JavaScript
gramming languages like delete in c++), the delete operator has nothing to do with directly freeing memory. memory management is done indirectly via breaking references. see the memory management page for more details. the delete operator removes a given property from an object. on successful deletion, it will return true, else false will be returned. however, it is important to consider the following scenarios: if the property which you are trying to delete does not exist, delete will not have any effect and will return true. if a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties). any property declared with var cannot be delete...
...an object (apart from the global scope) can be deleted with delete. any property declared with let or const cannot be deleted from the scope within which they were defined. non-configurable properties cannot be removed. this includes properties of built-in objects like math, array, object and properties that are created as non-configurable with methods like object.defineproperty(). ...
...e does not affect built-in static properties. delete math.pi; // returns false // employeedetails is a property of the global scope. // since it was defined without "var", it is marked configurable. delete employeedetails; // returns true function f() { var z = 44; // delete doesn't affect local variable names delete z; // returns false } delete and the prototype chain in the following example, we delete an own property of an object while a property with the same name is available on the prototype chain: function foo() { this.bar = 10; } foo.prototype.bar = 42; var foo = new foo(); // foo.bar is associated with the // own property. console.log(foo.bar); // 10 // delete the own property within the // foo object. delete foo.bar; // returns true // foo.bar is still avai...
...And 3 more matches
typeof - JavaScript
the typeof operator returns a string indicating the type of the unevaluated 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. ...
...s 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 typeof operator is followed by its operand: typeof operand typeof(operand) parameters operand an expression representing the object or primitive whose type is to be returned. description the following table summarizes the possible return values of typeof. for more information about types and primitives, see also the javascript data structure page. ...
...and typeof(operand) parameters operand an expression representing the object or primitive whose type is to be returned. description the following table summarizes the possible return values of typeof. for more information about types and primitives, see also the javascript data structure page. ...
...And 3 more matches
Trailing commas - JavaScript
trailing commas (sometimes called "final commas") can be useful when adding new elements, parameters, or properties to javascript code. if you want to add a new property, you can simply add a new line without modifying the previously last line if that line already uses a trailing comma. this makes version-control diffs cleaner and editing code might be less troublesome. javascript has allowed trailing commas in array literals since the beginning, and later added them to object literals (ecmascript 5) and most recently (ecmascript 2017) to function parameters. json, however, disallows trailing commas. syntax , examples trailing commas in literals arrays javascript ignores trailing commas in arrays: var arr = [ 1, 2, 3, ]; arr; // [1, 2, 3] arr.length; // 3 if more than one tr...
...d sparse (a dense array has no holes). when iterating arrays for example with array.prototype.foreach() or array.prototype.map(), array holes are skipped. var arr = [1, 2, 3,,,]; arr.length; // 5 objects starting with ecmascript 5, trailing commas in object literals are legal as well: var object = { foo: "bar", baz: "qwerty", age: 42, }; trailing commas in functions ecmascript 2017 allows trailing commas in function parameter lists. parameter definitions the following function definition pairs are legal and equivalent to each other. trailing commas don't affect the length property of function declarations or their arguments object. function f(p) {} function f(p,) {} (p) => {}; (p,) => {}; the trailing comma also works with method definitions for classes or objects: class c...
...airs are legal and equivalent to each other. trailing commas don't affect the length property of function declarations or their arguments object. ...
...And 3 more matches
Progressive web app structure - Progressive web apps (PWAs)
server-side rendering (ssr) means a website is rendered on the server, so it offers quicker first load, but navigating between pages requires downloading new html content. it works great across browsers, but it suffers in terms of time navigating between pages and therefore general perceived performance — loading a page requires a new round trip to the server. client-side rendering (csr) allows the website to be updated in the browser almost instantly when navigating to different pages, but requires more of an initial download hit and extra rendering on the client at the beginning. the website is slower on an initial visit, but can be faster to navigate. mixing ssr with csr can lead to the best results — you can render a website on the server, cache its contents, and then update th...
...d. the first page load is quick because of the ssr, and the navigation between 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 loadin...
...t visits before then loading all the contents of the app. that way, the next time someone visits the app from the device, the ui loads from the cache immediately and any new content is requested from the server (if it isn’t available in the cache already). this structure is fast, and also feels fast as the user sees "something" instantly, instead of a loading spinner or a blank page. ...
...And 3 more matches
d - SVG: Scalable Vector Graphics
Web › SVG › Attribute › d
the d attribute defines a path to be drawn. a path definition is a list of path commands where each command is composed of a command letter and numbers that represent the command parameters. the commands are detailed below. three elements have this attribute: <path>, <glyph>, and <missing-glyph> html,body,svg { height:100% } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <path fill="none" stroke="red" d="m 10,30 a 20,20 0,0,1 50,30 a 20,20 0,0,1 90,30 q 90,60 50,90 q 10,60 10,30 z" /> </svg> path for <path>, d is a string containing a series of path commands that define the path to be drawn. value <string> default value none animatable yes glyph warning: as of svg2 <glyph> is deprecated...
...posed of a command letter and numbers that represent the command parameters. svg defines 6 types of path commands, for a total of 20 commands: moveto: m, m lineto: l, l, h, h, v, v cubic bézier curve: c, c, s, s quadratic bézier curve: q, q, t, t elliptical arc curve: a, a closepath: z, z note: commands are case-sensitive. an upper-case command specifies absolute coordinates, while a lower-case command specifies coordinates relative to the current position. it is always possible to specify a negative value as an argument to a command: negative angles will be anti-clockwise; absolute negative x and y values are interpreted as negative coordinates; relative negative x values move to the left, and relative negative y values move upwards. moveto path commands moveto instruct...
...setting it down somewhere else—in other words, moving the current point (po; {xo, yo}). there is no line drawn between po and the new current point (pn; {xn, yn}). command parameters notes m (x, y)+ move the current point to the coordinate x,y. any subsequent coordinate pair(s) are interpreted as parameter(s) for implicit absolute lineto (l) command(s) (see below). formula: pn = {x, y} m (dx, dy)+ move the current point by shifting the last known position of the path by dx along the x-axis and by dy along the y-axis. any subsequent coordinate pair(s) are interpreted as parameter(s) for implicit relative lineto (l) command(s) (see below). formula: pn = {xo + dx, yo + dy} examples html,body,svg { height:100% } ...
...And 3 more matches
requiredFeatures - SVG: Scalable Vector Graphics
features 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 to a set of attributes, properties or elements, in others they represent some functionality...
...ity 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. ...
...strings are considered deprecated. ...
...And 3 more matches
transform - SVG: Scalable Vector Graphics
f svg2, transform is a presentation attribute, meaning it can be used as a css property. however, be aware that there are some difference in syntax between the css property and the attribute. see the documentation for the css property transform for the specific syntax to use in that case. as a presentation attribute, transform can be used by any element (in svg 1.1, only these 16 elements were allowed to use it: <a>, <circle>, <clippath>, <defs>, <ellipse>, <foreignobject>, <g>, <image>, <line>, <path>, <polygon>, <polyline>, <rect>, <switch>, <text>, and <use>). also, as a legacy from svg 1.1, <lineargradient> and <radialgradient> support the gradienttransform attribute, and <pattern> supports the patterntransform attribute, both of which act exactly like the transform attribute. ...
...olyline>, <rect>, <switch>, <text>, and <use>). also, as a legacy from svg 1.1, <lineargradient> and <radialgradient> support the gradienttransform attribute, and <pattern> supports the patterntransform attribute, both of which act exactly like the transform attribute. value <transform-list> default value none animatable yes transform functions the following transform functions can be used by the transform attribute <transform-list> warning: as per the spec, you should be able to also use css transform functions. however, the compatibility isn't guaranteed. matrix the matrix(<a> <b> <c> <d> <e> <f>) transform function specifies a transformation in the form of a transformation matrix of six values. matrix(a,b,c,d,e,f) is equivalent to applying t...
...aranteed. matrix the matrix(<a> <b> <c> <d> <e> <f>) transform function specifies a transformation in the form of a transformation matrix of six values. ...
...And 3 more matches
SVG animation with SMIL - SVG: Scalable Vector Graphics
although chrome 45 deprecated smil in favor of css animations and web animations, the chrome developers have since suspended that deprecation. firefox 4 introduced support for animating svg using synchronized multimedia integration language (smil). smil allows you to: animate the numeric attributes of an element (x, y, ...) animate transform attributes (translation or rotation) animate color attributes follow a motion path this is done adding an svg element like <animate> inside the svg element to animate. below are examples for the four different ways. animating attributes of an element the following example animates the cx attribute of a circle. to do so, we add an <animate> element inside the <circle> element. the important attributes for <animate> are: attributenam...
...indefinite" /> </circle> </svg> animating the transform attributes the <animatetransform> element let you animate transform attributes. this new element is necessary because we are not animating a simple attribute like x which is just a number. rotation attributes look like this: rotation(theta, x, y), where theta is the angle in degrees, and x and y are absolute positions. in the example below, we animate the center of the rotation and the angle. <svg width="300" height="100"> <title>svg smil animate with transform</title> <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" /> <rect x="0" y="50" width="15" height="34" fill="blue" stroke="black" stroke-width="1"> <animatetransform attributename="transform" begin="0s" dur="20s" ...
... example 1: linear motion in this example, a blue circle bounces between the left and right edges of a black box, over and over again, indefin...
...And 3 more matches
Using custom elements - Web Components
ed batch of elements that together provide a custom page feature. this article introduces the use of the custom elements api. note: custom elements are supported by default in firefox, chrome, and edge (76). opera and safari so far support only autonomous custom elements. high-level view the controller of custom elements on a web document is the customelementregistry object — this object allows you to register a custom element on the page, return information on what custom elements are registered, etc. to register a custom element on the page, you use the customelementregistry.define() method. this takes as its arguments: a domstring representing the name you are giving to the element. note that custom element names require a dash to be used in them (kebab-case); they can't be sing...
...ou are giving to the element. note that custom element names require a dash to be used in them (kebab-case); they can't be single words. a class object that defines the behaviour of the element. optionally, an options object containing an extends property, which specifies the built-in element your element inherits from, if any (only relevant to customized built-in elements; see the definition below). so for example, we can define a custom word-count element like this: customelements.define('word-count', wordcount, { extends: 'p' }); the element is called word-count, its class object is wordcount, and it extends the <p> element. a custom element's class object is written using standard es 2015 class syntax. for example, wordcount is structured like so: class wordcount extends htmlparag...
...e callbacks inside the class, which run at specific points in the element's lifecycle. for example, connectedcallback is invoked each time the custom element is appended into a document-connected element, while attributechangedcallback is invoked when one of the custom element's attributes is added, removed, or changed. you'll learn more about these in the using the lifecycle callbacks section below. there are two types of custom elements: autonomous custom elements are standalone — they don't inherit from standard html elements. you use these on a page by literally writing them out as an html element. for example <popup-info>, or document.createelement("popup-info"). customized built-in elements inherit from basic html elements. to create one of these, you have to specify which eleme...
...And 3 more matches
Using shadow DOM - Web Components
edge (75 and onwards) supports it too; the old edge didn't. high-level view this article assumes you are already familiar with the concept of the dom (document object model) — a tree-like structure of connected nodes that represents the different elements and strings of text appearing in a markup document (usually an html document in the case of web documents). ...
... 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 ...
... 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 d...
...And 3 more matches
XPath snippets - XPath
this article provides some xpath code snippets—simple examples of how to a few simple utility functions based on standard interfaces from the dom level 3 xpath specification that expose xpath functionality to javascript code. the snippets are functions you can use in the real world in your own code. node-specific evaluator function the following custom utility function can be used to evaluate xpath expressions on given xml nodes. the first argument is a dom node or document object, while the second is a string defining an xpath expression. example: defining a custom node-specific evaluatexpath() utility function // evaluate an xpath expression aexpression against a given dom node // or document object (anode), returning the results as an array // thanks wanderingstan at morethan...
...r found = []; var res; while (res = result.iteratenext()) found.push(res); return found; } this function uses the new xpathevaluator() constructor, which is supported in firefox, chrome, opera and safari, but not in edge or internet explorer. ...
...o default namespace is being used (though see document.creatensresolver for a workaround)). otherwise, you have to provide your own implementation of xpathnsresolver. if you are using xmlhttprequest to read a local or remote xml file into a dom tree (as described in parsing and serializing xml), the first argument to evaluatexpath() should be req.responsexml. ...
...And 3 more matches
PI Parameters - XSLT: Extensible Stylesheet Language Transformations
overview xslt supports the concept of passing parameters to a stylesheet when executing it. this has been possible for a while when using the xsltprocessor in javascript. however when using an <?xml-stylesheet?> processing instruction (pi) there used to be no way to provide parameters. to solve this two new pis are implemented in firefox 2 (see supported versions below for details), <?xslt-param?> and <?xslt-param-namespace?>. both pis can contain "pseudo attributes" the same way that the xml-stylesheet pi does. the following document passes the two parameters "color" and "size" to the stylesheet "style.xsl". <?xslt-param name="color" value="blue"?> <?xslt-param name="size" select="2"?> <?xml-stylesheet type="text/xsl" href="style.xsl"?> note that these pis have no effect when transfor...
...se pis have no effect when transformation is done using the xsltprocessor object in javascript. processing instructions the attributes in the xslt-param and xslt-param-namespace pis are parsed using the rules defined in xml-stylesheet. any unrecognized attributes must be ignored. parsing of any attribute must not fail due to the presence of an unrecognized attribute as long as that attribute follows the syntax in xml-stylesheet. both the xslt-param and the xslt-param-namespace pis must appear in the prolog of the document, i.e. before the first element tag. all pis in the prolog must be honored, both ones occurring before and onces occurring after any xml-stylesheet pis. if there are multiple xml-stylesheet pis the parameters apply to all stylesheets as a consequence of that all styleshee...
... the context node is the node used as initial current 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 stylesh...
...And 3 more matches
Compiling from Rust to WebAssembly - WebAssembly
wasm-pack, a tool for building npm packages in rust. this package will contain only webassembly and javascript code, and so the users of the package won't need rust installed. they may not even notice that it's written in webassembly. rust environment setup let's go through all the required steps to get our environment set up. install rust install rust by going to the install rust page and following the instructions. this installs a tool called "rustup", which lets you manage multiple versions of rust. by default, it installs 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 ...
.... note: pay attention to the post-install note about needing cargo's bin directory in your system path. this is added automatically, but you must restart your terminal for it to take effect. wasm-pack to build the package, we need an additional tool, wasm-pack. this helps compile the code to webassembly, as well as produce the right packaging for npm. to download and install it, enter the following command into your terminal: $ cargo install wasm-pack install node.js we are building an npm package in this tutorial, and so you need to have node.js and npm installed. to get node.js and npm, go to the get npm! page and follow the instructions. when it comes to picking a version, choose any one you'd like; this tutorial isn't version-specific. building our webassembly npm package enoug...
...rd 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 the next section. before we move on to the next section, we should talk a bit more about wasm-bindgen. wasm-pack uses wasm-bindgen, another tool, to provide a bridge between the types of javascript and rust. it allows javascript to call a rust api with a string, or a rust function to catch a javascript exception. we use wasm-bindgen's functionality in our package. in fact, that's the next section. calling external functions in javascript from rust the next part looks like this: #[wasm_bindgen] extern { pub fn alert(s: &str); } the bit inside the #[ ] is called an "attribute", and it modifies the next...
...And 3 more matches
Private Properties - Archive of obsolete content
ins how to work with the particular namespace implementation used by the sdk. it is possible to read this section on its own, but to fully appreciate how namespaces work, and the problem they set out to solve, it is recommended to read the entire article. using prefixes a common technique to implement private properties is to prefix each private property name with an underscore. consider the following example: function point(x, y) { this._x = x; this._y = y; } the properties _x and _y are intended to be private, and should only be accessed by member functions. to make a private property readable/writable from any function, it's common to define getter/setter functions for the property, respectively: point.prototype.getx = function () { return this._x; }; point.prototype.se...
...jects of the same class to access each other's private properties. using weakmaps the techniques above are either not restrictive enough (prefixes) or too restrictive (closures), however the recent introduction of weakmaps provides a solution. weakmaps were introduced to javascript in ecmascript 2015 and have recently been implemented in spidermonkey. before explaining how weakmaps work, the following looks at how ordinary objects can be used as hash maps, by creating a simple image cache: let images = {}; function getimage(name) { let image = images[name]; if (!image) { image = loadimage(name); images[name] = image; } return image; } now suppose there's a need to associate a thumbnail with each image. moreover, to create each thumbnail only when it's fir...
...rresponding image has gone out of scope. this is a memory leak waiting to happen. the above two problems are exactly what weakmaps were designed to solve. a weakmap is very similar to an ordinary hash map, but differs from it in two crucial ways: it can use ordinary objects as keys it does not maintain a strong reference to its values to understand how weakmaps are used in practice, the following rewrites the thumbnail cache using a weakmap: let thumbnails = new weakmap(); function getthumbnail(image) { let thumbnail = thumbnails.get(image); if (!thumbnail) { thumbnail = createthumbnail(image); thumbnails.set(image, thumbnail); } return thumbnail; } this version suffers from none of the problems we mentioned earlier. when a thumbnail's image goes out...
...And 2 more matches
page-worker - Archive of obsolete content
cript.js"></script> in the page header. in the "main.js" file: remove the contentscriptfile option in the page() constructor. globals constructors page(options) creates an uninitialized page worker instance. parameters options : object optional options: name type contenturl string the url of the content to load in the panel. allow object an object with keys to configure the permissions on the page worker. the boolean key script controls if scripts from the page are allowed to run. script defaults to true. include string, regexp, array of (string or regexp) this is useful when your page worker loads a page which will redirect to other pages. a match pattern str...
...ontent scripts for help on setting this property. contentscript string,array a string or an array of strings containing the texts of content scripts to load. content scripts specified by this option are loaded after those specified by the contentscriptfile option. contentscriptwhen string when to load the content scripts. ...
...vents. parameters type : string the type of event to listen for. listener : function the listener function that handles the event. removelistener(type, listener) unregisters an event listener from the page worker. parameters type : string the type of event for which listener was registered. listener : function the listener function that was registered. ...
...And 2 more matches
passwords - Archive of obsolete content
redential consists of a username and a password. using this module you can: search for credentials which have been stored in the password manager. you can then use the credentials to access their related service (for example, by logging into a web site). store credentials in the password manager. you can store different sorts of credentials, as outlined in the "credentials" section below. remove stored credentials from the password manager. credentials in this api, credentials are represented by objects. you create credential objects to pass into the api, and the api also returns credential objects to you. the sections below explain both the properties you should define on credential objects and the properties you can expect on credential objects returned by the api. ...
...ude username and password properties. different sorts of stored credentials include various additional properties, as outlined in this section. you can use the passwords api with three sorts of credentials: add-on credentials html form credentials http authentication credentials add-on credential these are associated with your add-on rather than a particular web site. they contain the following properties: username the username. password the password. url for an add-on credential, this property is of the form: addon:<addon-id>, where <addon-id> is the add-on's program id. you don't supply this value when storing an add-on credential: it is automatically generated for you. however, you can use it to work out which stored cred...
... manager, under "site", in brackets after the url. for example, if the realm for a credential is "user registration", then its "site" field will look something like: addon:jid0-01mbbfyu0zaxcfub1jykoostkic (user registration) html form credential if a web service uses html forms to authenticate its users, then the corresponding credential is an html form credential. it contains the following properties: username the username. password the password. url the url for the web service which requires the credential. you should omit anything after the hostname and (optional) port. formsubmiturl the value of the form's "action" attribute. you should omit anything after the hostname and (optional) port. if the form doesn't contain an ...
...And 2 more matches
tabs - Archive of obsolete content
("html", function(message) { console.log(message) }) }); note that tab.attach is tab-centric: if the user navigates to a new page in the same tab, then the worker and content scripts will be reattached to the new page. attaching stylesheets new in firefox 34. you can't attach style sheets to a tab using tab.attach(), but from firefox 34 onwards you can attach and detach them using the low-level stylesheet/style and content/mod apis. here's an add-on that uses a toggle button to attach a stylesheet to the active tab, and detach it again. the stylesheet is called "style.css" and is located in the add-on's "data" directory: var tabs = require("sdk/tabs"); var { attach, detach } = require('sdk/content/mod'); var { style } = require('sdk/stylesheet/style'); var { togglebutton } = requ...
... tabs hosted by private browser windows won't be seen if you enumerate the tabs module itself, and you won't receive any events for them. 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. converting to xul tabs to convert from the high-level tab objects used in this api to the low-level xul tab objects used in the tabs/utils api and by traditional add-ons, use the viewfor() function exported by the viewfor module. to convert back the other way, from a xul tab to a high-level tab object, use the modelfor() function, exported by the modelfor module. here's an example converting from a high-level tab to a xul tab and then back the other way: var { modelfor } = require("sdk...
...ther way, from a xul tab to a high-level tab object, use the modelfor() function, exported by the modelfor module. ...
...And 2 more matches
content/symbiont - Archive of obsolete content
als constructors symbiont(options) creates a content symbiont. parameters options : object optional options: name type frame object the host application frame in which the page is loaded. if frame is not provided hidden one will be created. contentscriptwhen string when to load the content scripts. ...
... all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires this property is optional and defaults to "end". contentscriptoptions object read-only value exposed to content scripts under self.options property. any kind of jsonable value (object, array, string, etc.) can be used here. optional. allow object permissions for the content, with the following keys: script boolean whether or not to execute script in the content. defaults to true. optional. optional. symbiont symbiont is composed from the worker trait, therefore instances of symbiont and their descendants expose all the public properties exposed by worker along with additional public pr...
...content scripts specified by this property are loaded before those specified by the contentscript property. contentscript the texts of content scripts to load. content scripts specified by this property are loaded after those specified by the contentscriptfile property. ...
...And 2 more matches
package.json - Archive of obsolete content
defaults to an empty string. it may include a optional url in parentheses and an email address in angle brackets. this value will be used as the add-on's em:creator element in the install.rdf file generated by cfx. note: jpm supports nodejs people fields. ...
...on field in package.json and put your icon named "icon.png" in the root directory of your add-on. if no icon is specified, the standard add-on icon will be used by default. when using jpm, using a relative path to the data directory (to make it re-usable for add-on html content) does not work. you can generate the url to your add-on icon in the data directory using the url format below, where "your-addon-name" is the value in the name field of package.json. resource://@your-addon-name/data/your-icon-name.png this value will be used as the add-on's em:iconurl element in its install.rdf. the icon may be up to 48x48 pixels in size. a larger icon will work, but may either scaled and possibly distorted) or might break parts of firefox ui. (if you test this, pleas...
... is deprecated along with cfx and is not available when using jpm. license the name of the license under which the add-on is distributed, with an optional url in parentheses. defaults to "mpl-2.0". note: it is recommended that you use an spdx license id. locales an object holding json objects referenced by a locale name that use the following keys: title, description and homepage. these json objects will be used to localizations for the add-on's meta data shown within the add-ons manager. see the documentation for how to localize the add-on's meta data. main a string representing the name of a program module that is located in one of the top-level module directories specified by lib. defaults to "index.js"...
...And 2 more matches
Getting started (cfx) - Archive of obsolete content
once you've done that, you'll be looking at a command prompt. ...
...eadme.md written * package.json written * test/test-main.js written * lib/main.js written * doc/main.md written your sample add-on is now ready for testing: try "cfx test" and then "cfx run". have fun!" implementing the add-on now you can write the add-on's code, which goes in the "main.js" file in your "lib" directory. this file was created for you in the previous step. open it and add the following code: var buttons = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = buttons.actionbutton({ id: "mozilla-link", label: "visit mozilla", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onclick: handleclick }); function handleclick(state) { tabs.open("https://www.mozilla.org/"); } save the file. next, save ...
... should see a message like: exporting extension to my-addon.xpi. to test that this worked, try installing the xpi file in your own firefox installation. you can do this by pressing the ctrl+o key combination (cmd+o on mac) from within firefox, or selecting the "open" item from firefox's "file" menu. this will bring up a file selection dialog; navigate to the "my-addon.xpi" file, open it and follow the prompts to install the add-on. summary in this tutorial we've built and packaged an add-on using three commands: cfx init to initialize an empty add-on template cfx run to run a new instance of firefox with the add-on installed, so we can try it out cfx xpi to package the add-on into an xpi file for distribution these are the three main commands you'll use when developing sdk add-ons...
...And 2 more matches
Unit Testing - Archive of obsolete content
if you're migrating test code from cfx to jpm, see the guide to migrating from cfx, in particular the section on loading modules from test code. the sdk provides a framework to help create and run unit tests for your code. to demonstrate how it works we'll write some unit tests for a simple base64 encoding module. a simple base64 module in a web page, you can perform base64 encoding and decoding using the btoa() and atob() functions. unfortunately these functions are attached to the window object: since this object is not available in your main add-on code, atob() and btoa() aren't available either. ...
... these functions are attached to the window object: since this object is not available in your main add-on code, atob() and btoa() aren't available either. so we'll create a base64 module to expose these functions from the platform (see creating reusable modules). to begin with, create a new directory, navigate to it, and run jpm init. ...
...ry, navigate to it, and run jpm init. now create a new file called "base64.js", and give it the following contents: const { atob, btoa } = require("resource://gre/modules/services.jsm"); exports.atob = a => atob(a); exports.btoa = b => btoa(b); this code exports two functions, which just call the platform's btoa() and atob() functions. ...
...And 2 more matches
Miscellaneous - Archive of obsolete content
tion. example for firefox: services.startup.quit(services.startup.eforcequit|services.startup.erestart); mouse and keyboard detecting mouse wheel events when scrolling the mouse wheel on an element, the dommousescroll event fires. event.detail contains the number of lines to scroll. this event is mozilla-only; other browsers may support window.onmousewheel. <div id="scrollarea" style="overflow: scroll; height: 6em; width: 10em;"> this is the scrolling area. this is the scrolling area. this is the scrolling area. this is the scrolling area. this is the scrolling area. this is the scrolling area. this is the scrolling area. this is the scrolling area. this is the scrolling area. this is the scrolling area. this is the scrolling area. this is the scrolling area. </...
... //event.detail is positive for a downward scroll, negative for an upward scroll alert("scrolling " + event.detail + " lines"); }, false); </script> if you do not receive a dommousescroll event while holding any of the modifier keys (ctrl,shift,alt,meta) you should check the mousewheel.withcontrolkey.action and related preferences. the meaning of the action preference is shown in the following table mousewheel.withxxxkey.action result 0 scroll by lines. if set, you will receive dommousescroll events. 1 scroll by page. 2 move around in the history. if set, you will not receive dommousescroll events. 3 change text size. if set, you will not receive dommousescroll events. you can listen to mouse wheel click events just...
...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 propertie...
...And 2 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
ensionevent. var myextension = { mylistener: function(evt) { alert("received from web page: " + evt.target.getattribute("attribute1") + "/" + evt.target.getattribute("attribute2")); } } document.addeventlistener("myextensionevent", function(e) { myextension.mylistener(e); }, false, true); // the last value is a mozilla-specific value to indicate untrusted content is allowed to trigger the event. the data from the web page (unprivileged code) will be the values of attribute1 and attribute2. to trigger the alert() in the listener and pass the data from the web page, write code such as this in the web page: var element = document.createelement("myextensiondataelement"); element.setattribute("attribute1", "foobar"); element.setattribute("attribute2", "hello world")...
... var mainwindow = window.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsiwebnavigation) .queryinterface(components.interfaces.nsidocshelltreeitem) .roottreeitem .queryinterface(components.interf...
...stener("myextensionevent", function(e) { myextension.mylistener(e); }, false, true); if you need to to pass lots of data, consider using cdata sections instead of the simple attributes on a custom element. note: if you're using html5's postmessage() to send a message from unprivileged code to privileged code, adding 'true' to the end of your event listener in your privileged chrome code will allow the message to be received. document.addeventlistener("message", function(e) { yourfunction(e); }, false, true); sending data from chrome to unprivileged document to "answer" the web page (e.g., return code), your extension can set an attribute or attach child elements on the event target element (<myextensiondataelement/> in this example). you can optionally clean up the created element, o...
...And 2 more matches
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
nal linkage will not be available in firefox 3. this document is a guide to common code patterns that may need to change to work with frozen linkage. strings the most obvious change required by frozen linkage is using the frozen string api. - #include "nsastring.h"- #include "nsstring.h"- #include "nsreadableutils.h"- #include "nsescape.h" + #include "nsstringapi.h" on windows, if you see the following error, you are including a header you shouldn't be: nsstringfwd.h(60) : fatal error c1001: internal compiler error to debug this error, make in the failing directory, adding the /showincludes directive to figure out what is being included incorrectly: make -c directory/that/failed os_cppflags=-showincludes the frozen string api is similar but not identical to the nonfrozen string api. the fr...
...(ns_stringinputstream_contractid, &rv);+ ns_ensure_success(rv, rv);++ rv = rawstream->setdata((const char*)data, length); ns_ensure_success(rv, rv); nsistringinputstream is not frozen (and thus, not available in the gecko sdk as currently published). in order to use this interface in your code, you will need to get the idl files from the source (via cvs, from a tarball, or using lxr). the following functions, however, are implemented in the glue library and can be used from frozen-linkage code: ns_newarrayenumerator (excluding deprecated nsisupportsarray version) ns_newemptyenumerator ns_newunionenumerator nscrt functions in nscrt.h are not available to frozen-linkage code. some of the constants are still useful though. - #include "nscrt.h" + #include <string.h> const char *str = "f...
...sgutils.h header is being enhanced to fill in some of the gaps caused by the differences between the internal and external apis. these enhancements make it easier to write code that will transparently compile using either api. the list of enhancements fall in to three categories. changes to internal apis to make them compatible with the external api. #define caseinsensitivecompare pr_true this allows you to use caseinsensitivecompare as the parameter to various string methods that normally accept pr_true under the internal api. #define tointeger(prv, radix) tointeger(reinterpret_cast<print32*>(prv), radix) this allows you to pass a pointer to an nsresult to the tointeger method, when it normally accepts a print32. note that you must pass the radix (normally 10). changes to external apis to ...
...And 2 more matches
Chapter 1: Introduction to Extensions - Archive of obsolete content
this document was authored by hideyuki emura and was originally published in japanese for the firefox developers conference summer 2007. emura-san is a co-author of firefox 3 hacks (o'reilly japan, 2008.) introduction if you're reading this guide, you’ve probably used firefox before. perhaps the first time you looked at firefox, you may have been surprised to see that it has a much simpler structure than other full-featured browsers, such as opera or safari. ...
...ures through extensions. the core browser is limited to basic features, so it’s something that a beginner can be comfortable with, but users who want something beyond that can install extensions. about extensions management using the add-ons manager firefox's add-ons manager is an excellent way to manage extensions, and is a great step up in ease of use. ...
...opment environment amenities initially, there wasn't adequate documentation available, and extension developers were largely left to fend for themselves1; however, now there's a considerable store of knowledge. because firefox and its extensions are designed to support multiple languages, excellent extensions come from all over the world, and can be quickly localized by anyone interested. this lowers the threshold both to using and to developing extensions; that fact, combined with firefox's rapidly growing popularity, has created a positive feedback loop, with the number of extension users and extension developers growing explosively—there are now more than 7000 extensions and themes published at the firefox add-ons site (https://addons.mozilla.org). what you can do with extensions le...
...And 2 more matches
Custom XUL Elements with XBL - Archive of obsolete content
pete" greeting="good morning" image="" />, then those attribute values are "inherited" to the content nodes that have this special attribute. the value attribute of the xul:label element would be "pete". the oncommand attribute of the button has some code you've probably never seen before: document.getbindingparent(this). this code gets the dom object that corresponds to the xshelloperson tag, allowing you access to its methods and properties. in this case we're calling the remove method, which we will discuss later on. if you need to create a container element, or any other element that has child nodes, you can use the xbl children tag in your content to indicate the place where the child nodes will be inserted. the includes attribute gives you a little more flexibility with children, but...
...tribute( this, "anonid", "xulshoolhello-name-label"); implementation the implementation section defines most of the scripting side of your element. here you can define methods and properties, as well as a constructor and a destructor for your element. javascript code is enclosed in cdata sections to prevent js and xml syntax conflicts. properties and fields the field and property tags allow you to handle element variables and access them from outside of the element. a field holds a value that can be changed, except when the readonly attribute is set. it's very similar to a js object variable, and we generally use a field for private variables inside of the element. <field name="fieldname">defaultvalue</field> from inside your binding methods, you can access fields with: th...
...rom inside your binding methods, you can access fields with: this.fieldname you can also access them from outside of the element, if you have a reference to it: elementref.fieldname just like with js objects, all fields are publicly accessible, and we use a "_" to indicate a field is "private". a property is a little more robust. it is defined using a getter and setter method, allowing read-only and write-only properties, as well as more complex behavior. there are two properties defined in our binding, which are just meant for easier access to the two text attributes in the element. we use the shorthand version of the property tag: <property name="name" onget="return this.getattribute('name');" onset="this.setattribute('name', val);" /> there's a less compact versio...
...And 2 more matches
Promises - Archive of obsolete content
promise apis for common asynchronous operations due to the performance and stability costs of synchronous io, many apis which rely on it have been deprecated. the following page contains examples of many promise-based replacement apis for common operations. these apis allow asynchronous operation to be achieved with a coding style similar to synchronous variants. the following examples make use of the task api, which harnesses generator functions to remove some of the syntactic clutter of raw promises, such that asynchronous promise code more closely resembles synchronous, procedural code. ...
...ment apis for common operations. these apis allow asynchronous operation to be achieved with a coding style similar to synchronous variants. the following examples make use of the task api, which harnesses generator functions to remove some of the syntactic clutter of raw promises, such that asynchronous promise code more closely resembles synchronous, procedural code. ...
...content); // make the second request. resp = yield new promise((resolve, reject) => { let xhr = new xmlhttprequest; xhr.onload = resolve; xhr.onerror = reject; xhr.open("post", updateurl); xhr.send(form); }); // use the response of the second request. notifyuser(resp.target.responsetext); }); example using promise-based helper the following example relies on the helper function defined below. task.spawn(function* () { // make the initial request. let xhr = yield request(dataurl, { responsetype: "json" }); let data = xhr.response; // use the response to construct form data object for the // second request. let form = new formdata; form.append("id", data.id); form.append("content", data.content); ...
...And 2 more matches
Index of archived content - Archive of obsolete content
.htaccess ( hypertext access ) 2015 mdn fellowship program api navigator navigator.moznotification add-ons add-on sdk builder guides content scripts communicating with other scripts communicating using "port" communicating using "postmessage" cross-domain content scripts interacting with page scripts loading content scripts reddit example port self ...
...panel passwords private-browsing querystring request selection self simple-prefs simple-storage system tabs timers ui url widget windows low-level apis /loader chrome console/plain-text console/traceback content/content content/loader content/mod content/symbiont content/worker core/heritage core/namespace core/promise dev/panel ...
...or console exception logging in javascript existing content extension frequently asked questions external cvs snapshots in mozilla-central fast graphics performance with html firefox block and line layout cheat sheet content states and the style system disabling interruptible reflow document loading - from load start to finding a handler documentation for bidi mozilla downloading nightly or trunk builds jss build instructions for osx 10.6 layout faq layout system overview multiple firefox profiles repackaging firefox style system overview using microformats...
...And 2 more matches
Source Navigator - Archive of obsolete content
ource-navigator's build system to automatically generate a makefile. source-navigator works with the insight gui interface for gdb. more information can be found here --> http://sourcenav.sourceforge.net/ why worth a try? it's quite fast as compared to mxr. (i think.) you can specify whether it's the declaration/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 c...
...a class hierarchy quite easily (unfortunately, not for classnames which are defined by macro.) installing source navigator in ubuntu execute the following line in a terminal window: sudo apt-get install sourcenav this should install source-navigator. one can check whether the installation is complete by executing: $ which snavigator /usr/bin/snavigator importing the source execute the following: snavigator. this triggers a splash screen, followed by a "source-navigator projects" dialog as the following: i've already created a new project bin.proj before documenting this. ...
...execute the following: snavigator. this triggers a splash screen, followed by a "source-navigator projects" dialog as the following: i've already created a new project bin.proj before documenting this. if this is your first time to open source navigator, the big white box on the left of the dialog should contain no lines. click "new project". this shows the "auto-create project" dialog: which allows you to decide your filename of the project file (which ends in .proj) and your source directory/directories that you want to import into the project. ...
...And 2 more matches
Drag and Drop - Archive of obsolete content
next » as of gecko 1.9.1 (firefox 3.5), these apis are officially deprecated the newer, simpler, portable api should be used in their place. this section describes how to implement objects that can be dragged around and dropped onto other objects. the drag and drop interface many user interfaces allow one to drag particular objects around within the interface. for example, dragging files to other directories, or dragging an icon to another window to open the document it refers to. mozilla and xul provide a number of events that can handle when the user attempts to drag objects around. a user can start dragging by holding down the mouse button and moving the mouse. the drag stops when the user releases the mouse. event handlers are called when the user starts and ends draggi...
...ion handles updating the mouse cursor and where the object should be dropped. if something cannot be dragged, it should not start a drag session. because the user generally has only one mouse, only one drag session is in use at a time. note that drag sessions can be created from within mozilla itself or from other applications. mozilla will translate the data being dragged as needed. the list below describes the event handlers that can be called, which may be placed on any element. you only need to put values for the handlers where you need to do something when the event occurs. ondrag called periodically throughout the drag and drop operation. ondraggesture called when the user starts dragging the element, which normally happens when the user holds down the mouse button and moves th...
... is the drag session, nsidragsession. the nsidragservice is responsible for creating drag sessions when a drag starts, and removing the drag session when the drag is complete. the function invokedragsession should be called to start a drag inside an ondraggesture event handler. once this function is called, a drag has started. the function invokedragsession takes four parameters, as described below: invokedragsession(element, transferablearray, region, actions) element a reference to the element that is being dragged. this can be retrieved by getting the property event.target during the event handler. transferablearray an array of nsitransferable objects, one for each item being dragged. an array is used because you might want to drag several objects at once, such as a set of files. ...
...And 2 more matches
Documentation for BiDi Mozilla - Archive of obsolete content
ibm's international components for unicode (icu), which was chosen after comparing and testing 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 mbidienable...
...ew 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. ...
...igit. 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. ...
...And 2 more matches
JavaScript Client API - Archive of obsolete content
is managed and protected; (b) that your third party client will only store data in encrypted form on the firefox sync servers operated by mozilla; (c) that you and your third party client will use the firefox sync apis solely for their intended purpose; (d) that your third party client will not hide or mask its identity as it uses the services and/or firefox sync apis, including by failing to follow required identification conventions; and (e) that you and your third party client will not use the firefox sync apis for any application or service that replicates or attempts to replicate the services or firefox sync experience unless such use is non-confusing (by non-confusing, we mean that people should always know with whom they are dealing and where the information or software they are downl...
...tps://wiki.mozilla.org/services/sync for their contact information. to create a custom sync engine to synchronize a new data you, you'll need to define an engine object that extends the base syncengine object. this involves writing types that extend the store, tracker, and record types as well. it will be very helpful to look at an existing sync engine for guidance. have a look at one of the following files: services/sync/modules/engines/bookmarks.js services/sync/modules/engines/history.js setting up a js module the code for your custom sync engine should live in a js module. first off we're going to import the files mentioned above at the top the file. we're also going to import ''util.js'' as it contains many useful helpers. const cu = components.utils; cu.import("resource://serv...
...ts. 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. ...
...And 2 more matches
Introducing the Audio API extension - Archive of obsolete content
rk at any time. please note that this document describes a non-standard experimental api. this api has been deprecated since gecko 22, disabled since gecko 28, and removed from gecko 31. you should use the web audio api instead. reading audio streams the loadedmetadata event when the metadata of the media element is available, it triggers a loadedmetadata event. ...
...ad. reading audio streams the loadedmetadata event when the metadata of the media element is available, it triggers a loadedmetadata event. this event has the following attributes: mozchannels: number of channels mozsamplerate: sample rate per second mozframebufferlength: number of samples collected in all channels this information is needed later to decode the audio data stream. ...
...is done, the samples need to be created. those samples have the same format as the ones in the mozaudioavailable event. then the samples are written in the audio stream with the function mozwriteaudio(). it's important to note that not all the samples might get written in the stream. the function returns the number of samples written, which is useful for the next writing. ...
...And 2 more matches
Supporting private browsing mode - Archive of obsolete content
vatebrowsingenabled = true; /* this is all private */ pbs.privatebrowsingenabled = oldprivatemode; in this example, we save the current state of the private browsing mode setting in the oldprivatemode variable, then turn on private browsing by setting its value to true. from that point until we restore the original value of the private browsing mode setting, things are done privately. this allows us to, for example, work with the places database without affecting its contents. private browsing notifications there are notifications available that allow you to easily watch for changes to the status of the private browsing mode, including detecting when it turns on and off. in addition, there is a browser:purge-session-history notification that is sent when the browser purges private data ...
... this lets you passively monitor for changes in private browsing status. var listener = new privatebrowsinglistener(); listener.watcher = { onenterprivatebrowsing : function() { // we have just entered private browsing mode! }, onexitprivatebrowsing : function() { // we have just left private browsing mode! } }; canceling shutting off private browsing mode extensions...
...other considerations for extensions in some extensions, it's hard to decide whether the data retained by the extension should be written to disk in private browsing mode or not. in such a case, it is considered good practice for the extension to enable respecting the private browsing mode based on a preference specific to that extension, and set that preferenc...
...And 2 more matches
Table Cellmap - Border Collapse - Archive of obsolete content
introduction this document describes the additional information that is stored for border collapse tables in the cellmap. information storage each cellmap entry stores for tables in the border collapse mode additional information about its top and left edge and its top left corner. as one can see from the following illustration this is enough to cover a whole table. ...
... additional information about its top and left edge and its top left corner. as one can see from the following illustration this is enough to cover a whole table. only the right most edge and the bottom most edge of a table need to be stored in a different place. border for the top and left border we store the width and the owner of the border. the width is stored in pixel coordinates. ...
...gh to cover a whole table. only the right most edge and the bottom most edge of a table need to be stored in a different place. border for the top and left border we store the width and the owner of the border. the width is stored in pixel coordinates. ...
...And 2 more matches
Tamarin-central rev 703:2cee46be9ce0 - Archive of obsolete content
tamarin-central rev 703:2cee46be9ce0 was declared stable on 12/02/08. the announcement sent to tamarin-devel can be read here. testing summary acceptance tests have passed on the following supported platforms: * windows, 32 & 64 bit * mac ox x ppc & intel, 32 bit * linux, 32 bit * windows mobile arm version asc-4200 of the actionscript compiler was used for all tests. performance testsuite time metric the following is a comparison of the current tamarin-central (tc-703) versus the prior build (tc-700) as well as current against the vm in flash player 10. the key takeaway is that the interpreter is much improved. osdefault-jitinterpretedaggressive jit mac (os/x 10.4 i...
...tsuite time metric the following is a comparison of the current tamarin-central (tc-703) versus the prior build (tc-700) as well as current against the vm in flash player 10. the key takeaway is that the interpreter is much improved. ...
...c-700) as well as current against the vm in flash player 10. the key takeaway is that the interpreter is much improved. ...
...And 2 more matches
The new nsString class implementation (1999) - Archive of obsolete content
static void ensurecapacity(nsstrimpl& astring,pruint32 anewlength); static void growcapacity(nsstrimpl& astring,pruint32 anewlength); static void append(nsstrimpl& adest,const nsstrimpl& asource,pruint32 anoffset,print32 acount); st...
...ring, nsautostring and nscstring all offer additional api's (that all degrade to those 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 th...
...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 fully interoperates with nsstring and nsstrimpl. nscstring the new nscstring class shares the same api with nsstring, but uses a 1-byte ascii character storage model. this will allow programmers to use the nsstring api's like a standard char* without incurring the 2-byte per character overhead. this class fully interoperates with nsstring, nsautostring and nsstrimpl. nsistring naturally we will need include an nsistring interface onto the nsstrimpl/nsstring classes. i won't repeat it's interface here since it is basically a restatement (in xpcom terms) of the nsstring interfa...
...And 2 more matches
Using Breakpoints in Venkman - Archive of obsolete content
affect the execution of the code. for more information about the sorts of actions you can take in venkman when you're at a breakpoint, see the debugging basics section of the introductory venkman article. clearing breakpoints to clear the breakpoint, click on the margin twice. the first click will clear the hard breakpoint and leave you with only a future breakpoint, which is represented by a yellow letter "f". a second click will remove the future breakpoint as well. advanced breakpoints venkman allows you to associate a breakpoint with a script that will be executed in the scope of the function when that breakpoint is hit. this advanced 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-...
...vailable 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 program state. stop if result is true effectively makes this a conditional...
...se value will do), execution will continue normally. if, on the other hand, the script returns a false value, venkman will stop execution at that point. early return from caller with result will cause the function that the breakpoint is set in to return the value of the breakpoint script as its result, immediatley after the breakpoint script completes. the pass exceptions to caller checkbox allows you to pass exceptions thrown by the breakpoint script directly to the caller. normally, if the breakpoint script generates an exception, venkman assumes you made a mistake and stops execution after displaying the exception. if you would like to see what your code does when exceptions are thrown at it, check "pass exceptions to caller", and thrown an exception from the breakpoint script. the l...
...And 2 more matches
Event Handlers - Archive of obsolete content
the most basic handler specifies the event to listen for and an action to take when the handler fires. this action can be specified either using an action attribute or by specifying the script as a child of the handler element. if both are specified, the attribute wins. ...
...e event should be factored into normal javascript file. (note that there is a possibility that this may change in the future.) handlers are attached to the bound element, and they are registered by default for bubbling events. this means that <handler event="click" action="foo()"/> is analogous to onclick="foo()" defined on the bound element. the phase attribute specifies the phase of event flow that the handler is registered for. the default value is bubbling, which means that the event handler will fire during the bubbling phase. the other possible values are target, which means the handler will only fire if event.originaltarget is the same as the target to which the handler is attached, and capturing, which indicates the handler should fire during the capturing phase of event flow. x...
... will fire during the bubbling phase. the other possible values are target, which means the handler will only fire if event.originaltarget is the same as the target to which the handler is attached, and capturing, which indicates the handler should fire during the capturing phase of event flow. xbl event handlers always fire last, after all other event handlers at the same position in the event flow. since xbl handlers usually constitute the default actions for a widget, this allows authors in the bound document to write events that potentially suppress the default actions taken by the xbl handlers. within an xbl inheritance chain, event handlers always fire first on the derived binding and then on the base binding in the chain. a derived handler then has a way of preventing the event from ...
...And 2 more matches
Using XPInstall to Install Plugins - Archive of obsolete content
etscape gecko, which is at the core of the mozilla browser recent beta-only versions of the aol software based on netscape gecko, the layout engine of the mozilla project. caveats: aol time warner's compuserve browser, also based on netscape gecko, does not support xpinstall. netscape communicator 4.x does not support xpinstall. what does a plugin consist of? plugins can consist of the following types of files, all of which can be installed via an xpi package: shared libraries (i.e. on windows, these are dlls, on unix these are *.so files). these files are native code files made with the netscape plugin api. if the plugin is scriptable, then it will also consist of an xpt file. examples would be flash 6r47 on windows, which consists of a dll (called npswf32.dll) and an xpt file for...
...n addition to that of the plugins directory of the current browser. ...
...the plugin identifier (or plid) is a useful concept that is also applicable when initializing the installation via the initinstall api. ...
...And 2 more matches
Writing to Files - Archive of obsolete content
and the second is a set of flags which control the writing. in this case, the 'text' flag is used which indicates that you will be writing text to the file. when writing text files, characters are writing using a chosen character set, encoded automatically. the default character set is 'utf-8' but this can be changed using an additional, yet optional, argument to the newoutputstream method. see below for more details about this. creating and appending to files a number of flags control whether a new file is created when writing or whether data is appended to an existing file. these flags should be included in addition to the 'text' or 'binary' flags when using the newoutputstream method. the default when writing is to create a new file when the file to write to does not exist, and replace the...
...characters are written to a text input stream using a specified character encoding, which defaults to utf-8. this means that a single character will occupy several bytes if it has a value greater than 128. this encoding is done automatically as long as you specify the 'text' flag to nsiscriptableio.newoutputstream(). other character encodings are available; see writing other character encodings below for details about writing text in other encodings. there are several methods available to write to a stream. for text files, you will usually use the writestring method. var file = io.getfile("desktop", "myinfo.txt"); var stream = io.newoutputstream(file, "text"); stream.writestring("this is some text"); stream.close(); in this example, a text input stream is created for the file 'myinfo.txt'. t...
...ilable which may be used for this. if you are going to write to a binary file instead of text, specify the 'binary' flag in place of the 'text' flag when creating the stream with nsiscriptableio.newoutputstream(). var stream = io.newoutputstream(file, "binary"); this line will create and open a binary stream for a file. once opened, you can write to the file using various writing methods. the following methods are available, all of which take one argument, which is the value to write: writeboolean will write a boolean value to a stream. if the argument is false, 0 is written, and if the argument is true, 1 is written. non-boolean values will be converted into booleans automatically. write8 will write a single byte. the 8 in the method name indicates that 8 bits of data are being written...
...And 2 more matches
Extensions - Archive of obsolete content
' to ensure that the new menu is added at the right place. note that the menu will not appear until it has a <menupopup>. adding a new menuitem you might wish to add a new item to one of the menus. this can be done by overlaying the popup to append the item to. for a list of the ids of the menus for firefox, see firefox menus. for example, to add an item to the end of the tools menu, use the following: <menupopup id="menu_toolspopup"> <menuitem label="thesaurus"/> </menupopup> note that other extensions may be adding their own items into the same menus. because of this, the new item might not appear at the end of the menu but before a menuitem added by another extension, depending on the order in which the overlays are applied. as you cannot predict this order, you should not rely on a...
... used rather than the menupopup element as this is the element that firefox uses. the code above will append the new item at the end of the context menu. if you want to place the item at a specific location within the context menu rather than at the end, you can use either the insertbefore or insertafter attributes to insert it before or after another item specified by an id. for example, the following may be used to insert a command just after the 'select all' command: <popup id="contentareacontextmenu"> <menuitem label="select links" oncommand="thumbnails.selectalllinks();" insertafter="context-selectall"/> </popup> see firefox context menu for a list of the ids of the items found on the firefox context menu. showing and hiding context menu items to have a menuitem you h...
...n 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 the popup is open, the gcontextmenu 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' propert...
...And 2 more matches
MenuItems - Archive of obsolete content
a menu command. adding shortcut keys to menu items a shortcut key may be associated with a menu item. unlike the access key, which only functions while the menu is open, a shortcut key works at any time. a shortcut key can be created using the key element. in reality, the keyboard shortcut is handled by the key element, however, the menu item will display the shortcut next to its label. this allows the user to discover what shortcut keys are available by looking at the menus. <keyset> <key id="open-key" modifiers="accel" key="o"/> <key id="close-key" modifiers="accel" key="c"/> </keyset> <menubar> <menu label="view"> <menupopup> <menuitem label="open" key="open-key"/> <menuitem label="close" key="close-key"/> </menupopup> </menu> </menubar> the two menuitem...
...on hover a -moz-image-region rule can be applied. in this example we use an image that is 16px wide and 32px high. the top 16px square is the icon in normal state the bottom part in hovered state. note that the image element is on a child level underneath the menu or menuitem, and it will have the class menu-iconic-icon. ...
...r the menu. if you do not set one, none of the items in that group will be checked by default. as with checkbox type menuitems, you can also set the autocheck attribute on a radio menuitem to disable the automatic adjustment of the checked state. this needs to be set on each radio menuitem. disabling a menuitem to have an item initially disabled, set the disabled attribute to true as in the following example: <menuitem label="undo" accesskey="u" disabled="true"/> when disabled, the item will appear greyed out and the action associated with the item cannot be carried out. the command event will not fire when an item is disabled. to disable a menuitem that doesn't apply, set the disabled property to true. to renable the item again, set the disabled property to false again. you may wish to...
...And 2 more matches
Multiple Queries - Archive of obsolete content
ntent. however, it is possible to use multiple queries. this may be used to combine the results from several queries together, or may be used to generate different types of results when recursive iterations. to use multiple queries, place each query element along with its rules inside a queryset element. the queryset element is a bit of a misnomer, it actually only contains one query each. the following is the basic structure of a template with multiple queries: <listbox datasources="..." ref="..."> <queryset> <query> ... </query> <rule> ... </rule> </queryset> <queryset> <query> ... </query> <rule> ... </rule> </queryset> </listbox> each queryset holds a query and its set of rules. if there is only rule, the rule element may b...
... </query> <rule> ... </rule> </queryset> <queryset> <query> ... </query> <rule> ... </rule> </queryset> </listbox> each queryset holds a query and its set of rules. if there is only rule, the rule element may be omitted as is the case when only one query is used. the results from the first query are generated first and output generated for it, followed by the results and output for the second query, and so forth for all of the queries. here is an example using an rdf datasource: <hbox id="photoslist" datasources="template-guide-photos3.rdf" ref="http://www.xulplanet.com/rdf/myphotos"> <template> <queryset> <query> <content uri="?start"/> <member container="?start" child="?photo"/> <triple subject="?p...
..., the results are combined and only three results are shown. however, you will probably notice that the one photo that matches the first query has appeared differently that the others. in fact, the content for this photo is that of the first query with the button, whereas the content for the other photos are that of the second query with the normal images. this method of using multiple queries allows different content to generated for each query. in this particular example, we could actually have used two rules instead. this would be a better idea as it only requires one query, is simpler and more efficient, however you could imagine a more complex query where this wasn't possible. how multiple queries are processed we already know that a query generates a set of results. there's no magic...
...And 2 more matches
RDF Modifications - Archive of obsolete content
'assert', to add a new triple (or arrow) to the rdf graph, 'unassert' to remove a triple, 'change' to adjust the target of a triple, and 'move' to adjust the source of a 'triple'. for mozilla's datasources, the latter two just unassert the old triple and add a new one, creating the effect of changing the value. however, only one notification is made. for instance, an assert call looks like the following: var source = rdf.getresource("http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg"); var predicate = rdf.getresource("http://purl.org/dc/elements/1.1/description"); var target = rdf.getliteral("one of the thirty or so egyptian obelisks"); datasource.assert(source, predicate, target, true); the assert call adds a new triple to the rdf datasource. when this happens, any templates observing ...
...calls. then, rather than notify on every change, the datasource will send one notification when the changes are finished. the template builder then rebuilds the template completely when done. this is useful when making a large amount of changes to avoid having to keep recalculating parts of the template that might change again quickly. adding rdf triples let's say we've just added the triple below to the datasource. subject: http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg predicate: http://purl.org/dc/elements/1.1/description object: one of the thirty or so egyptian obelisks the template builder will be notified through the rdf observer mechanism of the change. the template builder will need to check all of the queries and rules to see if this triple could cause a change in what wo...
...t cause any change in the output, the builder won't make any changes. if the output would change, the builder will need to adjust the output, either by adding a new result, removing an old result, or by changing the value of some part of the result. the builder is smart enough to only change what needs to be changed and leave the remaining parts alone. ...
...And 2 more matches
Special Condition Tests - Archive of obsolete content
« previousnext » there are several additional types of conditional tests that may be performed. parent tag tests sometimes you want to simply generate one block of content at the top level and different content at the recurisive level. for example, the bookmarks toolbar in a web browser might display buttons at the first level, but menus and submenus for content below that. templates have a means of allowing a rule to match only if the generated content would be inserted inside an element with a particular tag name. for instance, if the container was a <vbox>, a rule could be created that would only match a <vbox> element. this is useful for recursive templates, since the inner iterations may use different content. it's most useful to distinguish between the outer and inner...
... particular tag name. for instance, if the container was a <vbox>, a rule could be created that would only match a <vbox> element. this is useful for recursive templates, since the inner iterations may use different content. it's most useful to distinguish between the outer and inner levels during template generation. for the bookmarks toolbar, the outer content is inserted into an <hbox>, but at lower levels, the content will be inserted into a <menu> in case you aren't clear, the tag that must match for the outer iteration is the root element, the one with the datasources attribute on it. for inner iterations, it will be the element with the uri attribute from the previous iteration. here is a previous example, rewritten to use the parent matching syntax: <vbox datasources="people.xml" ref=...
...mpler. this technique is useful when you know that the content will be different at each level. if this is not the case, you will still need to use other types of conditions to handle this case. rdf parent matching for rdf sources, you can use the same technique. to do this kind of matching, you again place a parent attribute on the rule, set to the tag to match. ...
...And 2 more matches
Template Logging - Archive of obsolete content
l output details to the error console for each result. the error console can be found on the firefox tools menu. this logging of results can be very useful for debugging, but remember to remove this flag when you have finished and the template works correctly, as the logging can take up extra time that is not necessary when the template is working. each result is logged in a form much like the following: in template with id root using ref http://www.some-fictitious-zoo.com/birds new active result for query 2 matching rule 1: http://www.some-fictitious-zoo.com/birds/emperorpenguin in the example above, a new result has been added. for references, the value of the template's id and ref attributes are provided in each logged message. this is useful if multiple templates are being used. the seco...
... 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 overridden by an earlier query. as this example implies multiple queries are being used, we can determine that the first query did not provide a result with the given id, and that the result from the second query is used instead. 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'. in template with id root using ref http://www.some-fictitious-zoo.com/birds removed inactive result for query 2 (active query is 1): http://www.some-fictitious-zoo.com/birds/barnowl in this example, a result with the id 'http://www.some-fictitious-zoo.c...
...a result with the same id is being removed from the first query instead. note that this result is active and an indication is made in parantheses that there is no longer any active query. this indicates that the generated content will be removed. the log may instead indicate that another query is active; this would mean that the content for a different query is now generated. to summarize, the following forms of message may be logged: new active result for query 1 matching rule 2 a new data result has been added. in this example, the result matches the second rule of query 1. the generated content is from rule 2 of query 1. new inactive result for query 2 (overridden by query 1) a new data result has been added for query 2, but an earlier query 1 overrides it. the generated content is still ...
...And 2 more matches
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
nts defined in the content tag. this could be useful when trapping the focus and blur events. to define an event handler, use the handler element. each will describe the action taken for a single event handler. you can use more than one handler if necessary. if an event does not match any of the handler events, it is simply passed to the inner content as usual. the general handler syntax is as follows: <binding id="binding-name"> <handlers> <handler event="event-name" action="script"/> </handlers> </binding> place all of your handlers within the handlers element. each handler element defines the action taken for a particular event specified by its event attribute. valid event types are those supported by xul and javascript, such as click and focus. use the event name without the 'on'...
...ty of the check box is changed when the space bar is pressed. <handlers> <handler event="keypress" key=" " action="this.checked=!checked"/> </handlers> you can also use the keycode attribute to check for non-printable keys. the section on keyboard shortcuts provides more information. the modifier keys can be checked by adding a modifiers attribute. this should be set to one of the values set below: alt the user must press the alt key. control the user must press the control key. meta the user must press the meta key. shift the user must press the shift key. accel the user must press the special modifier key that is usually used for keyboard shortcuts on their platform. if set, the handler is only called when th...
... control key. meta the user must press the meta key. shift the user must press the shift key. accel the user must press the special modifier key that is usually used for keyboard shortcuts on their platform. if set, the handler is only called when the modifier is pressed. you can require multiple modifier keys by separating them with spaces. ...
...And 2 more matches
Box Objects - Archive of obsolete content
inside any borders, which is inconsistent with the other four boxobject position and size references, which include borders as part of the element. the values are always the position and sizes as currently displayed, so the values will be different if the element is moved or resized. for example, a flexible element will change in size and the box object dimensions will update accordingly. the following example shows this. example 1 : source view <button label="click me" oncommand="alert('the width is ' + this.boxobject.width);"/> you can use the width and height attributes of the element to specify the element's width and height, respectively. note that retrieving these values will return the size only if it was explicitly specified. these properties will return an empty string if ...
...leaves the element on screen and keeps the layout objects intact, but changes the size of the element to 0. this means that while both hidden and collapsed elements have 0 width and height, hidden elements have a x and y position of 0, while collapsed elements will retain their position in the window. to retrive or modify the hidden or collapsed state use the corresponding properties as in the following example. example 2 : source view <script> function showpositionandsize() { var labelbox = document.getelementbyid('thelabel').boxobject; alert("position is (" + labelbox.x + "," + labelbox.y + ") and size is (" + labelbox.width + "," + labelbox.height + ")"); } </script> <button label="hide" oncommand="document.getelementbyid('thelabel').hidden = true;"/> <button ...
... 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, previoussibling, and parentbox. their function should be self explanatory from their names. these properties return elements, for example, the firstchild property returns the first displayed child element. there is no corresponding childnodes ...
...And 2 more matches
Broadcasters and Observers - Archive of obsolete content
ld be used to hold, for instance, a flag to indicate whether the user was online or not. in the former case, menu items and toolbar buttons would need to be disabled when there was no page to go back to, or no text to cut or delete. in the latter case, various user interface elements might need to update when the user switches from offline mode to online mode. the simplest broadcaster is shown below. you should always use an id attribute so that it can be referred to by other elements. <broadcasterset> <broadcaster id="isoffline" label="offline"/> </broadcasterset> any elements that are watching the broadcaster will be modified automatically whenever the broadcaster has its label attribute changed. this results in these elements having a new label. like other non-displayed elements, the...
...l attributes also. we could continue with additional elements. as many elements as you want can observe a single broadcaster. you can also have only one if you wanted to but that would accomplish very little since the main reason for using broadcasters is to have attributes forwarded to multiple places. you should only use broadcasters when you need multiple elements that observe an attribute. ...
...h do the same thing. the difference is more semantic. use commands for actions and use broadcasters for state. in fact, any element can act as broadcaster, as long as you observe it using the observes attribute. the observes element there is also a way to be more specific about which attribute of the broadcaster to observe. this involves an observes element. ...
...And 2 more matches
Commands - Archive of obsolete content
ement is focused. a command is identified by its id attribute. mozilla uses the convention that command id's start with 'cmd_'. you will probably want to use the same id if a command is already being used, however, for your own commands, you can use any command id you wish. to avoid conflicts, you may wish to include the application name in the command id. a simple way of using commands is as follows: example: simple command example 1 : source view <command id="cmd_openhelp" oncommand="alert('help!');"/> <button label="help" command="cmd_openhelp"/> in this example, instead of placing the oncommand attribute on the button, we instead place it on a command element. the two are then linked using the command attribute, which has the value of the command's id. the result is that when the bu...
... oncommand="document.getelementbyid('cmd_openhelp').removeattribute('disabled');"/> in this example, both buttons use the same command. when the disable button is pressed, the command is disabled by setting its disabled attribute, and both buttons will be disabled as well. it is normal to put a group of commands inside a commandset element, together near the top of the xul file, as in the following: <commandset> <command id="cmd_open" oncommand="alert('open!');"/> <command id="cmd_help" oncommand="alert('help!');"/> </commandset> a command is invoked when the user activates the button or other element attached to the command. you can also invoke a command by calling the docommand method either of the command element or an element attached to the command such as a button. command ...
...element or a window. the command dispatcher contains methods for retrieving controllers for commands and for retrieving and modifying the focus. adding controllers you can implement your own controllers to respond to commands. you could even override the default handling of a command with careful placement of the controller. a controller is expected to implement four methods, which are listed below: supportscommand (command) this method should return true if the controller supports a command. if you return false, the command is not handled and command dispatcher will look for another controller. a single controller may support multiple commands. iscommandenabled (command) this method should return true if the command is enabled, or false if it is disabled. corresponding buttons will b...
...And 2 more matches
Focus and Selection - Archive of obsolete content
he focus event the focus event is used to respond when the focus is given to an element. the blur event is used to respond when the focus is removed from an element. you can respond to focus changes by adding an onfocus or onblur attribute on an element. they work just like their html counterparts. you might use these event handlers to highlight the element or display text on a status bar. the following example can be used to apply a function to handle a focus event. example 2 : source view <script> function displayfocus(){ var elem=document.getelementbyid('sbar'); elem.setattribute('value','enter your phone number.'); } </script> <textbox id="tbox1"/> <textbox id="tbox2" onfocus="displayfocus();"/> <description id="sbar" value=""/> the focus event, when it occurs, will call the displ...
...interface. the command dispatcher has other roles, which will be discussed in a later section on commands. for now, we'll look at some of the focus related features of the command dispatcher. you can retrieve the command dispatcher from a window using the document's commanddispatcher property. from there, you can get the focused element with the dispatcher's focusedelement property. the example below shows this. example 3 : source view <window id="focus-example" title="focus example" onload="init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function init(){ addeventlistener("focus",setfocusedelement,true); } function setfocusedelement(){ var focused = document.commanddispatcher.focusedelement; document.getelementbyid("focused").va...
...ect on the focused element. only focusable elements can be focused. making a label focusable if you were creating custom elements, you might have a need to change whether an element can have the focus or not. for this, you can use a special style property -moz-user-focus. this property controls whether an element can be focused. for instance, you could make a label focusable, as in the example below. example 4 : source view <label id="focused" style="-moz-user-focus: normal;" onkeypress="alert('label focused');" value="focus me"/> the style property is set to normal. you can also set it to ignore to turn off the focus for an element. this shouldn't be used for disabling an element, however; the disabled attribute or property should be used instead, since that is what it is designe...
...And 2 more matches
Input Controls - Archive of obsolete content
g for a guide to using input controls and forms on the web? see forms in html. text entry fields html has an input element which can be used for text entry controls. xul has a similar element, textbox, used for text entry fields. without any attributes, the textbox element creates a box in which the user can enter text. textboxes accept many of the same attributes as html input controls. the following are some of them: id a unique identifier so that you can identify the textbox. class the style class of the textbox. value if you want the textbox to have default text, supply it with the value attribute. disabled set to true to have text entry disabled. textbox.type you can set this attribute to the special value password to create a textbox that hides what it types. this is ...
...e class of the textbox. value if you want the textbox to have default text, supply it with the value attribute. disabled set to true to have text entry disabled. textbox.type you can set this attribute to the special value password to create a textbox that hides what it types. this is usually used for password entry fields. ...
...ed. textbox.type you can set this attribute to the special value password to create a textbox that hides what it types. this is usually used for password entry fields. maxlength the maximum number of characters that the textbox allows. note that while in html, several different kinds of fields can be created with the input element, in xul there are separate elements for each type. the following example shows some textboxes: example 1 : source view <label control="some-text" value="enter some text"/> <textbox id="some-text"/> <label control="some-password" value="enter a password"/> <textbox id="some-password" type="password" maxlength="8"/> multiline textbox the textbox examples above will create text inputs that can only be used for entering one line of text. html also has a te...
...And 2 more matches
Introduction to RDF - Archive of obsolete content
r xul elements as well such as listboxes and menus. we'll see this in the next section. a very brief overview of rdf will be provided here. for more information about rdf, see the rdf specification. rdf/xml rdf consists of a model, which is a graph representation of data. rdf/xml is an xml language which can be used to represent rdf data. it contains a fairly simple set of elements. the sample below shows a simple rdf template. <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> ... </rdf:rdf> this has some similarities to the xul header. instead of the window element, the rdf element is used. you can see the namespace for rdf was declared so that the rdf elements are recognized properly. inside, the rdf element, you will place the data. to see some e...
...ed as a large table with numerous fields. in the case of rdf however, the lists may be hierarchical as well. this is necessary so that we can have folders or categories of bookmarks. each of the fields in an rdf database is a resource, each with a name associated with it. the name is described by a uri. ...
... last visited http://home.netscape.com/web-rdf#lastvisitdate date of last visit these are generated by taking a namespace name and appending the field name. in the next section, we'll look at how we can use these to fill in the field values automatically. note that the last visited date has a slightly different namespace than the other three. rdf/xml file example below, a sample rdf/xml file is shown, listing a table with three records and three fields. <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:animals="http://www.some-fictitious-zoo.com/rdf#"> <rdf:seq about="http://www.some-fictitious-zoo.com/all-animals"> <rdf:li> <rdf:description about="http://www.some-fictitious-zoo.com/mammals/lion"> <animals:na...
...And 2 more matches
Modifying the Default Skin - Archive of obsolete content
using it may lead to hard-to-diagnose bugs or crashes. ...
...ple personalized look to a firefox window, you can easily change the style sheets associated with it. larger changes can be done by creating an entirely new skin. firefox has a theme manager for changing the default skin. (although the underlying code for mozilla calls them skins and the user interface calls them themes, they're both referring to the same thing). a skin is described using css, allowing you to define the colors, borders and images used to draw elements. the file classic.jar contains the skin definitions. the global directory within this archive contains the main style definitions for how to display the various xul elements. by changing these files, you can change the look of the xul applications. customize with userchrome.css if you place a file called 'userchrome.css' in a...
...if you place a file called 'userchrome.css' in a directory called 'chrome' inside your user profile directory, you can override settings without changing the archives themselves. this directory should be created when you create a profile and some examples placed there. the file 'usercontent.css' customizes web pages, whereas 'userchrome.css' customizes chrome files. for example, by adding the following to the end of the file, you can change all menubar elements to have a red background. menubar { background-color: red; } if you open any firefox window after making this change, the menu bars will be red. because this change was made to the user style sheet, it affects all windows. this means that the browser menu bar, the bookmarks menu bar and even the find files menu bar will be red. ...
...And 2 more matches
More Button Features - Archive of obsolete content
« previousnext » in this section, we will look at some additional features of buttons. adding an image you can add an image to a button by specifying a url in the image attribute. the image is loaded from the url, which can be a relative or absolute url, and then the image is displayed on the button. the button below will have both a label and the image 'happy.png'. the image will appear to the left of the label. ...
... have both a label and the image 'happy.png'. the image will appear to the left of the label. you can change this position by using two other attributes. this will be explained in a moment. example 1 : source view <button label="help" image="happy.png"/> button with css image another way to specify the image is by using the css list-style-image style property on the button. this is designed to allow the 'skin' (in this case, the appearance of the image) to be changed without changing the xul file. an example is shown below. example 2 : source view <button id="find-button" label="find" style="list-style-image: url('happy.png')"/> in this case, the image 'happy.png' is displayed on the button. the style attribute functions similar to its html counterpart. in general, it can be used on all x...
...utes that can be used to control this position. the dir attribute controls the direction of the image and text. by setting this attribute to the value reverse, the image will be placed on the right side of the text. by using the value normal, or leaving the attribute out entirely, the image will be placed on the left side of the text. the orient attribute can be used to place the image above or below the text. the default value is horizontal which is used to place the image on the left or right. you can also use the value vertical to place the image above or below. in this case, the dir attribute controls the placement above or below. the same values are used, where normal means place the image above the text, and reverse means place the image below the text. example 3 : source view <butt...
...And 2 more matches
Numeric Controls - Archive of obsolete content
ousnext » xul has two elements used for the entry of numeric values or ranges, and well as two elements for entering dates and times. these elements are only available in firefox 3 and later. number fields a textbox may be used for entering numbers by setting the value of the type 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. however, the minimum and maximum values can also be specified using the min and max attributes. if these are set, you can control the ...
...ified 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. the min attribute is set to 1 to indicate a minimum possible value of 1 and the max attribute is set to 20 to indiciate a maximum possible value of 20. if the minimum value is not specified, it has a default value of 0. the maxi...
...ndiciate a maximum possible value of 20. if the minimum value is not specified, it has a default value of 0. the maximum value defaults to the special value infinity which means that there is no limit. other numeric textbox attributes the increment attribute may be used to specify by how much the value changes when the arrows are pressed. the default value is 1, but specifying a different value allows the number to change by a larger amount. for instance, the following example steps in multiples of 10. <textbox type="number" increment="10" max="100"/> this textbox steps in multiples of 10 from 0 to 100. since the min attribute was not specified, it defaults to 0. note that the user can still enter other values if they are typed in. the increment attribute only affects the arrow buttons. the ...
...And 2 more matches
RDF Datasources - Archive of obsolete content
er of other built-in datasources. some of them are listed here with a few examples. they work very similarly to the bookmarks, although the fields will be different in each case. the history list the history datasource provides access to the user's history list which is the list of urls the user has visited recently. the resource can be referred to using rdf:history as the datasource. the table below shows the resources (or fields) that you can retrieve from the history datasource. put the url values below where you want the value of the resource to be used. date http://home.netscape.com/nc-rdf#date date of last visit name http://home.netscape.com/nc-rdf#name title of the page page http://home.netscape.com/nc-rdf#pag...
...you can use any of the resources that you want. bookmarks (rdf:bookmarks) the bookmarks are generated from the user's bookmark list. resources added date http://home.netscape.com/nc-rdf#bookmarkadddate date the bookmark was added description http://home.netsc...
...ources 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 example below. this has the effect of reading the data from all the datasources mentioned. <tree datasources="rdf:bookmarks rdf:history animals.rdf" ref="nc:bookmarksroot"> this example reads the resources from the bookmarks, history and the animals.rdf file. they are combined into a single composite datasource and can be used as if they were one. the special datasource rdf:null corresponds to nothing. you ca...
...And 2 more matches
Using Spacers - Archive of obsolete content
« previousnext » in this section, we will find out how to add some spacing in between the elements we have created. adding spacers one of the problems with developing user interfaces is that each user has a different display. some users may have larger displays with higher resolutions and others may have lower resolutions. in addition, different platforms may have special requirements on the user interface. if adding support for multiple languages, the text for one language may require more room than another. applications that need to support multiple platforms and languages usually have their windows laid out with lots of space to allow for this. some platforms and user interface toolkits provide components that are smart enough to resize and re-position themselves to fit th...
...of the user. (java uses layout managers for example.) xul provides the capability for elements to position and resize automatically. as we've seen, the find files window has appeared in a size that will fit the elements inside it. each time we add something, the window gets bigger. xul uses a layout system called the 'box model'. we'll talk more about this in the next section but it essentially allows you to divide a window into a series of boxes that hold elements. the boxes will be positioned and resized based on specifications that you can define. for now, just know that the window element is a type of box. before we get into detail about boxes, we'll introduce another xul element that is useful for layout, the spacer. a spacer is very simple and only requires one attribute, which will be ...
...ments. the boxes will be positioned and resized based on specifications that you can define. for now, just know that the window element is a type of box. before we get into detail about boxes, we'll introduce another xul element that is useful for layout, the spacer. a spacer is very simple and only requires one attribute, which will be explained in a moment. the simplest spacer looks like the following: <spacer flex="1"/> a spacer is used to place blank space into a window. its most useful ability is that it can grow or shrink as the user resizes the window. this would be how one would place buttons on the right or bottom of a window and have them stick to the right or bottom edge no matter what size the window is. as we'll see, you can use a series of spacers to create a number of layout e...
...And 2 more matches
Writing Skinnable XUL and CSS - Archive of obsolete content
mozilla can have any number of installed ui packages, from navigator to sidebar to editor. each package has its own skin, css files and images that determine the appearance of that package. in our particular mozilla skin, there is a special package calledglobal. this package contains a special skin called theglobal skin. if you wish for your package to blend in with the other packages, then the skin for your package should inherit information from the global skin in order to reduce the amount of duplication across packages and in order to make the ui as a whole easier to skin. ...
...mation should only be found in base skin files. the skin file should instead inherit from a base skin file to obtain the appropriate font, color, and border information. by obeying this restriction, your package will be almost entirely skinnable by changing only the global defaults. this rule also applies when designing a css file for a ui component that will be overlayed into other components. below are examples for each case. example 1: the navigator package has a personal toolbar with popup menu buttons. the colors for the toolbar and buttons should be drawn from global by placingclass attributes on the appropriate elements in the xul. there should be no rules in navigator.css that attempt to define colors, fonts, etc. for either the personal toolbar headers or for the menu buttons' bord...
...nger package has a css file that describes the appearance of the messenger button that appears on the taskbar used by all windows. the messenger css file should not attempt to describe the borders or the colors for this button. it should only describe the icon. because the button is used in the navigator window (through overlays), the fonts/colors used should not be described by messenger. this allows the button to blend in as much as possible regardless of where it is used. the importance of this rule cannot be overstated. derived skin files should not contain any rules for colors, fonts, or borders. exceptions to this rule must be approved in order to be allowed into the product. note that in our current designed mozilla skin (aside from global) every single css file is a derived skin fi...
...And 2 more matches
key - Archive of obsolete content
Archive › Mozilla › XUL › key
disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. key ty...
...able characters, such as the enter key or function keys, use this attribute instead of the key attribute. valid keys are listed at keyboard shortcuts. keytext type: string a label for the keyboard shortcut. this text would appear next to a menuitem label if that menuitem is associated with the key element via its key attribute. modifiers type: space-separated list of the values below a list of modifier keys that should be pressed to invoke the keyboard shortcut. multiple keys may be separated by spaces or commas. keys will map to other keys on platforms that do not have them. shift: the shift key. alt: the alt key. on the macintosh, this is the option key. on macintosh this can only be used in conjunction with another modifier, since alt+letter combinations are reserved...
... occurs when a user selects a menu item or presses a keyboard shortcut attached to the command. phase type: string the event phase where the handler is invoked. this should be set to 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. ...
...And 2 more matches
listbox - Archive of obsolete content
you may specify the number of rows to display in the list using the rows attribute. additional rows can be viewed using a scroll bar. a listbox is expected to contain listitem elements. ...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. disablek...
... information is available in the preferences system article. rows type: integer the number of rows to display in the element. if the element contains more than this number of rows, a scrollbar will appear which the user can use to scroll to the other rows. to get the actual number of rows in the element, use the getrowcount method. ...
...And 2 more matches
listitem - Archive of obsolete content
lean 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 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. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (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; } current type: boolean this attribute will be set to true if the listitem is the current item. this is typically used by a theme to customize the focus ring. to change the currently selected item in a listbox, use the listbox property selecteditem. disabled type: b...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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 ...
...And 2 more matches
menulist - Archive of obsolete content
el="option 2" value="2"/> <menuitem label="option 3" value="3"/> <menuitem label="option 4" value="4"/> </menupopup> </menulist> 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. 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. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (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; } disableautoselect type: boolean if this attribute is true or omitted, the selected item on the menu will update to match what the user entered in the textbox. if the text does not match any of the items in the list, the menu selection is cleared. if this attribute is fal...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. editable...
...And 2 more matches
panel - Archive of obsolete content
Archive › Mozilla › XUL › panel
firefox 4.0. attributes backdrag, close, consumeoutsideclicks, fade, flip, ignorekeys, label, left, level, noautofocus, noautohide, norestorefocus, onpopuphidden, onpopuphiding, onpopupshowing, onpopupshown, position, titlebar, top, type properties accessibletype, label, popupboxobject, popup, state methods hidepopup, moveto, openpopup, openpopupatscreen, sizeto examples the following example shows how a panel may be attached to a label. <panel id="thepanel"> <hbox align="start"> <image src="warning.png"/> <vbox> <description value="you have 6 new messages."/> <hbox> <button label="read mail"/> <button label="new message"/> </hbox> </vbox> </hbox> </panel> <description value="6 new messages" popup="thepanel"/> attributes ...
...hether or not the event that caused the popup to be automatically dismissed (or "rolled up") should be consumed or be dispatched as a normal event. if it is not set, it defaults to the platform behavior. if it set to true the rollup event is consumed. if set to false, the rollup event is not consumed. this attribute should be used instead of setconsumerollupevent. fadetype: one of the values belowthe fade attribute, which may only be used with arrow panels, lets you set up a panel that will automatically fade away after a short time. the default is none. nonethe panels doesn't automatically fade away.slowthe panels slowly fades away after a short time.fastthe panels quickly fades away after a short time. flip type: string normally, when a popup opens near the e...
... ignorekeys type: boolean if false, the default value, the escape key may be used to close the panel. if true, the escape key cannot be used to close the panel. label type: string for panels with titlebars, the label on the titlebar. left type: integer overrides the horizontal position of the popup specified by the showpopup method. level type: one of the values below specifies whether the panel appears on top of all windows, or just on top of the window the panel is in. if this attribute is not set, the popup window level depends on the platform. on linux, the default value is top, otherwise, the default value is parent. if a panel has one or more text fields, this attribute should not be set, otherwise ime or on-screen keyboard popups will appear incorrectl...
...And 2 more matches
preference - Archive of obsolete content
disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. instant...
... the checkbox disables the preference instead of enabling it. name type: string the name of the preference to change. for example, the browser's home page is set with the preference browser.startup.homepage. overview an onchange attribute is an event listener to the object for the event change. a change event is fired in different ways for different xul input elements as listed below: onchange type: script code textbox when enter key is pressed radio/check box when the state is changed select list when the selected item is changed what is accessible the script context at this point can only access the following things: global values/functions i.e. window, document, or any of the functions/objects/variables bound to the wind...
...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...
...And 2 more matches
prefwindow - Archive of obsolete content
fpanes should be put into overlays. note for mac os x: a common way of opening modal windows on mac os x that are not attached as a sheet to the main window is to use nsiwindowwatcher.openwindow() with a null parentwindow. this does not work with prefwindows, breaking the general behavior of the window and in particular the list of prefpanes. prefer the classical window.opendialog() with the following window features: "chrome,titlebar,toolbar,centerscreen,dialog=yes". attributes buttonalign, buttondir, buttonorient, buttonpack, buttons, defaultbutton, lastselected, onbeforeaccept, ondialogaccept, ondialogcancel, ondialogdisclosure, ondialoghelp, onload, onunload, title, type properties buttons, currentpane, defaultbutton, lastselected, preferencepanes, type methods acceptdialo...
...or the box containing the buttons. buttondir type: string the value of the dir attribute for the box containing the buttons. buttonorient type: string the value of the orient attribute for the box containing the buttons. buttonpack type: string the value of the pack attribute for the box containing the buttons. buttons type: comma-separated list of the values below a comma-separated list of buttons to appear in the dialog box. the buttons will be placed in suitable locations for the user's platform and basic event handling will be performed automatically. the following values can be used in the list: accept: the ok button, which will accept the changes when pressed. this button will also be the default button. cancel: the cancel button which wi...
...tring the text to appear in the title bar of the window. type type: string set this attribute to child for preference dialogs that are child dialogs of a main preferences window. this ensures that the preferences are only saved when the main dialog is closed, if this is the appropriate behaviour for the platform. properties buttons type: comma-separated list of the values below a comma-separated list of buttons to appear on the dialog box. the buttons will be placed in suitable locations for the user's platform and basic event handling will be performed automatically. the following values can be used in the list: accept: the ok button, which will accept the changes when pressed. this button will also be the default button. cancel: the cancel button which wi...
...And 2 more matches
radio - Archive of obsolete content
Archive › Mozilla › XUL › radio
ul tutorial. attributes accesskey, command, crop, disabled, focused, group, image, label, selected, tabindex, value properties accesskey, accessibletype, control, crop, disabled, image, label, radiogroup, selected, tabindex, value examples <radiogroup> <radio id="orange" label="red" accesskey="r"/> <radio id="violet" label="green" accesskey="g" selected="true"/> <radio id="yellow" label="blue" accesskey="b" disabled="true"/> </radiogroup> 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. command type: id set to the id of a command element that is being observed by the element. crop ...
...b" disabled="true"/> </radiogroup> 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. 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 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. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (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; } disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is disabled. disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, a...
...And 2 more matches
resizer - Archive of obsolete content
ze;"/> <resizer dir="bottomleft" height="2" style="cursor: sw-resize;"/> </vbox> <vbox flex="1"> <resizer dir="top" height="2" style="background-color: grey; cursor: n-resize;"/> <browser flex="1" id="browser" type="content-primary"/> <resizer dir="bottom" height="2" style="background-color: grey; cursor: s-resize;"/> </vbox> <vbox width="2" style="background-color: grey; overflow: hidden;"> <resizer dir="topright" height="2" style="cursor: ne-resize;"/> <resizer dir="right" flex="1" style="cursor: e-resize;"/> <resizer dir="bottomright" height="2" style="cursor: se-resize;"/> </vbox> </hbox> </window> resizing an element <stack style="border: 1px solid black;"> <button id="button" label="resizable" left="18" top="18" right="18" bottom="18"/> <resizer di...
... left resized to the left. right resized to the right. top resized up. bottom resized down. bottomstart resized down and toward the start of the line (toward the left for left-to-right locales, toward the right for right-to-left locales). bottomend resized down and toward the end of the line (toward the right for left-to-righ...
... element that should be resized by the resizer. typetype: stringset this to the value "window" for a resizing grip that appears in the bottom corner of the window, used for resizing the window. as some platforms provide this resizing grip automatically, this type of resizer element will be hidden and ensure that the window does not get an extra resizer. ...
...And 2 more matches
separator - Archive of obsolete content
elements. this type of separator should be used to separate parts of a dialog. it doesn't draw a bar visually, but is just a small space. it is functionally equivalent to a spacer except it defaults to a small size (usually 1.5 ems). ...
...groove-thin"/> attributes orient type: one of the values below used to specify whether the separator is a horizontal or vertical separator. note that the values are the reverse of what seems more likely. horizontal the separator separates vertically placed elements. vertical the separator separates horizontally placed elements. ...
...> attributes orient type: one of the values below used to specify whether the separator is a horizontal or vertical separator. note that the values are the reverse of what seems more likely. horizontal the separator separates vertically placed elements. vertical the separator separates horizontally placed elements. ...
...And 2 more matches
<statusbarpanel> - Archive of obsolete content
an ellipsis will be used in place of the cropped text. if the box direction is reversed, the cropping is reversed. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (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. i...
... 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. label type: string gets and sets the value of the label attribute. ...
...And 2 more matches
timepicker - Archive of obsolete content
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. ...
... 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. ...
... 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. ...
...And 2 more matches
XULRunner 1.8.0.1 Release Notes - Archive of obsolete content
requirements. the system requirements for xulrunner are the same as the system requirements for firefox. installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using a archive tool (7zip is recommended). the following directory is recommended: c:\program files\mozilla xulrunner\1.8.0.1 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a new directory ...
...1.8.0.1 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a new directory using tar -xzf xulrunner-1.8.0.1.en-us.linux-i686.tar.gz. the following directory is recommended: /opt/xulrunner/1.8.0.1 . register xulrunner with the system by running xulrunner --register-global (to install for all users, must be run as root) or xulrunner --register-user (to install for one user only). uninstalling xulrunner windows/linux from a command prompt, run xulrunner --unregister-global or xulrunner --unregister-user to unregister xulrunner just as...
...of xulrunner, remove the /library/frameworks/xul.framework directory. installing xul applications xul applications can be obtained from various sources, and are typically packaged as a zip archive with the extension .xulapp or .xpi. sample applications are available from the mozilla developer center. save the application archive to your desktop or another convenient place. ...
...And 2 more matches
XULRunner 1.8.0.4 Release Notes - Archive of obsolete content
quirements. the system requirements for xulrunner are the same as the system requirements for firefox. installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using an archive tool (7zip is recommended). the following directory is recommended: c:\program files\mozilla xulrunner\1.8.0.4 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a new directory...
....8.0.4 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a new directory using tar -xzf xulrunner-1.8.0.4.en-us.linux-i686.tar.gz. the following directory is recommended: /opt/xulrunner/1.8.0.4 . register xulrunner with the system by running xulrunner --register-global (to install for all users, must be run as root) or xulrunner --register-user (to install for one user only). uninstalling xulrunner linux from a command prompt, run xulrunner --unregister-global or xulrunner --unregister-user to unregister xulrunner just as you re...
...ulrunner, remove the /library/frameworks/xul.framework directory. installing xul applications xul applications can be obtained from various sources, and are typically packaged as a zip archive with the extension .xulapp or .xpi. sample applications are available from the mozilla developer center. save the application archive to your desktop or another convenient place. ...
...And 2 more matches
XULRunner 1.9.1 Release Notes - Archive of obsolete content
equirements. the system requirements for xulrunner are the same as the system requirements for firefox. installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using an archive tool (7zip is recommended). the following directory is recommended: c:\program files\mozilla xulrunner\1.9.1 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a new directory us...
...1.9.1 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a new directory using tar -xjf xulrunner-1.9.1.19.en-us.linux-i686.tar.bz2. the following directory is recommended: /opt/xulrunner/1.9.1 . register xulrunner with the system by running xulrunner --register-global (to install for all users, must be run as root) or xulrunner --register-user (to install for one user only). uninstalling xulrunner linux from a command prompt, run xulrunner --unregister-global or xulrunner --unregister-user to unregister xulrunner just as you regis...
...of xulrunner, remove the /library/frameworks/xul.framework directory. installing xul applications xul applications can be obtained from various sources, and are typically packaged as a zip archive with the extension .xulapp or .xpi. sample applications are available from the mozilla developer center. save the application archive to your desktop or another convenient place. ...
...And 2 more matches
XULRunner 1.9.2 Release Notes - Archive of obsolete content
system requirements. the system requirements for xulrunner are the same as the system requirements for firefox. installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using an archive tool (7zip is recommended). the following directory is recommended: c:\program files\mozilla xulrunner\1.9.2 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a new directory using ta...
...lrunner\1.9.2 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a new directory using tar -xjf xulrunner-3.6.26.en-us.linux-i686.tar.bz2. the following directory is recommended: /opt/xulrunner/1.9.2 . register xulrunner with the system by running xulrunner --register-global (to install for all users, must be run as root) or xulrunner --register-user (to install for one user only). uninstalling xulrunner linux from a command prompt, run xulrunner --unregister-global or xulrunner --unregister-user to unregister xulrunner just as you registere...
...ifferent version. type sudo rm /var/db/receipts/org.mozilla.xulrunner.* installing xul applications xul applications can be obtained from various sources, and are typically packaged as a zip archive with the extension .xulapp or .xpi. sample applications are available from the mozilla developer center. save the application archive to your desktop or another convenient place. ...
...And 2 more matches
XULRunner 1.9 Release Notes - Archive of obsolete content
quirements. the system requirements for xulrunner are the same as the system requirements for firefox. installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using an archive tool (7zip is recommended). the following directory is recommended: c:\program files\mozilla xulrunner\1.9 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a new directory usi...
...\1.9 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a new directory using tar -xjf xulrunner-1.9.0.17.en-us.linux-i686.tar.bz2. the following directory is recommended: /opt/xulrunner/1.9 . register xulrunner with the system by running xulrunner --register-global (to install for all users, must be run as root) or xulrunner --register-user (to install for one user only). uninstalling xulrunner linux from a command prompt, run xulrunner --unregister-global or xulrunner --unregister-user to unregister xulrunner just as you regist...
...ulrunner, remove the /library/frameworks/xul.framework directory. installing xul applications xul applications can be obtained from various sources, and are typically packaged as a zip archive with the extension .xulapp or .xpi. sample applications are available from the mozilla developer center. save the application archive to your desktop or another convenient place. ...
...And 2 more matches
Getting started with XULRunner - Archive of obsolete content
on that will assume that you have this installed in /library/frameworks. in ubuntu desktop and its variants (xubuntu, kubuntu, ...), from version 11.10 (oneiric ocelot), xulrunner is not longer maintained and doesn't exist in ubuntu repository. therefore, either you need to compile xulrunner manually or download a binary release from mozilla's ftp server. ...
...e file extension to zip and then use your normal filesystem's decompression tool to open it up. the contents of omni.ja are available to xulrunner applications and are what make it possible to build amazing applications easily! step 3: create the application folder structure time to start a simple, bare bones application shell. call it a xul “hello world” if you want. all of what you see below can be found in the xulrunner documentation here on mdn in much more detail. hint: skip ahead and download the sample application, you can experiment with it while following this tutorial. you can download the sample application from https://github.com/matthewkastor/xulrunner-examples. please continue reading to learn the "what", "why" and "how" parts of building a xulrunner application. on w...
... | | +-- main.xul | | | | | +-- main.js | | | +-- chrome.manifest | +-+ defaults/ | | | +-+ preferences/ | | | +-- prefs.js | +-- application.ini | +-- chrome.manifest notice that there are 5 files in the folder structure: application.ini, chrome.manifest (2), prefs.js, and main.xul. the /chrome/chrome.manifest file is optional, but might be useful for backward compatibility. see the note below. for more details on the structure of installable bundles in general see: structure of an installable bundle. note: in xulrunner 2.0, the chrome.manifest is now used to register xpcom components in addition to its previous uses. part of this change means the /chrome/chrome.manifest is no longer considered the "root" manifest. xulrunner will not check that folder location for a root-level chro...
...And 2 more matches
2006-11-03 - Archive of obsolete content
he has also created a bug ...
...ozilla/mail/config/mozconfig client.mk:339: /cygdrive/c/mozilla/.mozconfig.mk: no such file or directory he claims that the file ".mozconfig" exists in /cygdrive/c/mozilla/mail/config/mozconfig the disable-crypto cause problem originally posted on november 2nd: gxk is building minimo using the code base from sept. 11 2006. when he builds using the disable.crypto option he encounters the following problem: no rule to make target `../../dist/lib/components/libpipboot.a', needed by `minimo'. he has 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 getting an error when doing so: building deps for /cygdrive/c/mozilla/toolkit/airbag/airbag/src/common/windows/guid_...
...that airbag doesn't build with msvc 7.1. (http://www.google.com/url?sa=d&q=htt...tail%3fid%3d64) gavin recommended that phil should add |ac_add_options --disable-airbag| to his .mozconfig. new windows compatibility issue? originally posted on november 1st: dale dale has set up a windows machine in order to perform mozilla builds but has been unsuccessful to do so. according to him he has followed the windows build requirements recommended by mozilla. he also noted that he has had different results (error messages when compiling) on different machines. dale has discovered that there are other people who are experiencing the same issues as he is. he has also found a work around which is to use version 20040127-1 of sh.exe instead of the sh.exe version 20040127-3. fix host_libidl_libs...
...And 2 more matches
Extentsions FAQ - Archive of obsolete content
using position:absolute and-index:100000 in html) you can almost do this with a stack: <window ...> <stack flex="1"> <image top="40" left="80"/> <vbox> other content here </vbox> </stack> </window> the only restriction is that your image can't overlap the right or bottom of the window. there are workarounds to this restriction by messing around with overflow or negative margins but i forgot offhand how to do that. how to create a dynamic drop down menu that may have submenus using javascript for an extension? these two links should give you a starting point: http://www..xulplanet.com/tutorials/...u/advmenu.html http://www.xulplanet.com/tutorials/x...dommodify.html request for a thunderbird extension that can automatically detect the default ...
...int: http://www..xulplanet.com/tutorials/...u/advmenu.html http://www.xulplanet.com/tutorials/x...dommodify.html request for a thunderbird extension that can automatically detect the default domain when composing e-mails via autodetect. <https://bugzilla.mozilla.org/show_bug.cgi?id=312818> "thunderbird requires domain in addresses and doesn't always add default" there is an extension that allows what you want attached to one of the comments in this bug. how to get the value of a text box when a button is clicked? read http://developer.mozilla.org/en/docs/extension_faq and check if there are any errors in js console. friday, september 29 - october 6, 2006 (↑ top) is there anyway, via plugin or extension, for firefox to mimic the functionality of ie in this respect? the ietab (...
...r 29 - october 6, 2006 (↑ top) is there anyway, via plugin or extension, for firefox to mimic the functionality of ie in this respect? the ietab (opens ie in a firefox tab) should be able do this if you set it to always open "file://*" urls in an ie tab. the appearance with a firefox tab isn't quite the same as having a completely 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 ye...
...And 2 more matches
2006-09-29 - Archive of obsolete content
summary: mozilla.dev.tech.layout september 22-29, 2006 announcements no announcements for this week. discussions discussion on how the firefox 1.5.0.7 dom generates xhtml inline elements using wordpress. it was determined that the generated elements from wordpress do not follow the wc3 guidelines in appendix c of xhtml 1.0. although the w3 validation accepted the generated xhtml as valid, a bug identified within the html working group ignored the invalid elements. ...
...efox 1.5.0.7 dom generates xhtml inline elements using wordpress. it was determined that the generated elements from wordpress do not follow the wc3 guidelines in appendix c of xhtml 1.0. although the w3 validation accepted the generated xhtml as valid, a bug identified within the html working group ignored the invalid elements. details can be located at layout confusion refactoring the nshtmlreflowstate(computeblockboxdata, initconstraints) and nsimageframe::getdesiredsize which uses ns_inrinsicsize, into the following method: /** * compute the size that a frame will occupy. called while * constructing the nshtmlreflowstate to be used to reflow the frame, * in order to fill its mcomputedwidth and mcomputedheight member * variables. * * the |height| member of the return v...
...non-replaced blocks should shrink-wrap (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 re...
...And 2 more matches
NPEvent - Archive of obsolete content
wparam 32 bit field for th...
...wparam 32 bit field for the windows event parameter; parameter...
...focus wm_killfocus for information about these events, see the microsoft windows developer documentation. wparam 32 bit field for the windows event parameter; parameter value depends upon event type. lparam 32 bit field for the windows event parameter; parameter value depends upon event type. eventrecord npevent on mac os npevent is defined as an eventrecord data structure, which has the following fields: what integer representing an event type. both windowed and windowless plug-ins receive the same events. values: 0 nullevent 1 mousedown 2 mouseup 3 keydown 4 keyup 5 autokey 6 updateevt 7 diskevt 8 activateevt 15 osevt 23 khighlevelevent getfocusevent 0, 1 (true, false) losefocusevent adjustcursorevent 0, 1 (true, false) for information about these events, see the mac os developer...
...And 2 more matches
The First Install Problem - Archive of obsolete content
istry key (identifying the activex control) as well as information about where to find the ocx (e.g. under the inprocserver32 subkey). for mozilla-based browsers, this system would be on a per-module basis, and instead of a uuid, we'll use a uri nomenclature 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 ve...
...rator 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 following values to the newly created key -- some are string values (reg_sz), and some are actually subkeys. string values take the form stringvalue=valuedata, and subkeys contain their own string values and value data. "path" -- string value -- this would be the absolute path to the plugin module. this is the path to the actual dll. (note that the file name must still begin with "np", just a...
...ased on an application's actual mimetypes. examples: [hkey_local_machine\software\mozillaplugins\@mycompany.com/myapplication,version=5.01\mimetypes\application/x-myapp] there can be more than one such subkey, depending on how many mimetypes an application wishes to handle (or advertise that it handles). the mimetypes subkeys contain the following string (reg_sz) value: "description" -- this is the actual description of the mimetype, very much as it appears in the dll (e.g. the same mimetype description that apears when you type "about:plugins" as a url in mozilla's location bar. example: [hkey_local_machine\software\mozillaplugins\]\@mycompany.com/myapplication,version=5.01\mim...
...And 2 more matches
Building a Theme - Archive of obsolete content
ws: \program files\mozilla firefox\omni.ja mac os x: /applications/firefox.app/contents/macos/omni.ja now, open (or unzip) this file into the directory you created. it contains several folders, modules, jssubloader and others. the files we will be needing are located under the chrome\toolkit\skin\classic folder. create a folder called chrome in your theme's folder. next, the contents of the following directories to their respective folders into the folder. global to chrome/global mozapps to chrome/mozapps now that you've copied the global and mozapps folders, a handful of other folders from the browser/omni.ja archive are required. it is located in the browser folder in the location mentioned above. the files we will be needing from the browser/omni.ja archive are located under chrom...
...folder. global to chrome/global mozapps to chrome/mozapps now that you've copied the global and mozapps folders, a handful of other folders from the browser/omni.ja archive are required. it is located in the browser folder in the location mentioned above. the files we will be needing from the browser/omni.ja archive are located under chrome/browser/skin/classic. copy the contents of the following directories to their respective folders. this gives us a base set of styles to work with. browser to chrome/browser/ communicator to chrome/communicator/ you should end up with this directory structure: <ext path>/ /install.rdf /chrome.manifest /chrome/ browser/ communicator/ global/ mozapp...
...it's especially important to install the dom inspector, which we'll be using in later steps. create the install manifest open the file called install.rdf that you created at the top of your extension'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#">...
...And 2 more matches
Using the W3C DOM - Archive of obsolete content
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. ...
... 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_attribute_value] the following form related properties (originally from internet explorer) are not supported in the w3c document object model: formname.inputname.value inputname.value formctrlname document.forms(0) (note: document.forms[0] (using square brackets) uses the dom standard forms collection) scripts that use these properties will throw errors in most standards-compliant browsers. instead, use the w3c dom ...
...hese are supported by internet explorer too so there is no need to use msie-specific attributes and methods. accessing elements with the w3c dom the basic method for referencing elements in an html page is document.getelementbyid(). all modern browsers support it. the method returns a reference to the uniquely identified element, which can then be used to script the element. ...
...And 2 more matches
-ms-filter - Archive of obsolete content
o be confused with the standard filter property, as the two are fundamentally incompatible with each other. important: as of windows internet explorer 9 this feature was deprecated. as of internet explorer 10 this feature was removed and should no longer be used. ...
...ogid> | <-ms-filter-function-legacy> where <-ms-filter-function-progid> = 'progid:' [ <ident-token> '.' ]* [ <ident-token> | <function-token> <any-value> ')' ] <-ms-filter-function-legacy> = <ident-token> | <function-token> <any-value> ')' the <string> contains the list of filters, transitions, and procedural surfaces. refer to the filters and transitions reference for details. examples the following example shows how to use the -ms-filter attribute in internet explorer 8. code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/filter_8.htm -ms-filter: 'progid:dximagetransform.microsoft.motionblur(strength=50), progid:dximagetransform.microsoft.basicimage(mirror=1)'; the following example shows how to use an inline style sheet to set the filter on an image. c...
... an inline style sheet to set the filter on an image. code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/filter_h.htm <img style="filter:progid:dximagetransform.microsoft.motionblur(strength=50) progid:dximagetransform.microsoft.basicimage(mirror=1)" src="/workshop/samples/author/dhtml/graphics/cone.jpg" height="80px" width="80px" alt="cone"> the following example shows how to use scripting to set the filter on an image. code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/filter_s.htm <body> <p>click the image to start the filter.</p> // call the function. <div id="filterfrom" style="position: absolute; width: 200px; height: 250px; background-color: white; ...
...And 2 more matches
Properly Using CSS and JavaScript in XHTML Documents - Archive of obsolete content
n an xhtml page is served with mime type text/html it is treated by all browsers as if it were nothing more than html. however when an xhtml page is served with mime type text/xml or application/xhtml+xml, then it should be treated as an xml document which must conform to the strict rules for authoring and displaying xml. proper xhtml is an application of xml and as such requires that authors follow strict rules when authoring xhtml. in particular: raw < and & characters are not allowed except inside of cdata sections (<![cdata[ ... ]]>). comments (<!—— ... ——>) must not contain double dashes (——). content contained within comments (<!—— ... ——>) can be ignored. problems with inline style and script inline style and script tags can cause several different problems...
... problems in xhtml when it is treated as xml rather than html. javascript contains characters which can not exist in xhtml javascript typically contains characters which can not exist in xhtml outside of cdata sections. <script type="text/javascript"> var i = 0; while (++i < 10) { // ... ...
... xhtml since the use of raw < is only allowed as a part of markup in xhtml or xml. use of comments inside inline style and script authors who are familiar with html commonly enclose the contents of inline style and script tags in comments in order to hide the contents of the tags from browsers which do not understand them. <style type="text/css"> <!-- body {background-color: blue; color: yellow;} --> </style> <script type="text/javascript"> <!-- var i = 0; var sum = 0; for (i = 0; i < 10; ++i) { sum += i; } alert('sum = ' + sum); // --> </script> this example illustrates that a conformant browser can ignore content inside of comments. in addition, this example shows how the differences between browsers in handling inline content in text/xml or application/xhtml+xml...
...And 2 more matches
Reference - Archive of obsolete content
olons be added to all the examples? --maian 21:06, 25 aug 2005 (pdt) the original authors didn't use semicolons, but i'd add them. --nickolay 00:58, 26 aug 2005 (pdt) (more coding style questions) --maian 04:06, 31 aug 2005 (pdt) i'd say, just make a note here about decisions you make. it would be best to have all examples to use the same style. --nickolay 05:37, 31 aug 2005 (pdt) gonna follow mozilla's coding guides here: http://www.mozilla.org/hacking/mozil...de.html#visual --maian 00:30, 20 september 2005 (pdt) btoa() and atob() base64 encode and decode functions this documentation is missing the base64 encode (btoa) and decode (atob) functions. anyone know why this has been left out? danbeck 07:02, 22 september 2005 (pdt) afaict , base64-related functionality is not a part of...
...ssing from the documentation? brundlefly 13:15, 19 december 2005 (pst) neither: core javascript 1.5 reference:operators:special operators:delete operator --nickolay 14:48, 19 december 2005 (pst) reading offline? well, may be it's no so common in today's world... but is there a way to get content of jsref-1.5 or other documents as a tarball? there are still valid needs for this: computers on slow links, computers behind insane firewalls, as well as computers not connected to internet. unfortunately there is not an [easy] method to download content/packages of content off of devmo for 'local' browsing/viewing/printing, yet. it is in the "nice to have" category for us here, however i am unaware of anyone feverishly working on it. (there are some other priorities ahead of that, imho). if d...
...nstance is for example the math object, it behaves same way as creating new object. i checked this by doing alert(math.constructor) //shows that object is its constructor alert(object.constructor) //shows that function is its constructor alert(function.constructor) //shows that function is its constructor note : the function.constructor seems to keep on refering to itself, if you do the following you get same results which suggests that this is indeed the top level object. alert(function.constructor.constructor) alert(function.constructor.constructor.constructor.constructor) function == object however the following statement suggests that function is object. but when we create a prototype method for object its also available in function object.prototype.myfunction = function() {}; a...
...And 2 more matches
Troubleshooting XForms Forms - Archive of obsolete content
ified version, xhtml 2.0, located at http://www.w3.org/2002/06/xhtml2 ) inline instance, no controls get bound have you remembered to use the correct namespace for the instance nodes? for an inline instance you most probably need to have <xf:instance xmlns=""> .... any instance, no controls get bound if no controls show with either inline instance or an <xf:instance src="...">, check the following: as with inline instance, make sure the instance of the form control ref binding expression matches the namespace of the data. if form controls are within repeat, check that you are using attribute nodeset for the repeat instead of attribute ref. if the instance is not in the empty namespace (xmlns=""), then all binding expressions must use a prefix bound to the namespace. xpath 1.0 expres...
...xf:instance id="ins2" xmlns=""> <data> <value>42</value> </data> </xf:instance> you should use <output ref="instance('ins2')/value"/> to show the contents of the value element. (specification). repeat and tables not working unfortunately you cannot do: <table> <xf:repeat nodeset="..."> <tr> ... </tr> </xf:repeat> </table> the xhtml modularization does not allow this. you either have to use css tables or repeat attributes, which at the moment are not working properly in the firefox xforms extension :( should be fixed by bug 306247 and bug 280368 respectively. submission not working if you are trying to replace="instance" make sure that the document being returned is xml. there will be an error on the javascript console if it is not. on most webserv...
... document being returned is xml. there will be an error on the javascript console if it is not. on most webservers you cannot use <submission method="post" action="file.xml"> to a static xml file. you need to use method="get", or <instance src="file.xml"> if the instance is always needed. if you are trying to submit to a different domain than the form is loaded from, make sure that you have allowed cross-domain submission for that specific "form domain". read here for more information. conflicts with other plug-ins if you are using the noscript plugin you may notice that your put and/or post requests are being converted to get requests. in order to fix this, go to the noscript options dialog (right-click on the 's' icon on the status bar and select 'options...') and select the advanced...
...And 2 more matches
Mozilla XForms Specials - Archive of obsolete content
o-classes in xforms (:enabled, :disabled, etc. ), except for :read-only and :read-write, because of non-specified behaviour of these for (x)html. instead you have to use :-moz-read-only and :-moz-read-write for now. (limitation tracked in bug 313111)pseudo element support there is no support for the pseudo elements (::value, ::repeat-item, and ::repeat-index ). instead you will have to use the following normal classes instead: xf-value xf-repeat-item xf-repeat-index for example, to target the value element of an input control use: @namespace xf url("http://www.w3.org/2002/xforms"); xf|input .xf-value { ... } the pseudo elements are defined in the css3 basic user interface specification . (limitation tracked in bug 271724) optional parameters in xpath functions optional parameters in xpat...
...th functions are not supported, you will have to specify all parameters when calling a function. this affects functions like hmac() or digest(). instead of using digest('abc', 'sha-1') explicitly use the third parameter (the results are equal): digest('abc', 'sha-1', 'base64') (limitation tracked in bug 477857) extensions enumerating instances the standardized nsixformsmodelelement does not allow one to enumerate over all possible instances, but only to retrieve instances by their name. in the mozilla xforms extension we added a getinstancedocuments() function to the model which returns all the model's instance documents. this is documented in nsixformsnsmodelelement. getting to instance element from a data node in the xforms 1.0 specification there is no way to get to the instance elemen...
...zilla xforms extension we added a getinstancedocuments() function to the model which returns all the model's instance documents. this is documented in nsixformsnsmodelelement. getting to instance element from a data node in the xforms 1.0 specification there is no way to get to the instance element from an instance data node. we have added a function via the getfeature() call on each node, that allows the form author to do that. that is, if instancenode is a node in an instance document, then: instancenode.getfeature("org.mozilla.xforms.instanceowner", "1.0") will return the <instance> element (in the main document) that the node belongs to. getting to the instance document from the instance element in the xforms 1.0 specification you have to go through the model element to get to the instan...
...And 2 more matches
Archived open Web documentation - Archive of obsolete content
znerd 04 august 2009 browser detection and cross browser support 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. ...
... znerd 04 august 2009 browser detection and cross browser support 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. ...
...l and iterates over enumerable properties of an object. liveconnect (please update or remove as needed.) msx emulator (jsmsx) 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, thoug...
...And 2 more matches
Mozilla's DOCTYPE sniffing - Archive of obsolete content
scribes 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 that need to be in quirks mode to be displayed correctly should be displayed using quirks mode. (almost all, rather than all, to allow for the following points as well.) authors writing web pages to current standards should be able to trigger strict mode. pages written using any public identifiers in doctype declarations that appear in the f...
...ages 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 ibm doctype noted below a doctype declaration without a dtd, i.e., <!doctype html>. a doctype declaration with an interna...
... the public identifier "-//w3c//dtd html 4.0//en". ...
...And 2 more matches
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
.2 and higher and netscape versions 6.1 and higher. it does not cover netscape 6 and 6.01 introduction plugins that used to take advantage of being scriptable via liveconnect in 4.x netscape browsers lost this possibility in the new world. the main reason for this is that there is no guarantee of java compatibility on a binary level due to the jri/jni switch. ...
...the present document describes the steps of what should be done to the plugin code to turn it scriptable again. ...
... will contain native methods callable from javascript. this class should also inherit from nsiclassinfo and implement its methods to be able to request all necessary privileges from the mozilla security manager (see example 2). two new cases for the above mentioned new variables should be added to the plugin implementation of npp_getvalue (see example 3). ...
...And 2 more matches
Common causes of memory leaks in extensions - Extensions
g 727552. to avoid these issues, references to dom nodes in foreign document should instead be stored in an object which is specific to that document, and cleaned up when the document is unloaded, or stored as weak references. be careful with setinterval/settimeout using window.setinterval() or window.settimeout() can be problematic, too, when it comes to zombie compartments. ...
...-on like noscript), then using the content window functions won't work. problems in bootstrapped (restartless) add-ons bootstrapped extensions use a bootstrap.js compartment. if you put a reference to anything within this compartment into a long-lived window object (such as browser.xul), javascript module or xpcom component, the bootstrap.js compartment will become a zombie. for example, the following code snippets — part of a bootstrap.js — will leak: function leakref() {} function modifydocument(document) { var a = document.createelement("a"); document.body.appendchild(a); // the new dom node holding a reference to leakref will prevent // that function object from being garbage collected and hence // will leak the whole bootstrap compartment. a.someproperty = leakref; }...
...window in question is browser.xul or some long-lived web app such as gmail, the leaked compartment might survive for quite some time. function leakref() {} function main(window) { // this is a potential leak, as the window (e.g. browser.xul) will hold on to // the leakref function and the enclosing compartment via the listener. window.addeventlistener("leaky", leakref, true); // the following line still fails to avoid the leak, as usecapture differs // and removeeventlistener will not remove anything. // this kind of subtle bug is very common. // unload(function() window.removeeventlistener("leaky", leakref, false), window); // this is the right way to do it remove the listener. unload(function() window.removeeventlistener("leaky", leakref, true), window); } note: the ...
...And 2 more matches
Game monetization - Game development
ime and money in marketing. only the best games will break even or earn more than they cost to make, and you still need a lot of luck for that. how much you charge for your game depends on the market, quality of your game and a lot of other small factors. an arcade ios title can be sold for 0.99 usd, but a longer rpg-style desktop game on steam can cost 20 usd; both prices are ok. you have to follow the market and do your own research — learning from your mistakes quickly is important. in-app purchases instead of having people pay for your game up front, you can offer a free game with in-app purchases (iaps.) in this case the game can be acquired without spending a dime — give the game to the players, but offer in-game currency, bonuses or benefits for real money. specific examples can...
...g on previous activities related to promoting your game may benefit, but your game has to be addictive, which isn't as easy as it sounds. you still need to plan it out, and at some point you'll need a bit of luck too. if your game goes viral and people start sharing it, you can get a lot of downloads and money out of adverts. there are many companies offering advert systems — you sign up and allow them to show adverts in exchange for a percentage of the earnings. google adsense is said to be the most effective one, but it's not designed for games and it's a pretty bad practice to use it for that purpose. instead of risking of having your account closed and all the money blocked try to use the usual, gamedev targeted portals like leadbolt. they offer easy to implement systems to show the ad...
... players too much, but visible enough to make them click it or at least take notice. adding adverts between game sessions on game over screens is a popular approach. licensing there's an approach that can work as a monetization model on it's own, and that's selling licenses for distribution of your game. there are more and more portals interested in showing your games on their websites. they follow various strategies to earn money via your games, but you don't have to worry about all that as selling the license is usually a one-time deal. you get the money and they can get creative with using your game to make money. finding publishers might be hard at first — try to look for them at the html5 gamedevs forums. if you're well known they may reach out to you. most of the deals are done thr...
...And 2 more matches
Unconventional controls - Game development
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 years can make — you can read the whole story in our building games for firefox os tv hacks post. using a tv remote to control the game ended up being surprisingly easy, because the events fired by the controller are emulating conventional keyboard keys. captain rogers had the keyboard controls imple...
...have exactly the same key codes as the arrow keys on the remote. how do you know the codes for the other remote keys? you can check them by printing the responses out in the console: window.addeventlistener("keydown", function(event) { console.log(event.keycode); }, this); every key pressed on the remote will show its key code in the console. you can also check this handy cheat sheet seen below if you're working with panasonic tvs running firefox os: you can add moving between states, starting a new game, controlling the ship and blowing stuff up, pausing and restarting the game. all that is needed is checking for key presses: window.addeventlistener("keydown", function(event) { switch(event.keycode) { case 8: { // pause the game break; } ...
...n for kiwi.js, or the case study of building a web game with leap motion and pixi.js. be sure to visit the leapjs repository on github to learn about the javascript client for the leap motion controller and read the documentation there. if all else fails, there's also a gallery of working examples you can look at. to get the leap motion working on your computer you have to first install it by following the steps at leapmotion.com/setup. when everything is installed and the controller is connected to your computer we can proceed with implementing support in our little demo. first, we add a <script> tag with the url pointing at this file, and add <div id="output"></div> just before the closing </body> tag for outputting diagnostic information. we will need a few helper variables for our code ...
...And 2 more matches
Extra lives - Game development
h step out of 16 of the gamedev phaser tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson13.html. we can make the game enjoyable for longer by adding lives. in this article we'll implement a lives system, so that the player can continue playing until they have lost three lives, not just one. new variables add the following new variables below the existing ones in your code: var lives = 3; var livestext; var lifelosttext; these respectively will store the number of lives, the text label that displays the number of lives that remain, and a text label that will be shown on screen when the player loses one of their lives. defining the new text labels defining the texts look like something we already did in the ...
...he existing ones in your code: var lives = 3; var livestext; var lifelosttext; these respectively will store the number of lives, the text label that displays the number of lives that remain, and a text label that will be shown on screen when the player loses one of their lives. defining the new text labels defining the texts look like something we already did in the score lesson. ...
...s in your code: var lives = 3; var livestext; var lifelosttext; these respectively will store the number of lives, the text label that displays the number of lives that remain, and a text label that will be shown on screen when the player loses one of their lives. defining the new text labels defining the texts look like something we already did in the score lesson. ...
...And 2 more matches
Load the assets and print them on screen - Game development
as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson03.html. our game will feature a ball rolling around the screen, bouncing off a paddle, and destroying bricks to earn points — familiar, huh? in this article we'll look at how to add sprites into our gameworld. having a ball let's start by creating a javascript variable to represent our ball. add the following line between the game initialization code (our var game... block) and the preload() function: var ball; note: for the sake of this tutorial, we will use global variables. the purpose of the tutorial is to teach phaser-specific approaches to game development rather than dwelling on subjective best approaches. loading the ball sprite loading images and printing them on our canvas is a lot...
...global variables. the purpose of the tutorial is to teach phaser-specific approaches to game development rather than dwelling on subjective best approaches. loading the ball sprite loading images and printing them on our canvas is a lot easier using phaser than using pure javascript. to load the asset, we will use the game object created by phaser, executing its load.image() method. add the following new line just inside the preload() function, at the bottom: function preload() { // ... game.load.image('ball', 'img/ball.png'); } the first parameter we want to give the asset is the name that will be used across our game code — for example, in our ball variable name — so we need to make sure it is the same. the second parameter is the relative path to the graphic asset. in our...
...er we want to give the asset is the name that will be used across our game code — for example, in our ball variable name — so we need to make sure it is the same. the second parameter is the relative path to the graphic asset. in our case, we will load the image for our ball. ...
...And 2 more matches
Gecko FAQ - Gecko Redirect 1
cko? gecko is the open source browser engine designed to support open internet standards such as html 5, css 3, the w3c dom, xml, javascript, and others. gecko is used in multiple browsers, including mozilla firefox, seamonkey, and others. gecko is continuously under development at mozilla.org. gecko has been known previously by the code names "raptor" and "nglayout"; the new name was chosen following a trademark infringement dispute. for more information see the wikipedia article on gecko. what is a layout engine? basically, a layout engine takes content (such as html, xml, image files, applets, and so on) and formatting information (such as cascading style sheets, presentational html tags, etc.) and displays the formatted content on the screen. it paints the browser's content area, whi...
...develop browser software. these developers can pick and choose the browser components they want from among those that gecko offers, and package these components alongside their own within their finished products. ...
...ponents they want from among those that gecko offers, and package these components alongside their own within their finished products. ...
...And 2 more matches
Test your skills: HTML accessibility - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. html accessibility 1 in this task we will test your understanding of text semantics, and why they are good for accessibility. ...
...task we will test your understanding of text semantics, and why they are good for accessibility. the given text is a simple information panel with action buttons, but the html is really bad. we want you to update it use appropriate semantic html. you don't need to worry too much about recreating the exact same look and text sizing, as long as the semantics are good. 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. html accessibility 2 in the second task, you have a form containing three input fields. you need to: semantically associate the input with their labels. assume that these inputs will be part of a larger form, and wrap them in an element that associates them all...
...e second task, you have a form containing three input fields. you need to: semantically associate the input with their labels. assume that these inputs will be part of a larger form, and wrap them in an element that associates them all together as a single related group. give the group a description/title that summarises all of the information as personal data. 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. html accessibility 3 in this task you are required to turn all the information links in the paragraph into good, accessible links. the first two links just go to regular web pages. the third link goes to a pdf, and it's large — 8mb. the fourth link goes to a...
...And 2 more matches
Test your skills: WAI-ARIA - Learn web development
this aim of this skill test is to assess whether you've understood our wai-aria basics article. note: you can try out solutions in the interactive 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. ...
... 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. ...
... 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. ...
...And 2 more matches
Combinators - Learn web development
endant combinator — typically represented by a single space ( ) character — combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc) element matching the first selector. selectors that utilize a descendant combinator are called descendant selectors. body article p in the example below, we are matching only the <p> element which is inside an element with a class of .box. child combinator the child combinator (>) is placed between two css selectors. it matches only those elements matched by the second selector that are the direct children of elements matched by the first. descendent elements further down the hierarchy don't match. for example, to select only <p> elements tha...
...u end up with a descendant selector and all <li> elements will get a red border. adjacent sibling combinator the adjacent sibling selector (+) is used to select something if it is right next to another element at the same level of the hierarchy. for example, to select all <img> elements that come right after <p> elements: p + img a common use case is to do something with a paragraph that follows a heading, as in my example below. here we are looking for a paragraph which is directly adjacent to an <h1>, and styling it. if you insert some other element such as a <h2> in between the <h1> and the <p>, you will find that the paragraph is no longer matched by the selector and so does not get the background and foreground color applied when the element is adjacent. general sibling combina...
...ger matched by the selector and so does not get the background and foreground color applied when the element is adjacent. general sibling combinator if you want to select siblings of an element even if they are not directly adjacent, then you can use the general sibling combinator (~). to select all <img> elements that come anywhere after <p> elements, we'd do this: p ~ img in the example below we are selecting all <p> elements that come after the <h1>, and even though there is a <div> in the document as well, the <p> that comes after it is selected. using combinators you can combine any of the selectors that we discovered in previous lessons with combinators in order to pick out part of your document. for example if we want to select list items with a class of "a", which are direct...
...And 2 more matches
CSS building blocks - Learn web development
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/another 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 this module contains the following articles, which cover the most essential parts of the css language. along the way you'll come across plenty of exercises to allow you to test your understanding. cascade and inheritance the aim of this lesson is to develop your understanding of some of the most fundamental concepts of css — the cascade, specificity, and inheritance — which control how css is applied to html and how con...
... come across plenty of exercises to allow you to test your understanding. cascade and inheritance the aim of this lesson is to develop your understanding of some of the most fundamental concepts of css — the cascade, specificity, and inheritance — which control how css is applied to html and how conflicts are resolved. css selectors there are a wide variety of css selectors available, allowing for fine-grained precision when selecting elements to style. in this article and its sub-articles, we'll run through the different types in great detail, seeing how they work. ...
...the cascade, specificity, and inheritance — which control how css is applied to html and how conflicts are resolved. css selectors there are a wide variety of css selectors available, allowing for fine-grained precision when selecting elements to style. in this article and its sub-articles, we'll run through the different types in great detail, seeing how they work. the sub-articles are as follows: type, class, and id selectors attribute selectors 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...
...And 2 more matches
Test your skills: Flexbox - Learn web development
the aim of this task is to get you working with flexbox and demonstrate your understanding of how flex items behave. below are four common design patterns which you might use flexbox to create, your task is to build them. note: you can try out solutions in the interactive 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. flex layout one these list items are the navigation for a site. ...
... 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. flex layout one these list items are the navigation for a site. they should be laid out as a row, with an equal amount of space between each item. the finished example should look like the image below. 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. flex layout two these list items are all different sizes, but we want them to be displayed as three equal sized columns, no matter what content is in each item. try updating the live c...
...ry 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. flex layout two these list items are all different sizes, but we want them to be displayed as three equal sized columns, no matter what content is in each item. try updating the live code below to recreate the finished example: additional questions: can you now make the first item twice the size of the other items? for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. flex layout three there are two elements in the html below, a div with a class of .parent which contains another div with a class ...
...And 2 more matches
Test your skills: Grid Layout - Learn web development
this aim of this task is to get you working with css grid layout, and test that you understand how a grid and grid items behave. you will be working through three small tasks which use different elements of the material you have just covered. note: you can try out solutions in the interactive 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. grid layout one in this task you should create a grid into which the four child elements will auto-place. the grid should have three columns sharing the available space equally, and a 20-pixel gap between the column and row tracks. try u...
...k 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. grid layout one in this task you should create a grid into which the four child elements will auto-place. the grid should have three columns sharing the available space equally, and a 20-pixel gap between the column and row tracks. 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. grid layout two in this example we already have a grid defined. by editing the css rules for the two child elements, cause them to span over several grid tracks each; the second item should overlay the first as in the image ...
...o 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. grid layout two in this example we already have a grid defined. by editing the css rules for the two child elements, cause them to span over several grid tracks each; the second item should overlay the first as in the image below. try updating the live code below to recreate the finished example: additional questions: can you now cause the first item to display on top without changing the order of items in the source? for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. grid layout three there are four direct children in this g...
...And 2 more matches
Multiple-column layout - Learn web development
ains how to use this feature. prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css.) objective: to learn how to create multiple-column layout on webpages, such as you might find in a newspaper. a basic example we will now explore how to use multiple-column layout, often referred to as multicol. you can follow along by downloading the multicol starting point file and adding the css into the appropriate places. at the bottom of the section you can see a live example of what the final code should look like. our starting point contains some very simple html; a wrapper with a class of container inside which is a heading and some paragraphs. the <div> with a class of container will become our multicol con...
...k like. our starting point contains some very simple html; a wrapper with a class of container inside which is a heading and some paragraphs. the <div> with a class of container will become our multicol container. we switch on multicol by using one of two properties column-count or column-width. the column-count property will create as many columns as the value you give it, so if you add the following css to your stylesheet and reload the page, you will get three columns: .container { column-count: 3; } the columns that you create have flexible widths — the browser works out how much space to assign each column. column-count example body { width: 90%; max-width: 900px; margin: 2em auto; font: .9em/1.2 arial, helvetica, sans-serif; } <div class="container"> <h1>si...
... vivamus tristique elit dolor, sed pretium metus suscipit vel. mauris ultricies lectus sed lobortis finibus. vivamus eu urna eget velit cursus viverra quis vestibulum sem. aliquam tincidunt eget purus in interdum. cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p> </div> .container { column-count: 3; } change your css to use column-width as follows: .container { column-width: 200px; } the browser will now give you as many columns as it can of the size that you specify; any remaining space is then shared between the existing columns. this means that you will not get exactly the width that you specify, unless your container is exactly divisible by that width. column-width example body { width: 90%; max-width: 900px; margin: 2e...
...And 2 more matches
create fancy boxes - Learn web development
also all about unleashing your creativity. it will not be done in one day, and some web developers spend their whole life having fun with it. we are about to see many examples, but we will always work on the most simple piece of html possible, a simple element: <div class="fancy">hi! i want to be fancy.</div> ok, that's a very small bit of html, what can we tweak on that element? all of the following: its box model properties: width, height, padding, border, etc. its background properties: background, background-color, background-image, background-position, background-size, etc. its pseudo-element: ::before and ::after and some aside properties like: box-shadow, transform, outline, etc. so we have a very large playground. let the fun begin. box model tweak the box model alone all...
...</div> this is something that is both very simple and very fun. the border-radius property is made to create a rounded corner applied to boxes, but what happens if the radius size is equal or larger than the actual width of the box? .fancy { /* within a circle, centered text looks prettier. */ text-align : center; /* let's avoid our text touching the border. as our text will still flow in a square, it looks nicer that way, giving the feeling that it's a "real" circle. */ padding : 1em; /* the border will make the circle visible. you could also use a background, as backgrounds are clipped by border radius */ border : 0.5em solid black; /* let's make sure we have a square. if it's not a square, we'll get an ellipsis rather than a circle ;) ...
...: #a4c9cf; /* well, actually we are not making a full circle as we want the bottom of our cloud to be flat. feel free to tweak this example to make a cloud that isn't flat at the bottom ;) */ border-radius: 100% 100% 0 0; } /* those are common style that apply to both our ::before and ::after pseudo elements. */ .fancy::before, .fancy::after { /* this is required to be allowed to display the pseudo-elements, event if the value is an empty string */ content: ''; /* we positionnate our pseudo-elements on the left and right sides of the box, but always at the bottom */ position: absolute; bottom : 0; /* this makes sure our pseudo-elements will be below the box content whatever happens. */ z-index : -1; background-color: #a4c9cf; b...
...And 2 more matches
How much does it cost to do something on the Web? - Learn web development
ighted, so it is better to check the license of the file before you use it. sites like pixabay provide images under cc0 license, so you can use, edit and publish them even with modification for commercial use. media editors if you want to include video or audio into your website, you can either embed online services (for example youtube, vimeo, or dailymotion), or include your own videos (see below for bandwidth costs). for audio files, you can find free software (audacity, wavosaur), or paying up to a few hundred dollars (sony sound forge, adobe audition). likewise, video-editing software can be free (pitivi, openshot for linux, imovie for mac), less than $100 (adobe premiere elements), or several hundred dollars (adobe premiere pro, avid media composer, final cut pro). the software you r...
...rowsers you either already have a browser or can get one for free. if necessary, download firefox here or google chrome here. web access computer / modem you need a computer. costs can vary tremendously, depending on your budget, and where you live. to publish a barebones website, you only need a basic computer capable of launching an editor, and a web browser, so the entry level can be quite low. of course, you'll need a more serious computer if you want to produce complicated designs, touch up photos, or produce audio and video files. you need to upload content to a remote server (see hosting below), so you need a modem. your isp can rent internet connectivity to you for a few dollars per month, though your budget might vary, depending on your location. isp access make sure that you...
...that will likely cost you a few dozen dollars, including the rent for the modem. ...
...And 2 more matches
How do you upload your files to a web server? - Learn web development
ample hosting provider" whose urls look like this: mypersonalwebsite.examplehostingprovider.net. we have just opened an account and received this info from them: congratulations for opening an account at example hosting provider. your account is: demozilla your website will be visible at demozilla.examplehostingprovider.net to publish to this account, please connect through sftp with the following credentials: sftp server: sftp://demozilla.examplehostingprovider.net username: demozilla password: quickbrownfox port: 5548 to publish on the web, put your files into the public/htdocs directory. let's first look at http://demozilla.examplehostingprovider.net/ — as you can see, so far there is nothing there: note: depending on your hosting provider, most of the time you'll see...
...to the public/htdocs directory. let's first look at http://demozilla.examplehostingprovider.net/ — as you can see, so far there is nothing there: note: depending on your hosting provider, most of the time you'll see a page saying something like “this website is hosted by [hosting service].” when you first go to your web address. to connect your sftp client to the distant server, follow these steps: choose file > site manager... from the main menu. in the site manager window, press the new site button, then fill in the site name as demozilla in the provided space. fill in the sftp server your host provided in the host: field. in the logon type: drop down, choose normal, then fill in your provided username and password in the relevant fields. fill in the correct port and o...
...à! our website is live! rsync rsync is a local-to-remote file synchronizing tool, which is generally available on most unix-based systems (like macos and linux), but windows versions exist too. it is seen as a more advanced tool than sftp, beause by default it is used on the command line. a basic command looks like so: rsync [-options] source user@x.x.x.x:destination -options is a dash followed by a one or more letters, for example -v for verbose error messages, and -b to make backups. you can see the full list at the rsync man page (search for "options summary"). source is the path to the local file or directory that you want to copy files over from. user@ is the credentials of the user on the remote server you want to copy files over to. x.x.x.x is the ip address of the remote se...
...And 2 more matches
What are hyperlinks? - Learn web development
led links, are a foundational concept behind the web. to explain what links are, we need to step back to the very basics of web architecture. back in 1989, tim berners-lee, the web's inventor, spoke of the three pillars on which the web stands: url, an address system that keeps track of web documents http, a transfer protocol to find documents when given their urls html, a document format allowing for embedded hyperlinks as you can see in the three pillars, everything on the web revolves around documents and how to access them. the web's original purpose was to provide an easy way to reach, read, and navigate through text documents. since then, the web has evolved to provide access to images, videos, and binary data, but these improvements have hardly changed the three pillars. befor...
...t. tap or click a link to activate it, or if you use a keyboard, press tab until the link is in focus and hit enter or spacebar. links are the breakthrough that made the web so useful and successful. in the rest of this article, we discuss the various types of links and their importance to modern web design. deeper dive as we said, a link is a text string tied to a url, and we use links to allow easy jumping from one document to another. that said, there are some nuances worth considering: types of links internal link a link between two webpages, where both webpages belong to 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 ...
...ver 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 same way as other links. links and search engines links matter both to users and search engines. ev...
...And 2 more matches
Images in HTML - Learn web development
ceived explicit, written permission from the image owner. you have ample proof that the image is, in fact, in the public domain. copyright violations are illegal and unethical. in addition, never point your src attribute at an image hosted on someone else's website that you don't have permission to link to. this is called "hotlinking". again, stealing someone's bandwidth is illegal. it also slows down your page, leaving you with no control over whether the image is removed or replaced with something embarrassing. our above code would give us the following result: note: elements like <img> and <video> are sometimes referred to as replaced elements. this is because the element's content and size are defined by an external resource (like an image or video file), not by the contents of...
...e or video file), not by the contents of the element itself. note: you can find the finished example from this section running on github (see the source code too.) alternative text the next attribute we'll look at is alt. its value is supposed to be a textual description of the image, for use in situations where the image cannot be seen/displayed or takes a long time to render because of a slow internet connection. for example, our above code could be modified like so: <img src="images/dinosaur.jpg" alt="the head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"> the easiest way to test your alt text is to purposely misspell your filename. if for example our image name was spelled dinosooooor.jpg, the browser wouldn't display the image, and wo...
...e title attribute by scott o'hara. it is better to include such supporting information in the main article text, rather than attached to the image. active learning: embedding an image it is now your turn to play! this active learning section will have you up and running with a simple embedding exercise. you are provided with a basic <img> tag; we'd like you to embed the image located at the following url: https://udn.realityripple.com/samples/ec/5a13bd14f6.jpg earlier we said to never hotlink to images on other servers, but this is just for learning purposes, so we'll let you off this one time. we would also like you to: add some alt text, and check that it works by misspelling the image url. set the image's correct width and height (hint: it is 200px wide and 171px high), then expe...
...And 2 more matches
General asynchronous programming concepts - Learn web development
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 can appear to be frozen. this is called blocking; the browser is blocked from continuing to handle user input and perform other tasks until t...
... thread 2: task c --> task d javascript is single-threaded javascript is traditionally single-threaded. even with multiple cores, you could only get it to run tasks on a single thread, called the main thread. our example from above is run like this: main thread: render circles to canvas --> display alert() after some time, javascript gained some tools to help with such problems. web workers allow you to send some of the javascript processing off to a separate thread, called a worker so that you can run multiple javascript chunks simultaneously. you'd generally use a worker to run expensive processes off the main thread so that user interaction is not blocked. main thread: task a --> task c worker thread: expensive task b with this in mind, have a look at simple-sync-worker.html (see i...
...t get a worker to directly do anything to update the ui. we couldn't render our 1 million blue circles inside our worker; it can basically just do the number crunching. the second problem is that although code run in a worker is not blocking, it is still basically synchronous. this becomes a problem when a function relies on the results of multiple previous processes to function. consider the following thread diagrams: main thread: task a --> task b in this case, let's say task a is doing something like fetching an image from the server and task b then does something to the image like applying a filter to it. if you start task a running and then immediately try to run task b, you'll get an error, because the image won't be available yet. main thread: task a --> task b --> |task d| worke...
...And 2 more matches
Test your skills: Object basics - Learn web development
this aim of this skill test is to assess whether you've understood our javascript object basics article. note: you can try out solutions in the interactive 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. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). object basics 1 in this task you are provided with an object literal, and your tasks are to store the value of the name property...
... of the downloadable version). object basics 1 in this task you are provided with an object literal, and your tasks are to store the value of the name property inside the catname variable, using bracket notation. run the greeting() method using dot notation (it will log the greeting to the browser devtools' console). update the color property value to black. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. object basics 2 in our next task, we want you to have a go at creating your own object literal to represent one of your favourite bands. the required members are: name: a string representing the band name. nationality: a string representing the country the band...
...e band comes from. genre: what type of music the band plays. members: a number representing the number of members the band has. formed: a number representing the year the band formed. split: a number representing the year the band split up, or false if they are still together. albums: an array representing the albums released by the band. each array item should be an object containing the following members: name: a string representing the name of the album. released: a number representing the year the album was released. include at least two albums in the albums array. once you've done this, you should then write a string to the variable bandinfo, which will contain a small biography detailing their name, nationality, years active, and style, and the title and release...
...And 2 more matches
Measuring performance - Learn web development
mputer literacy, basic software installed, and basic knowledge of client-side web technologies. 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 performanceentry object is part of the performance timeline. ...
...gation and timings article for further examples on using performance web apis. tools and metrics there are a number of different tools available to help you improve performance. these can generally be classified into two categories: tools that indicate or measure performance, such as pagespeed insights or the firefox network monitor and performance monitor. these tools show you how fast or slow your web app or site load. they also indicate areas that can be improved to optimize your web app. tools that update code so that your web app or site will perform better. for example, bundling tools pack your code into single files to reduce the number of http requests or minifiers that remove all whitespace from your code to make the files smaller. we'll talk about both categories in this co...
...And 2 more matches
Multimedia: video - Learn web development
e 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 reduce file size. if not, there a...
...ss 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 reduce file size. if not, there are online tools, such as ffmpeg (discussed in section below), that encode, decode, convert, and perform other optimization functions. optimize <source> order order video source from smallest to largest. for example, given video compressions in three different formats at 10mb, 12mb, and 13mb, declare the smallest first and the largest last: <video width="400" height="300" controls="controls"> <!-- webm: 10 mb --> <source src="video.webm" type="vide...
...e that a looping background video autoplays, you must add several attributes to the video tag: autoplay, muted, and playsinline. <video autoplay="" loop="" muted="true" playsinline="" src="backgroundvideo.mp4"> while the loop and autoplay make sense for a looping and autoplaying video, the muted attribute is required for autoplay in mobile browsers. playsinline is required for mobile safari, allowing videos to play without forcing fullscreen mode. remove audio from muted hero videos for hero-video or other video without audio, removing audio is smart. <video autoplay="" loop="" muted="true" playsinline="" id="hero-video"> <source src="banner_video.webm" type='video/webm; codecs="vp8, vorbis"'> <source src="web_banner.mp4" type="video/mp4"> </video> this hero-video code (a...
...And 2 more matches
Learn web development
ion 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 development for complete beginners. html — structuring the web html is the language that we use to structure the different parts of our content and define what their meaning or purpose is. this topic teaches html in detail. css — styling the web css i...
...cript — dynamic client-side scripting javascript is the scripting language used to add dynamic functionality to web pages. this topic teaches all the essentials needed to become comfortable with writing and understanding javascript. web forms — working with user data web forms are a potent tool for interacting with users — most commonly, they are used for collecting data from users, or allowing them to control a user interface. in the articles listed below, we'll cover all the essential aspects of structuring, styling, and interacting with web forms. accessibility — make the web usable by everyone accessibility is the practice of making web content available to as many people as possible regardless of disability, device, locale, or other differentiating factors. this topic gives ...
...ng how to build up a server-side app using two popular frameworks: django (python) and express (node.js). getting our code examples the code examples you'll encounter in the learning area are all available on github. if you want to copy them all to your computer, the easiest way is to download a zip of the latest master code branch. if you prefer to copy the repo in a more flexible way that allows for automatic updates, you can follow the more complex instructions: install git on your machine. this is the underlying version control system software that github works on top of. open your computer's command prompt (windows) or terminal (linux, macos). to copy the learning area repo to a folder called learning-area in the current location your command prompt/terminal is pointing to, use ...
...And 2 more matches
Accessibility information for UI designers and developers
when 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. color enough contrast ensure there is enough contrast between foreground and background colors. your content can then be better consumed by users with low vision and people with color deficiencies. the ratio should be 4.5:1 for regular text and 3:1 for large text. calculating this ratio is easiest done with a tool, for example lea verou's contrast ratio. there are also plug-ins available for design software, like stark for sketch. don't rely on color alone when your interface uses color to distinguish between things, make sure the distinction is also made in other ways. for example, add text l...
...ator, as without it, users that can't or don't use a mouse cannot see where they are. it would be like removing the mouse indicator. see also: understanding sc 2.4.7: focus visible be ready for resizing and custom styles on the web, users can use tools in their browser to make font sizes larger, or even provide custom css to meet their specific needs. ...
...ible be ready for resizing and custom styles on the web, users can use tools in their browser to make font sizes larger, or even provide custom css to meet their specific needs. ensure your design is flexible enough to allow for this. text sizing users should be able to enlarge their text size up to 200 percent without breaking functionality. ...
...And 2 more matches
Mozilla's Section 508 Compliance
ard 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/unix ma...
...ually. 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 the keyboard: 1) find as you type allows for quick navigation to links and convenient text searching 2) browse with caret (f7 key toggles) allows users to select arbitrary content with the keyboard and move through content as if inside a readonly editor. incomplete. inadequate attention paid to mac keyboard bugs. needs more investigation. (b) applications shall not disrupt or disable activated features of ...
...color contrast settings. when the windows "high contrast theme" is used classic, and thus the system look and feel, is automatically selected. complete when run in the gnome desktop. the default theme, classic, uses gnome's font and color contrast settings. under linux/unix it is the user's choice, whether to stick with the gnome theme or not -- they must choose classic if they want to follow the gnome theme. unknown - needs research (h) when animation is displayed, the information shall be displayable in at least one non-animated presentation mode at the option of the user. complete. mozilla's preferences under privacy & security - images contain options for making animated images still. (i) color coding shall not be used as...
...And 2 more matches
Android-specific test suites
studio, which is the fastest way to iterate on code and tests. disabling one failing test there is no manifest listing the android local unit tests. to disable a single test, edit the source code and insert junit's @ignore annotation before the existing @test annotation. for example, to disable org.mozilla.gecko.permissions.testsuccessrunnableisexecutedifpermissionsaregranted, add @ignore as follows: ... @runwith(testrunner.class) public class testpermissions { @ignore @test public void testsuccessrunnableisexecutedifpermissionsaregranted() { ... contact information android-test is currently owned by :sebastian and :nalexander. file tickets in the firefox for android product in bugzilla. android-checkstyle verifies that the java coding style is consistent throughout. see...
...net/index.html and https://docs.gradle.org/2.14/userguide/checkstyle_plugin.html for more details. running android-checkstyle to run android-checkstyle, first build firefox for android with your changes; then run ./mach android checkstyle this will run the tests and report the results to stdout, as well as produce an html report. disabling one failing test in general, it's not sensible to allow java code that doesn't observe the existing coding style; in this respect, this job is equivalent to the eslint jobs that check the javascript coding style throughout the tree. however, the existing configuration can be tweaked and the set of files checked can be modified. contact information android-checkstyle is currently owned by :mcomella and :nalexander. file tickets in the firefox for and...
...ck the javascript coding style throughout the tree. however, the existing configuration can be tweaked and the set of files checked can be modified. contact information android-checkstyle is currently owned by :mcomella and :nalexander. file tickets in the firefox for android product in bugzilla. android-findbugs ensures that the code avoids common java coding errors. using this suite will allow the code to be analyzed to spot any design flaws or potential bugs. if an issue is found within the code, a warning will be identified and put into the correct category that the suite controls — this could be malicious, correctness, or just bad practice. see http://findbugs.sourceforge.net/index.html and https://docs.gradle.org/2.14/userguide/findbugs_plugin.html for more details. running and...
...And 2 more matches
Creating a Language Pack
subdirectory ab-cd where ab-cd is your locale code). you still need to specify which application you're localizing (e.g., for firefox, that's browser, thunderbird would be mail). configure step you need to prepare the build directory, which is done with ./mach configure you only need to run this if the version number of firefox changes. ...
... // lots of notifications about missing entities ... ...
...e repacked to include your locale. $ make wget-en-us en_us_binary_url=http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-mozilla-aurora if you're building on mac 64 bit, you'll need to change the command slightly: $ make wget-en-us en_us_binary_url=http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-mozilla-aurora moz_pkg_platform=mac at some point, you should see the following success message: downloaded http://ftp.mozilla.org/pub/mozilla.o....en-us.mac.dmg to /users/your_id/mozilla/vc/firefox/browser/locales/../../dist/firefox-3.6b5pre.en-us.mac.dmg the en-us binary has been downloaded. let's unpack it $ make unpack again, for 64-bit mac, append moz_pkg_platform=mac to this command. at the end of the process, you should see the following success message. ... ...
...And 2 more matches
Simple Thunderbird build
e basic steps needed to build a bleeding-edge, development version of thunderbird 60 or later. for thunderbird up to 59, see the old build documentation. for additional, more detailed information, see the build documentation. hardware requirements at least 4 gb of ram. 8 gb or more is recommended. while you can build thunderbird on older hardware it can take quite a bit of time to compile on slower machines with less ram. good internet connection for the initial source download. build prerequisites depending on your operating system you will need to carry out a different process to prepare your machine. so firstly complete the instructions for your os and then continue following these build instructions. windows build prerequisites gnu/linux build prerequisites macos build prereq...
...rd 59 and earlier): hg clone https://hg.mozilla.org/mozilla-central source/ cd source/ hg clone https://hg.mozilla.org/comm-central comm/ the source code requires 3.6gb of free space or more and additionally 5gb or more for default build. build configuration to build thunderbird, you need to add a file named mozconfig to the root directory of the mozilla-central checkout that contains the following line: ac_add_options --enable-application=comm/mail you can create a file with this line by doing this in the source/ directory: echo 'ac_add_options --enable-application=comm/mail' > mozconfig if you omit this line, the build system will build firefox instead. other build configuration options can be added to this file, although it's strongly recommended that you only use options that yo...
...ning when building thunderbird (deprecated) note: the lightning calendar add-on was integrated into thunderbird starting with version 74. the `--enable-calendar` option is now deprecated and no longer has any effect. if it is in your `mozconfig` file, you should go ahead and remove it when building thunderbird 74 or later, since support for it will eventually be removed completely. add the following line to your mozconfig file: ac_add_options --enable-calendar to add that line you can do this in the source/ directory: echo 'ac_add_options --enable-calendar' >> mozconfig building before you start, make sure that the version you checked out is not busted. for hg tip, you should see green bs on https://treeherder.mozilla.org/#/jobs?repo=comm-central to start the build, cd into the so...
...And 2 more matches
Commenting IDL for better documentation
de. the documentation team has tools that convert comments from the doxygen format into the standard reference article format we use here on mdn, with certain limitations. this article will help you understand how you can format your comments to help ensure that the conversion process can be automated as much as possible in order to ensure that your interface gets properly documented. ...
...operly documented. happily, following these recommendations will also help ensure your comments are extremely human-readable, too. don't worry! ...
...y to search and read documentation. but by following the guidelines here, you can help make sure that our tools can generate a "good start" version of the documentation for your interfaces, and that the writers will be able to easily figure out what the tools are not able to do automatically. comment format doxygen supports several comment formats; for style and consistency reasons, we use the following: /** * */ note the two asterisks ("**") on the first line of the comment. that lets doxygen (and by extension, our automated documentation import tools) know that the comment should be absorbed into documentation. if you use any other format for your comments, our tools will ignore them. ...
...And 2 more matches
SVG Guidelines
the gradients and filters takes place on the authors computer before the result is stored in the raster file. this work doesn't need to be redone when the image is displayed on someone else's computer. on the other hand, if the image is saved as an svg image then all this work needs to be done each time the svg is displayed on someone else's computer. this isn't to say that svg images are always slower than raster equivalents. in fact it can be faster to send vector information from an svg to a user's gpu than it is to extract raster data from an equivalent raster image. and even when an svg image is slower than a raster equivalent, the difference is usually not noticable. however, just don't fall into the trap of thinking that svgs are faster than eqivalent raster images, or vice versa. once...
...is slower than a raster equivalent, the difference is usually not noticable. however, just don't fall into the trap of thinking that svgs are faster than eqivalent raster images, or vice versa. once again, "it depends". authoring guidelines a lot of svg files (particularly those generated by svg editors) ship without being cleaned up and can contain a ton of junk that bloats the file size and slows down rendering. in general the best way to combat this is to first run svg files through a linter such as svgo (see the tools section below). however, when authoring svgs by hand here are some best practices to help keep them lightweight. these rules are based on some real examples seen in mozilla's code. ...
...size and slows down rendering. in general the best way to combat this is to first run svg files through a linter such as svgo (see the tools section below). however, when authoring svgs by hand here are some best practices to help keep them lightweight. these rules are based on some real examples seen in mozilla's code. ...
...And 2 more matches
Embedding the editor
y 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 the editor frame. xbl creates an nseditorboxobject for each <editor> tag, and allows javascript to access properties of this box object (such as the nsieditorshell). the <editor> tag is simply a <iframe> on which an editor is created; in all other respects, it behaves like a xul <iframe>. the problem with this ownership model is that there can be only one editor per <editor> tag, yet the document loaded in the <iframe> may itself contain multiple <iframe>s (consider a frameset d...
...e true editor via window.editorshell. this assumption was short-sighted, and must be fixed. editor assumes xul document structure there is c++ and js code in the editor that assumes that the editor is living in a xul document, and that there are xul document nodes out there whose attributes can be tweaked to change the state of the ui (e.g. the inline style buttons). this needs to be changed to allow embedders to provide their own, possibly native ui. editor needs to call through one or more interfaces when communicating with the ui. embedding objectives editor requires design changes such that the embedding applications above can be fulfilled, and these changes will need to address the current problems. briefly, the embedding objectives are: <editor> should get you a working editor in a x...
...ill need to address the current problems. briefly, the embedding objectives are: <editor> should get you a working editor in a xul application should be able to have multiple <editor>s per xul window should be able to embed an editable content frame in a native application embedders should be able to supply their own chrome (toolbars etc). meeting these objectives will also solve the following existing composer problems: composer should handle frameset documents composer should handle documents with <iframe>s. composer shouldn't rely on certain xul document structure proposed solutions fixing editor rooting as described above, editor rooting needs to be changed so that an editor lives on top of an nsdocshell, rather than hanging off the nseditorboxobject. there is a docshell...
...And 2 more matches
Gecko Keypress Event
d)), then the properties of the event are the same as they were in gecko1.8.1. that is, when the currently selected keyboard layout produces a unicode character (according to the current state of capslock and numlock), the charcode property contains that character. when the keypress event includes modifier keys, sometimes the charcode value is replaced with an ascii character according to the following rules. the accel key depends on the platform. ctrl is the accel key on windows and linux, while meta (i.e. command) is the accel key on mac. when the accel key is down, the charcode of a keypress event may be replaced with a character from a latin keyboard layout only when the original character is not an ascii character. this behavior helps the internationalization of web applications that...
... replace the charcode with an ascii character, the web application developers would need to consider all non-latin keyboard layouts (arabic, greek, hebrew, russian, etc.). the charcode value depends on the state of capslock and numlock (except they are currently ignored if alt (option) is down on mac - see bug 432953). there are also some differences between the platforms, as described in the following sections. windows the charcode is replaced only when ctrl is down but alt is not down. if the os-provided character cannot be entered without using the ctrl key, then, gecko does not replace the character. e.g., ctrl+shift+'2' on persian keyboard 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 zw...
...r users to distinguish between accesskeys using two different characters on the same key (when the shift modifier is usually used to select one of the characters). the pairs of characters that might be on the same key depend on the keyboard layout. (bug 359638 partially addressed this issue by trying both characters on the key, but bug 303192 would provide a complete solution.) solution the following rules apply: key handlers should be provided with information about all the possible meanings of the event. a handler on the innermost element should handle a key event even when the event does not match exactly and there is an outer element with a handler that does match exactly (bug 433192). when handling web content accesskeys, the handlers should consider both characters that are avai...
...And 2 more matches
How to get a stacktrace with WinDbg
t a stacktrace (call stack) for a crash or hang but breakpad fails because it's a special crasher or a hang. this article describes how to get a stacktrace in those cases with windbg on windows. (to get a stacktrace for thunderbird or some other product, substitute the product name where ever you see firefox in this instructions.) requirements to get such a stacktrace you need to install the following software: debugging tools for windows microsoft distributes the debugging tools for windows for free, those include windbg which you will need here. download it from install debugging tools for windows. (you'll want the 32-bit version, even if you are using a 64-bit version of windows) then install it, the standard settings in the installation process are fine. a firefox nightly or release ...
...r (|), which is required. (the keystroke for a pipe character on us keyboards is shift+\) submit the log file on a bug or via the support site, even if nothing seems to happen during the debug process start debugging now that firefox is opened in the debugger, you need to configure your windbg to download symbols from the mozilla symbol server. to load the symbols, enter the three commands below, pressing enter after each one. (more details are available at using the mozilla symbol server.) .sympath srv*c:\symbols*http://symbols.mozilla.org/firefox;srv*c:\symbols*http://msdl.microsoft.com/download/symbols .symfix+ c:\symbols .reload /f now wait for the symbols to download. this may take some time depending on your connection speed; the total size of the mozilla and microsoft symbols d...
... and need to close the running instance first before you start debugging, otherwise you won't get useful results. now run firefox by opening the debug menu and clicking go. while firefox is running, you will not be able to type any commands into the debugger. after it starts, try to reproduce the crash or hanging issue that you are seeing. if firefox fails to start, and you see lines of text followed by a command prompt in the debugger, a "breakpoint" may have been triggered. if you are prompted for a command but don't see an error about a crash, go back to the debug menu and press go. once the browser crashes, you will see an error (such as "access violation") in the windbg command window. if firefox hangs and there is no command prompt available in the debugger, open the debug menu and c...
...And 2 more matches
Widget Wrappers
id the widget's id type the type of widget (button, view, custom). for xul-provided widgets, this is always 'custom' provider the provider type of the widget, id est one of provider_api or provider_xul node reference to the corresponding dom node anchor the anchor on which to anchor panels opened from this node. ...
...get's id type the type of widget (button, view, custom). for xul-provided widgets, this is always 'custom' provider the provider type of the widget, id est one of provider_api or provider_xul node reference to the corresponding dom node anchor the anchor on which to anchor panels opened from this node. ...
...w, custom). for xul-provided widgets, this is always 'custom' provider the provider type of the widget, id est one of provider_api or provider_xul node reference to the corresponding dom node anchor the anchor on which to anchor panels opened from this node. ...
...And 2 more matches
FileUtils.jsm
need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/fileutils.jsm"); the file constructor if you have a path to a file (or directory) you want to obtain an nsifile for, you can do so using the file constructor, like this: var f = new fileutils.file(mypath); method overview nsifile getfile(string key, array patharray, bool followlinks); nsifile getdir(string key, array patharray, bool shouldcreate, bool followlinks); nsifileoutputstream openfileoutputstream(nsifile file, int modeflags); nsifileoutputstream openatomicfileoutputstream(nsifile file, int modeflags); nsifileoutputstream opensafefileoutputstream(nsifile file, int modeflags); void closeatomicfileoutputstream(nsifileou...
... mode_truncate 0x20 corresponds to the pr_truncate parameter to pr_open perms_file 0644 default permissions when creating files. perms_directory 0755 default permissions when creating directories methods getfile() gets a file at the specified hierarchy under a nsidirectoryservice key. nsifile getfile( string key, array patharray, bool followlinks ); parameters key the nsidirectoryservice key to start from (see getting special files for more info) patharray an array of path components to locate beneath the directory specified by key. the last item in this array must be the leaf name of a file. followlinks optional true if links should be followed, false otherwise. return value returns a nsifile object for the file specifi...
...wlinks optional true if links should be followed, false otherwise. return value returns a nsifile object for the file specified. the file is not created if it does not exist, however all required directories along the way are. getdir() gets a directory at the specified hierarchy under a nsidirectoryservice key. nsifile getdir( string key, array patharray, bool shouldcreate, bool followlinks ); parameters key the nsidirectoryservice key to start from (see getting special files for more info) patharray an array of path components to locate beneath the directory specified by key. shouldcreate optional true if the directory hierarchy specified in patharray should be created if it does not exist, false otherwise. ...
...And 2 more matches
PopupNotifications.jsm
ll be anchored to the popupnotification object's icon box. this anchorid must point to an element contained inside the popupnotification object's icon box (for firefox windows, the global popupnotifications object uses the notification-popup-box element). mainaction a javascript object literal containing fields that define the button to draw in the notification panel. see notification actions below for details. secondaryactions an array of notification action objects; these are used to populate the drop-down menu on the notification panel's button. options a javascript object containing optional properties for the notification. see notification options below for details. return value returns the notification object corresponding to the added notification. notification actions notif...
...tion object corresponding to the added notification. notification actions notification action objects describe the user interface for actions associated with the notification. the main action is used to describe the button presented in the notification panel, while secondary actions are displayed in the drop-down menu associated with the button. ...
...ion action object must contain the following properties: label a text label describing the action. accesskey a string indicating the keystroke that will trigger the action. callback a javascript function to be invoked when the action is selected by the user. notification options the notification options object lets you further customize the notification panel. any combination of the following properties may be provided: persistence an integer value indicating the number of page loads for which the notification will persist; once this many page loads have occurred, the notification may dismiss automatically. timeout a timestamp (milliseconds since the epoch) indicating the earliest time after which the notification can be automatically dismissed. notifications that specify a t...
...And 2 more matches
SourceMap.jsm
cemap); sourcemapconsumer a sourcemapconsumer instance represents a parsed source map which we can query for information about the original file positions by giving it a file position in the generated source. new sourcemapconsumer(rawsourcemap) the only parameter is the raw source map (either as a string which can be json.parse'd, or an object). according to the spec, source maps have the following attributes: version: which version of the source map spec this map is following. sources: an array of urls to the original source files. names: an array of identifiers that can be referenced by individual mappings. sourceroot: optional. the url root from which all sources are relative. mappings: a string of base64 vlqs which contain the actual mappings. file...
...ces are relative. mappings: a string of base64 vlqs which contain the actual mappings. file: the generated filename this source map is associated with. sourcemapconsumer.prototype.originalpositionfor(generatedposition) returns the original source, line, and column information for the generated source's line and column positions provided. the only argument is an object with the following properties: line: the line number in the generated source. column: the column number in the generated source. and an object is returned with the following properties: source: the original source file, or null if this information is not available. line: the line number in the original source, or null if this information is not available. column: the column numb...
...olumn: the column number in the original source, or null if this information is not available. name: the original identifier, or null if this information is not available. sourcemapgenerator an instance of the sourcemapgenerator represents a source map which is being built incrementally. new sourcemapgenerator(startofsourcemap) to create a new one, you must pass an object with the following properties: file: the filename of the generated source that this source map is associated with. sourceroot: an optional root for all relative urls in this source map. sourcemapgenerator.prototype.addmapping(mapping) add a single mapping from original source line and column to the generated source's line and column for this source map being created. the mapping object should ha...
...And 2 more matches
WebRequest.jsm
sses. the webrequest api is modeled on chrome's webrequest extension api, which makes it easier to write cross-browser add-on code. there are some differences between this api and chrome's, though: see chrome incompatibilities for the details. usage to import webrequest, use code like: let {webrequest} = cu.import("resource://gre/modules/webrequest.jsm", {}); the webrequest object has the following properties, each of which corresponds to a specific stage in executing a web request: onbeforerequest onbeforesendheaders onsendheaders onheadersreceived onresponsestarted oncompleted each of these objects defines two functions: addlistener(callback, filter, opt_extrainfospec) removelistener(callback) adding listeners use addlistener to add a listener to a particular event. it...
...ng a web request: onbeforerequest onbeforesendheaders onsendheaders onheadersreceived onresponsestarted oncompleted each of these objects defines two functions: addlistener(callback, filter, opt_extrainfospec) removelistener(callback) adding listeners use addlistener to add a listener to a particular event. it takes one mandatory argument and two optional arguments, as detailed below. name type description callback function the callback argument is a function to be called when the event is triggered. it's passed an object whose structure will vary depending on the event you're listening to: see the event-specific documentation for details. filter object the optional filter argument is used to restrict the request...
...e listener that contains instructions for what the browser should do with this request. there are four things you can do with a request: cancel it redirect it modify request headers modify response headers. to perform one of these operations, include a property with the appropriate name in the object returned from the listener, and assign it the desired value, as detailed in the table below: operation available in return property cancel onbeforerequest cancel boolean value set to true. see some examples of canceling requests. redirect onbeforesendheaders redirecturl string set to the url to redirect the request to. see some examples of redirection. modify request headers onbeforesendheaders ...
...And 2 more matches
Localizing with Koala
eases/mozilla-1.9.2. branch: default. revision: leave empty. click "ok". koala will now try to clone the en-us source repository from http://hg.mozilla.org/releases/mozilla-1.9.2. it's almost 1 gb worth of download, so it may take a while. click "ok". on windows, if koala doesn't clone the repositories, you'll need to do it manually. ...
...rial" checkbox (e.g. "c:\mozilla\l10n\locale\x-testing\3.6" if you enabled mercurial (recommended), koala will ask you if you wish to clone the remote repository. click "ok" (even if you're creating a new localization and there is no remote repository). existing localizations: if koala fails to clone the remote repository, you will need to do it manually. just open the console and issue the following commands: c:\users\stas> cd c:\mozilla\l10n\locale\x-testing c:\mozilla\l10n\locale\x-testing> rmdir 3.6 c:\mozilla\l10n\locale\x-testing> hg clone http://hg.mozilla.org/releases/l10n-mozilla-1.9.2/x-testing 3.6 new localizations: if you have the bitbucket repository already set up by l10n-drivers, the steps are the same as above. just hg clone from the right bitbucket url. for example: c:\u...
...o see what is left to be translated. to make sure you're always translating the most recent en-us reference, you should update the source repository before you start working. open koala's start page. in "last used compares" click "update repo" to update the en-us repository to the most recent version. or, you can select firefox (3.6), en-us (included) and x-testing (3.6) in the "open" section below, and click "update repos" on the right. koala will re-run the comparison of your local localization files with the newest en-us reference and display the results in the sidebar on the left. filter the files list in the sidebar to only display files containing "search" in their name. you'll see that search.properties is now marked as "modified" (before it was "added) and the entity counts have cha...
...And 2 more matches
Localization technical reviews
this guide provides details on what a localization technical review is, what criteria are used for the technical reviews, and the process for requesting one and following its progress. the technical review process we use for new localizations can be confusing for any trying to start a new localization. we use 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. ...
...for any trying to start a new localization. we use 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 effectivel...
...ox no longer has a utf-7 parser. there should not be any utf-7 encodings in the file toolkit/chrome/global/intl.properties. for more info about utf-7 in firefox, see bug 441876. ...
...And 2 more matches
Basics
you can right-click on any math fragment of interest throughout this document. ...
... d y d x = 1 y 2 , form rather complicated expressions lim n → n ( 1 + 1 n ) n − e n , k = ∂ 2 z ∂ x 2 ∂ 2 z ∂ y 2 - ( ∂ 2 z ∂ x ∂ y ) 2 ( 1 + ( ∂ z ∂ x ) 2 + ( ∂ z ∂ y ) 2 ) 2 , write vector equations y = a ⁢ x + b , etc. ...
...n − e n , k = ∂ 2 z ∂ x 2 ∂ 2 z ∂ y 2 - ( ∂ 2 z ∂ x ∂ y ) 2 ( 1 + ( ∂ z ∂ x ) 2 + ( ∂ z ∂ y ) 2 ) 2 , write vector equations y = a ⁢ x + b , etc. notice how the mathematics appear in the main flow of text and respond as you resize the window. ...
...And 2 more matches
Mozilla Web Developer FAQ
...
... correct type is text/css. in the standards mode and the almost standards mode only style sheets with the correct type are applied. you can see the http headers sent by the server by using the livehttpheaders extension or by using the web sniffer. class names and ids are case-sensitive. the element selectors are case-sensitive with xml. style sheet processing instructions are only allowed in the prolog of xml documents. also, they only work in xml documents—not in documents served as text/html. width and height do not apply to non-replaced inline elements such as (by default) <span>. text-align: center; centers inline content within a block. it does not (and should not) center the block box itself. a block is centered by setting its margin-left and margin-right to auto and i...
...ng as the argument. also, old client sniffers can shut out new browsers. the point of having a common api (the w3c dom) is interoperability, and checking for a particular 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 disp...
...And 2 more matches
Memory reporting
etimes a unitless count or percentage); a description of what is measured. see the nsimemoryreporter documentation and nsimemoryreporter.idl for full details. making measurements nsimemoryreporter provides the high-level interface for a memory reporter, but the heart of a memory reporter is the measurement of the "amount". two ways to measure memory reporters can be divided into the two following kinds. traversal-based reporters traverse one or more data structures and measure the size of all the allocated blocks in the data structure. counter-based reporters maintain a counter that is incremented on each relevant allocation and decremented on each relevant deallocation. traversal-based reporters are preferable, for the following reasons. they are less error-prone. we've had m...
...decremented on each relevant deallocation. traversal-based reporters are preferable, for the following reasons. they are less error-prone. we've had multiple bugs in the past with counter-based reporters. the cost of reporting isn't incurred unless the memory reporter is queried. they provide more information to dmd, which is a tool that helps keep about:memory's "heap-unclassified" number low. see below for more details. sometimes counter-based reporters are unavoidable, particularly when writing memory reporters for third-party code that cannot be modified. a simple example imagine a simple string class with the following data fields: class mystring { private: char *mbuffer; // heap-allocated size_t mlen; // ... methods ... } here are what the measurement functi...
...llocsizeof) const { return amallocsizeof(mbuffer); } size_t mystring::sizeofincludingthis(mozilla::mallocsizeof amallocsizeof) const { return amallocsizeof(this) + sizeofexcludingthis(amallocsizeof); } (note that sizeofexcludingthis and sizeofincludingthis aren't overrides of methods on a global base class that is common to all reporters. these names are just a convention that is commonly followed. that said, note that for some classes these methods may be virtual.) mfbt/memoryreporting.h defines mozilla::mallocsizeof as follows: typedef size_t (*mallocsizeof)(const void* p); functions with this signature measure the size of p by asking the heap allocator how big it is (via moz_malloc_usable_size). all this is probably not what you'd expect, but the above functions have the follo...
...And 2 more matches
tools/power/rapl
e machine-wide estimates, so if you want to estimate the power consumption of a single program you should minimize other activity on the machine while measuring. 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. invocation first, do a standard build of firefox. mac on mac, rapl can be run as follows. $objdir/dist/bin/rapl linux on linux, rapl can be run as root, as follows. sudo $objdir/dist/bin/rapl alternatively, it can be run without root privileges by setting the contents of /proc/sys/kernel/perf_event_paranoid to 0. note that if you do change this file, its contents may reset when the machine is next rebooted. you must be running linux kernel version 3.14 or later for rapl to wor...
...f_event_paranoid to 0. note that if you do change this file, its contents may reset when the machine is next rebooted. you must be running linux kernel version 3.14 or later for rapl to work. otherwise, it will fail with an error message explaining this requirement. windows unfortunately, rapl does not work on windows, and porting it would be difficult because windows does not have apis that allow easy access to the relevant model-specific registers. output the following is 10 seconds of output from a default invocation of rapl. total w = _pkg_ (cores + _gpu_ + other) + _ram_ w #01 5.17 w = 1.78 ( 0.12 + 0.10 + 1.56) + 3.39 w #02 9.43 w = 5.44 ( 1.44 + 1.20 + 2.80) + 3.98 w #03 14.26 w = 10.21 ( 5.47 + 0.19 + 4.55) + 4.04 w #04 10.02 w = 6.15 ( 2.62 + 0.43 + 3.10) + ...
... 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 pow...
...And 2 more matches
About NSPR
2.0" but rather "second 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 behavi...
...d 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 notification capabilities with the ability to associate the synchronization objects dynamically. i/o nspr's i/o is a slightly augmented bsd sockets model that allows arbitrary layering. it was originally intended to export synchronous i/o methods only, relying on threads to provide the concurrency needed for complex applications. that method of operation is preferred though it is possible to configure the network i/o channels as non-blocking in the traditional sense. network addresses part of nspr deals with manipulation of network addresses. nspr defines ...
... for complex applications. that method of operation is preferred though it is possible to configure the network i/o channels as non-blocking in the traditional sense. network addresses part of nspr deals with manipulation of network addresses. nspr defines a network address object that is internet protocol (ip) centric. while the object is not declared as opaque, the api provides methods that allow and encourage clients to treat the addresses as polymorphic items. the goal in this area is to provide a migration path between ipv4 and ipv6. to that end it is possible to perform translations of ascii strings (dns names) into nspr's network address structures, with no regard to whether the addressing technology is ipv4 or ipv6. time timing facilities are available in two forms: interval timin...
...And 2 more matches
NSPR Poll Method
y provides a reference implementation of the bottom layer using the sockets api, but you can provide your own implementation of the bottom layer using another network transport api. the poll method is one of the functions in the priomethods table. the prototype of the poll method is print16 poll_method(prfiledesc *fd, print16 in_flags, print16 *out_flags); the purpose of the poll method is to allow a layer to modify that flags that will ultimately be used in the call to the underlying network transport's select (or equivalent) function, and to indicate that a layer is already able to make progress in the manner suggested by the polling flags. the arguments and return value of the poll method are described below. in_flags [input argument] the in_flags argument specifies the events at the ...
...out 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 section below. ...
...those are the events that the caller should poll the underlying network transport for. these events may be different from the events in in_flags (which reflect the caller's view) for some protocols. ...
...And 2 more matches
NSS Key Log Format
(pre)-master-secret log filename. key logging is enabled by setting the environment variable sslkeylogfile to point to a file. note: starting with nss 3.24 (used by firefox 48 and 49 only), the sslkeylogfile approach is disabled by default for optimized builds using the makefile (those using gyp via build.sh are not affected). ...
...yp via build.sh are not affected). distributors can re-enable it at compile time though (using the nss_allow_sslkeylogfile=1 make variable) which is done for the official firefox binaries. (see bug 1188657.) notably, debian does not have this option enabled, see debian bug 842292. this key log file is a series of lines. comment lines begin with a sharp character ('#') and are ignored. secrets follow the format <label> <space> <clientrandom> <space> <secret> where: <label> describes the following secret. <clientrandom> is 32 bytes random value from the client hello message, encoded as 64 hexadecimal characters. <secret> depends on the label (see below). ...
...2292. this key log file is a series of lines. comment lines begin with a sharp character ('#') and are ignored. secrets follow the format <label> <space> <clientrandom> <space> <secret> where: <label> describes the following secret. <clientrandom> is 32 bytes random value from the client hello message, encoded as 64 hexadecimal characters. <secret> depends on the label (see below). ...
...And 2 more matches
NSS 3.19.2.1 release notes
introduction network security services (nss) 3.19.2.1 is a patch release for nss 3.19.2. the bug fixes in nss 3.19.2.1 are described in the "security advisories" section below. distribution information the hg tag is nss_3_19_2_1_rtm. nss 3.19.2.1 requires nspr 4.10.10 or newer. nss 3.19.2.1 and nspr 4.10.10 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_2_1_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.19.2.1. users are encouraged to upgrade immediately. bug 1192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within ...
...ers 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. ...
...1) 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. ...
...And 2 more matches
NSS 3.19.4 release notes
introduction network security services (nss) 3.19.4 is a patch release for nss 3.19. the bug fixes in nss 3.19.4 are described in the "security advisories" section below. distribution information the hg tag is nss_3_19_4_rtm. nss 3.19.4 requires nspr 4.10.10 or newer. nss 3.19.4 and nspr 4.10.10 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_4_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.19.4. users are encouraged to upgrade immediately. bug 1192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within the asn.1 decode...
...ers 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. ...
...1) 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. ...
...And 2 more matches
NSS 3.20.1 release notes
introduction network security services (nss) 3.20.1 is a patch release for nss 3.20. the bug fixes in nss 3.20.1 are described in the "security advisories" section below. distribution information the hg tag is nss_3_20_1_rtm. nss 3.20.1 requires nspr 4.10.10 or newer. nss 3.20.1 and nspr 4.10.10 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_20_1_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.20.1. users are encouraged to upgrade immediately. bug 1192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within the asn.1 decode...
...ers 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. ...
...1) 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. ...
...And 2 more matches
NSS 3.25 release notes
introduction the network security services (nss) team has released nss 3.25, which is a minor release. 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. ...
... several functions have been added to the public api of the nss cryptoki framework. ...
...h algorithm as the prf when using tls 1.2 client authentication. several functions have been added to the public api of the nss cryptoki framework. ...
...And 2 more matches
NSS sources building testing
hat combines both nss and nspr. if you are a software developer and intend to contribute enhancements to nss, you should obtain the latest development snapshot of nss using mercurial/hg (a distributed source control management tool). in order to get started, anonymous read-only access is sufficient. create a new directory on your computer that you will use as your local work area, and run the following commands. hg clone https://hg.mozilla.org/projects/nspr hg clone https://hg.mozilla.org/projects/nss after the above commands complete, you should have two local directories, named nspr and nss, next to each other. (historical information: nspr and nss source code have recently been re-organized into a new directory structure. in past versions, all files were located in a directory hierarch...
...ion: nspr and nss source code have recently been re-organized into a new directory structure. in past versions, all files were located in a directory hierarchy that started with the "mozilla" prefix. the nspr base library was located in directory mozilla/nsprpub. the subdirectories dbm, security/dbm, security/coreconf, security/nss were part of the nss sources.) the nss directory contains the following important subdirectories: nss/coreconf contains knowledge for cross platform building. nss/lib contains all the library code that is used to create the runtime libraries used by applications. nss/cmd contains a set of various tool programs that are built using nss. several tools are general purpose and can be used to inspect and manipulate the storage files that software using the n...
...n the difference between internal nss code and exported interfaces. software that would like to use the nss library must use only the exported interfaces. these can be found by looking at the files with the .def file extension, inside the nss/lib directory hierarchy. ...
...And 2 more matches
nss tech note3
all about certificate extensions nss technical note: 3 09 may 2002 nelson b. bolyard this week at least 5 different people came to me with variants of the same question: what certificate extensions do i have to put into my cert for nss to allow it to be used for purpose <x>?? this message attempts to answer that question, and to document nss's approach to validating certificates for certain purposes. when nss is asked to verify the validity of a certificate chain, it verifies the validity of that cert chain for a particular purpose, known as a seccertusage, as of a specific date and time. the list of known seccertusages is short: certusagesslclient ........... an ssl client authentication cert certusagesslserver ........... an ordinary ssl server cert certusagesslserverwith...
... to verify the validity of a certificate chain, it verifies the validity of that cert chain for a particular purpose, known as a seccertusage, as of a specific date and time. the list of known seccertusages is short: certusagesslclient ........... an ssl client authentication cert certusagesslserver ........... an ordinary ssl server cert certusagesslserverwithstepup.. an ssl server cert that allows export clients to use strong crypto. certusagesslca ............... an intermediate or root ca cert allowed to issue ssl client or ssl server certs or other intermediate ssl ca certs. certusageemailsigner ......... used to verify s/mime email signatures certusageemailrecipient ...... used to encrypt s/mime emails. certusageobjectsigner ........ used to verify signatures on files of ...
... tells nss whether the cert is a ca cert, or not, and affects every other aspect of how the cert is interpreted by nss. the oid for this extension is { 2 5 29 19 }, encoded in hex as 0x55, 0x1d, 0x13. if the extension is present and has the value true, then this cert is taken to be a ca cert. otherwise it is not (except that trust flags may override this, see discussion of trust flags farther below). netscape has its own openly defined cert type extension, which can be used to explicitly set the cert type in any cert. the cert type extension has bits in it that correspond 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, ...
...And 2 more matches
ssltyp.html
es. syntax #include <certt.h> typedef struct certcertdbhandlestr certcertdbhandle; certcertificate an opaque x.509 certificate object. syntax #include <certt.h> typedef struct certcertificatestr certcertificate; description certificate structures are shared objects. when an application makes a copy of a particular certificate structure that already exists in memory, ssl makes a shallow copy--that is, it increments the reference count for that object rather than making a whole new copy. when you call cert_destroycertificate, the function decrements the reference count and, if the reference count reaches zero as a result, frees the memory. the use of the word "destroy" in function names or in the description of a function often implies reference counting. never alter the content...
... whole new copy. when you call cert_destroycertificate, the function decrements the reference count and, if the reference count reaches zero as a result, frees the memory. the use of the word "destroy" in function names or in the description of a function often implies reference counting. never alter the contents of a certificate structure. if you attempt to do so, the change affects all the shallow copies of that structure and can cause severe problems. pk11slotinfo an opaque structure representing a physical or logical pkcs #11 slot. syntax #include <pk11expt.h> typedef struct pk11slotinfostr pk11slotinfo; secitem a structure that points to other structures. syntax #include <seccomon.h> #include <prtypes.h> #include <secport.h> typedef enum { sibuffer, sicleardatab...
... call seckey_destroyprivatekey, the function both frees the memory and sets all the bits to zero. never alter the contents of a key structure. treat the structure as read only. secstatus the return value for many ssl functions. syntax #include <seccomon.h> typedef enum { secwouldblock = -2, secfailure = -1, secsuccess = 0 } secstatus; enumerators the enum includes the following enumerators: secwouldblock reserved for internal use. secfailure the operation failed. to find out why, call pr_geterror. secsuccess the operation succeeded. in this case the value returned by pr_geterror is meaningless. ...
...And 2 more matches
Rhino scopes and contexts
before using rhino in a concurrent environment, it is important to understand the distinction between contexts and scopes. both are required to execute scripts, but they play different roles. simple embeddings of rhino probably won't need any of the information here, but more complicated embeddings can gain performance and flexibility from the techniques described below. contexts the rhino context object is used to store thread-specific information about the execution environment. there should be one and only one context associated with each thread that will be executing javascript. to associate the current thread with a context, simply call the enter method of context: context cx = context.enter(); once you are done with execution, simply exit the context: context.exit(); th...
...any accesses to shared variables. a top-level scope is created by calling context.initstandardobjects to create all the standard objects: scriptableobject scope = cx.initstandardobjects(); the easiest way to embed rhino is just to create a new scope this way whenever you need one. however, initstandardobjects is an expensive method to call and it allocates a fair amount of memory. ...
...l see below that there are ways to share a scope created this way among multiple scopes and threads. name lookup so how are scopes used to look up names? in general, variables are looked up by starting at the current variable object (which is different depending on what code is being executed in the program), traversing its prototype chain, and then traversing the parent chain. in the diagram below, the order in which the six objects are traversed is indicated. order of lookups in a two-deep scope chain with prototypes. for a more concrete example, let's consider the following script: var g = 7; function f(a) { var v = 8; x = v + a; } f(6); we have a top-level variable g, and the call to f will create a new top-level variable x. all top-level variables are properties of the sco...
...And 2 more matches
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. so far, so good. ...
...idermonkey 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. so far, so good. now for the tricky parts. we need to perform a recursive find and replace text operation on all files in the current directory. in the unix world we would issue the following command: find ./ -type f -exec sed -i "s/mozjs185/$brand/" {} \; windows users: notepad++ can be used to perform the recursive find and replace text operation. if you have failed to insert your brand name in any of the previous steps where it is called for, you must delete this build directory and restart this process from the beginning. this time paying careful attention to the commands you ...
...install:: $(pkg_config_files) @echo pkg_config_file: $(pkg_config_files) those two lines should be modified to read back: install:: $brand.pc @echo pkg_config_file: $brand.pc note: while it is possible to automate the manual editing process, this has been discouraged due to the fact that these files are automatically generated and very little constant data can be depended upon. ...
...And 2 more matches
Creating JavaScript jstest reftests
are run by the jstest harness in the shell and the reftest harness in the browser. this directory contains tests of spidermonkey conformance to ecmascript as well as spidermonkey non-standard extenstions to ecmascript. directory overview in the js/src/tests directory, there are a few important subdirectories. ...
...ubdirectories. non262 tests the directory js/src/tests/non262/ should contain all tests of the following type: regressions of spidermonkey non-standard spidermonkey extensions to the javascript language test of "implementation-defined" details of the ecmascript standard for example, the exact definition of pi or some details of array sorting. you should not add tests of the following type: tests of the jit test of jit correctness belong in the jit-test suite, read more here. 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 intern...
...62 is the implementation conformance test suite for the latest drafts of ecmascript language specification, as well as internationalization api specification and the json data interchange format. it is maintained by tc39, the ecmascript standard's technical committee. mozilla manually imports these tests into the js/src/tests/test262 directory. you should contribute directly to test262 in the following scenarios: you are writing tests for the implementation of a new feature or feature proposal for ecmascript. if tests for the new feature proposal do not yet exist in test262 (they might!), contributing to test262 will allow all other javascript implementors to use your tests as well. you would like to contribute tests of an ecmascript, intl or json feature insufficiently cover...
...And 2 more matches
Exact Stack Rooting
edscript, etc. because of the lifo restriction, using this interface manually is extremely cumbersome. instead, spidermonkey has a convenient suite of c++ raii classes to do this for you, called js::rootedt: rootedstring str1(cx, js_valuetostring(cx, val)); rootedstring str2(rt, js_valuetostring(cx, val)); note 1: c++ insists that an initializing assignment (e.g., the default constructor followed by operator=) must have a copy constructor available, even if it is not used. since it is never correct to implicitly copy a js::rootedt (more on this in a second) we have deleted the copy constructor from these classes. therefore, we are forced to force you to initialize with constructor syntax. sorry. note 2: in c++, destructors are required to run in declaration order, nicely maintaining o...
...o compile. warning: js::handlet does not root objects itself! that is the job of js::rootedt. warning: never give a function a js::handlet return type: this can easily lead to a js::handlet outliving its js::rootedt's lifetime. js::mutablehandle<t> typedef js::mutablehandle<t> js::mutablehandlet; -> mutablehandleobject, mutablehandlestring, etc. the purpose of js::mutablehandlet is to allow out-parameters for rooted gcthings. this class solves two problems: c++ only allows one level of user-defined implicit type conversion. when passed to an out-param, &handle would convert correctly to js::handlet*, but &local is a compile error. even though js::handlet is indirect, it implicitly behaves like the thing it is pointing to. this makes js::handlet and js::rootedt behave the same, a...
...the problem is that this requires us to overload operator->. if we have a method taking handle<value>*, then out->setobject(foo) will not work as expected. to solve these problems we have the js::mutablehandlet class. ...
...And 2 more matches
Tracing JIT
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. ...
... 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 tracing jit follows: generic low level component: nanojit/* the files in the nanojit directory define the nanojit component. nanojit/lir.* the nanojit/lir.cpp and nanojit/lir.h files define the intermediate representation lir, which is used as input to nanojit. lir is a conventional three-address, linear ssa code. a single instruction of lir is called a lins, short for "lir instruction". lins values are depi...
... nanojit/assembler.h files define the class assembler, which transforms lins values into nins values. in other words, an assembler transforms lir code into native code. an assembler is also able to modify existing fragments of native code, by rewriting native jump instructions to jump to new locations. in this way the assembler can "patch together" multiple fragments, so 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...
...And 2 more matches
JS_GetLocaleCallbacks
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. callbacks jslocalecallbacks * pointer to a jslocalecallbacks struct. ...
...x 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. callbacks jslocalecallbacks * pointer to a jslocalecallbacks struct. ...
... callback functions struct jslocalecallbacks { jslocaletouppercase localetouppercase; jslocaletolowercase localetolowercase; jslocalecompare localecompare; // not used #if expose_intl_api jslocaletounicode localetounicode; }; typedef bool (* jslocaletouppercase)(jscontext *cx, js::handlestring src, js::mutablehandlevalue rval); typedef bool (* jslocaletolowercase)(jscontext *cx, js::handlestring src, js::mutablehandlevalue rval); typedef bool (* jslocalecompare)(jscontext *cx, js::handlestring src1, js::handlestring src2, js::mutablehandlevalue rval); typedef bool (* jslocaletounicode)(jscontext *cx, const char *src, js::mutablehandlevalue rval); type description jslocaletouppercase implementation of st...
...And 2 more matches
JS_SetOptions
at any time. try to avoid using it. enables and disables options on a jscontext, replacing all previously set options. syntax uint32 js_setoptions(jscontext *cx, uint32 options); name type description cx jscontext * a context on which to set options. options uint32 the new set of options. this is the logical or of zero or more flags described below. description js_setoptions sets the option flags of a given js context cx. this function returns a uint32 value containing the previous values of the flags. to turn individual options on or off, use js_setoptions with js_getoptions: // turn on warnings for dubious practices js_setoptions(cx, js_getoptions(cx) | jsoption_extra_warnings); // turn off those extra warnings js_setoptions(cx, js...
...ues of the flags. to turn individual options on or off, use js_setoptions with js_getoptions: // turn on warnings for dubious practices js_setoptions(cx, js_getoptions(cx) | jsoption_extra_warnings); // turn off those extra warnings js_setoptions(cx, js_getoptions(cx) & ~jsoption_extra_warnings); the options parameter and the return value are the logical or of zero or more constants from the following table: option description jsoption_extra_warnings warn on dubious practice. mxr id search for jsoption_extra_warnings jsoption_werror convert warnings to errors. mxr id search for jsoption_werror jsoption_varobjfix make js_evaluatescript() use the last object on its obj param's scope chain...
... //@line number ["filename"] option supported for the xul preprocessor and kindred beasts. mxr id search for jsoption_atline jsoption_xml obsolete since jsapi 15 ecmascript for xml (e4x) support: parse <!-- --> as a token, not backward compatible with the comment-hiding hack used in html script tags. ...
...And 2 more matches
SpiderMonkey 1.8.8
al-link-when-the-release-happens (md5 checksum: insert-actual-hash-here). spidermonkey 1.8.8 is the javascript engine that shipped in firefox 10.0. it continues to improve performance over previous spidermonkey releases, with ongoing jit compilation work and with the introduction of type inference to enable faster jitted code. it also contains new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. —insert-actual-release-date-here platform support spidermonkey 1.8.8 is supported on all the platforms where firefox insert-actual-firefox-version-number-here runs. spidermonkey 1.8.8 inclu...
...mpiles 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 in previous versions. it's the same language, just not as fast. migrating to spidermonkey 1.8.8 the following features in earlier versions of spidermonkey have been dropped. the jsresolve_classname and jsresolve_with resolve flags (passed to jsclass.resolve when jsclass.flags contains jsclass_new_resolve) have been removed. spidermonkey 1.8.8 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types, functions, and callback signatures have changed, though m...
...ications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. here is a list of the most significant changes. a significant number of typedefs of built-in types, or of types which are now standardized, have been removed. these and other changes are explained in detail below. new javascript language features javascript 1.8.8 includes significant updates to language features, yo. typedef changes many types have been removed from the jsapi and replaced with simpler alternatives. including jsapi.h provides all these types, but more-specific headers also provide these types if you wish to use them in other code. obsolete typedef replacement type provided ...
...And 2 more matches
SpiderMonkey 17
la.org/js/mozjs17.0.0.tar.gz (md5 checksum: 20b6f8f1140ef6e47daa3b16965c9202). spidermonkey 17 is the javascript engine that shipped in firefox 17. it continues to improve performance over previous spidermonkey releases, with ongoing jit compilation work and with the introduction of type inference to enable faster jitted code. it also contains new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. — 25 march 2013 platform support spidermonkey 17 is supported on all the platforms where firefox 17 runs. spidermonkey 17 includes a just-in-time compiler (jit) that compiles javascript to ...
... 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 in previous versions. it's the same language, just not as fast. migrating to spidermonkey 17 the following features in earlier versions of spidermonkey have been dropped. the jsresolve_classname and jsresolve_with resolve flags (passed to jsclass.resolve when jsclass.flags contains jsclass_new_resolve) have been removed. spidermonkey 17 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types, functions, and callback signatures have changed, though most...
...ications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. here is a list of the most significant changes. a significant number of typedefs of built-in types, or of types which are now standardized, have been removed. these and other changes are explained in detail below. new javascript language features javascript 17 includes significant updates to language features, yo. typedef changes many types have been removed from the jsapi and replaced with simpler alternatives. including jsapi.h provides all these types, but more-specific headers also provide these types if you wish to use them in other code. obsolete typedef replacement type provided by ...
...And 2 more matches
Querying Places
use nsinavhistoryservice.getnewquery() and nsinavhistoryservice.getnewqueryoptions() to retrieve empty objects. ...
...l history, sorted in database order, // which is nsinavhistoryqueryoptions.sort_by_none. let options = placesutils.history.getnewqueryoptions(); // no query parameters will return everything let query = placesutils.history.getnewquery(); // execute the query let result = placesutils.history.executequery(query, options); result types nsinavhistoryqueryoptions has a resulttype property that allows configuration of the grouping and level of detail to be returned in the results. the different values for this property are listed below. these values are also properties of nsinavhistoryqueryoptions, and are accessed like this: components.interfaces.nsinavhistoryqueryoptions.results_as_visit. results_as_uri: this is the default, and returns one result node of type result_type_uri for each ur...
...lts_as_visit: this option returns one entry for each time a page was visited matching the given query. the result may contain duplicate entries for urls, each with a different date. the nodes are of type result_type_visit, and provide a session id for each visit. this session id is the same for all pages that were reached by clicking links. a new session starts when the user types a new url or follows a bookmark (xxx link to more details about what constitutes a session). results_as_full_visit: this is an extended version of result_type_visit. the results are of type result_type_full_visit and have additional information about the visit, such as the referring visit, and how the transition happened (typed, redirect, link, etc). not yet implemented -- see bug 320831. basic query search param...
...And 2 more matches
XML Extras
not as just another document format. the module is structured as a drop-in component and exposes its xml-as-data features both to javascript and c++/xpcom users. the xml extras module is built by default on all platforms, and is included in the browser installers so it is available in the nightly builds. feature status feature status xmlserializer available xmlhttprequest available domparser (string and stream input source) available web services with soap and wsdl no longer available from gecko 1.9/firefox 3. ...
... a few examples dealing with xml from mozillazine knowledge base. qa and testing there are some online tests for mainly exercising the http get method via xmlhttprequest. other test cases for each of the implemented components listed above exist in extensions/xmlextras/tests/. more exhaustive test suites need to be created, however. if you'd like to help out with qa, you can do one of the following: sign up as the qa owner for any of the implemented components. the qa owner will manage the tests associated with their component, act as qa contact for related bugs and help with regression testing. contribute a test suite or individual tests that use the implemented components. file bugs for new test you have, and/or check them into extensions/xmlextras/tests/. file bugs against the im...
...sts that use the implemented components. file bugs for new test you have, and/or check them into extensions/xmlextras/tests/. file bugs against the implemented components. bugs should be filed against the xml component in the browser product. documentation probably the best way to learn how to use these technologies is through examples. there are some in extensions/xmlextras/tests/. if you follow that link to look at the examples you will need to look at page source for the html documents. for xmlhttprequest object you can mostly rely on the microsoft xmlhttprequest documentation, with some caveats: all functions and property names begin with a lower case letter and the object creation is different. some properties are not implemented. thad hoffman has written a document that shows how ...
...And 2 more matches
XPCOM array guide
Mozilla › Tech › XPCOM › Guide › Arrays
is guide describes the available arrays as well as the enumerator classes that can be used to get to them. in this document the term array refers to a container for multiple objects with a numeric, zero-based index. the standard array classes are: nsiarray - a scriptable container for scriptable xpcom objects. this array is read-only, and the interface does not provide any methods that will allow adding and removing members. nsimutablearray - a scriptable container for scriptable xpcom objects, which allows addition and removal of member objects. this interface actually derives from nsiarray. nstarray<t> - a c++ class which provides a typesafe container for objects or primitive types (pointers, integers, and so on). the objects must define a default constructor and a copy constructor. t...
...esafe arrays like nscomarray<t> nstarray<t> wherever possible. avoid all obsolete arrays and enumerators. avoid creating temporary arrays. scriptable arrays nsiarray / nsimutablearray usage nsiarray is useful if you need to pass arrays of com objects through interfaces or require a scriptable array. it can hold strong or weak references to its container objects. this basic interface only allows querying of existing elements in the array. the methods that modify the array have been broken out into nsimutablearray. an nsiarray implementation can be created from c++ or javascript using nsicomponentmanager.createinstance() and the contract id "@mozilla.org/array;1". the created array implements nsimutablearray and nsiarray. since nsimutablearray derives from nsiarray, the resulting array ...
...o the caller *aresult = array; ns_addref(*aresult); } javascript example function getlist() { var array = components.classes["@mozilla.org/array;1"] .createinstance(components.interfaces.nsimutablearray); // append some elements ... // return it to the caller return array; } access to elements since nsiarray is a regular xpcom object, its interfaces follows the standard conventions of ownership. access to specific elements is through queryelementat, which is similar to queryinterface, but it takes a specific index. void notifyobservers(nsiarray* aarray) { pruint32 length; aarray->getlength(&length); for (pruint32 i=0; i<length; ++i) { nscomptr<nsimyobserver> element; aarray->queryelementat(i, ns_get_iid(nsielement), getter_addrefs(el...
...And 2 more matches
XPCOM changes in Gecko 2.0
several changes that affect xpcom component compatibility are taking place in gecko 2. this article details those changes, and provides suggestions for how to update your code. no more frozen interfaces there are no longer any frozen interfaces; from now on, all interfaces are subject to change. documentation will be updated as time allows to remove references to interfaces being "frozen" or "unfrozen." component registration the way xpcom components are registered changed in gecko 2. prior to gecko 2, during component registration, all binary and javascript component files were loaded and called, asking them to register themselves. if you used xpcomutils.jsm, some of this was hidden from you, but it was still there. starting in gecko 2, however, components are registered using manifest file...
... code : components.utils.import("resource://gre/modules/xpcomutils.jsm"); function mycomponent() { } mycomponent.prototype = { // this must match whatever is in chrome.manifest! classid: components.id("{e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8}"), queryinterface: xpcomutils.generateqi([components.interfaces.nsimycomponent]), /* nsimycomponent implementation goes here */ ... }; // the following line is what xpcom uses to create components. each component prototype // must have a .classid which is used to create it. const nsgetfactory = xpcomutils.generatensgetfactory([mycomponent]); a component may implement backwards compatibility with gecko 1.9.2 by dynamically detecting which symbols are exported by xpcomutils.jsm and exporting the correct function: /** * xpcomutils.generatensget...
... extensions observed app-startup because in the past, you needed to load for app-startup in order to be able to register to observe profile-after-change in the first place. as of gecko 1.9.1, this is no longer the case, however; you can now register for profile-after-change using the category manager. see receiving startup notifications for details. to add a category entry, you must insert the following line to your chrome.manifest: category profile-after-change mycomponent @foobar/mycomponent;1 important: formerly, the contract id of the category entry was prefixed with "service," if the component was implemented as a service. this prefix needs to be dropped when migrating to chrome.manifest. changed category names the xpcom category manager is used to register certain global helper objects...
...And 2 more matches
Packaging WebLock
« previousnext » in this final part of the tutorial, we'll put all of the pieces of the web locking component - the library itself, the type library, the header file, and the user interface resources - into a package that can be installed on other systems. the first section, component installation overview, describes the general installation process in mozilla. the following sections describe the steps you can take to organize the weblock component for distribution and installation. note: the emphasis of this tutorial is on the component development itself, so this section on packaging and installing extensions to gecko is necessarily brief. for more detailed information on packaging and installation of components into gecko-based applications, see http://www.mozilla.org/p...
...llation scripts. using xpinstall, you can create web-based installations for gecko-based applications, mozilla extensions, or individual components. the installation script for the weblock component can also be used to register the component with the browser into which it is installed (see registration methods in xpcom for more information on registration). the sample installation script shown below uses the mozilla xpinstall technology to manipulate an installer and talk to mozilla'schrome registry as high-level javascript objects. what is the chrome registry? like the windows registry, the chrome registry is a database of information about applications, skins, and other extensions that have been installed in a gecko application. since mozilla and other gecko-based applications are cross...
...ent. weblock installation script is the completetrigger installation script, which can be launched from a web page. the files themselves are stored in the jar file weblock.jar, which is simple a zip file with the xpi extension that sometimes also contains an internal installation file called install.js. once you have the component and the other resources for weblock packaged properly (see the following section, archiving resources), the installation script for weblock is a simple one (see the weblock installation script). archiving resources once you have compiled all the resources that make up the weblock component and the files that make up the user interface that will be added to the browser, you can place these within a subdirectory called weblock. place the entire subdirectory into a...
...And 2 more matches
Preface
his is a book about gecko, and about creating xpcom components for gecko-based applications. though the emphasis is on the practical steps you take to make your c++ code into a component that can be used in gecko, we hope that these steps will also give us an occasion to discuss all of the tools, techniques, and technologies that make up xpcom. accordingly, the book is arranged so that you can follow along and create your own components or learn about different xpcom topics individually, as in a reference work. for example, the introduction includes a discussion of components and what they are, and the first chapter - in which you compile the basic code and register it with mozilla - prompts a discussion of the relationship between components and modules, of xpcom interfaces, and of the regis...
...or these components in gecko, which is xpcom. who should read this book no one. it is badly out of date, and much of what it says is either no longer remotely accurate, or is severely deprecated. if you are a historian, though... creating xpcom components is meant for c++ developers. though you can create xpcom components in javascript and other languages, and though you might be able to follow along as a c programmer, the component implementation code is written in c++, and much of the discussion of how to make your codeinto an xpcom component starts from c++. you don't need to be a c++ expert, however. although basic ideas such as inheritance and encapsulation should be familar to you, wherever possible they are explained in the book as they are used. also many of the examples are in ...
...m's functionality. a full description of the component in this tutorial can be found in the what we'll be working on section of the tutorial. despite what old documentation says, xpcom should not be used to make npapi plugins scriptable. starting with gecko 1.7.5 (firefox 1.0) a special npapi extension for scriptability is supported, see scripting plugins. organization of the tutorial the following list provides an overview of the steps that we will take to build an xpcom component called weblock, which provides site blocking functionality to gecko-based browsers. each one of these steps has its own chapter, in which a number of topics associated with the step are discussed. create the generic module code for the component. use c++ macros, special string classes and smart pointers to...
...And 2 more matches
Detailed XPCOM hashtable guide
need to be sorted; very small datasets (less than 12-16 items); data that does not need random access. in these situations, an array, a linked-list, or various tree data structures are more efficient. ...
...re more efficient. mozilla's hashtable implementations mozilla has several hashtable implementations, which have been tested and, tuned, and hide the inner complexities of hashtable implementations: pldhash - low-level c api; stores keys and data in one large memory structure; uses the heap efficiently; client must declare an "entry class" and may not hold onto entry pointers. plhashtable - low-level c api; entry class pointers are constant; more efficient for large entry structures; often wastes memory making many small heap allocations. nsthashtable - low-level c++ wrapper around pldhash; generates callback functions and handles most casting automagically. client writes their own entry class which can include complex key and data types. nsdatahashtable/nsinterfacehashtable/nsclassha...
... you must declare an entry struct ...
...And 2 more matches
nsIAccessible
attributes are grouped by categories. role, states and name these includes main properties used to describe the accessible. nsiaccessible.role to get the role of the accessible nsiaccessible.getstate() to get states of the accessibe nsiaccessible.name, nsiaccessible.value to get the name and the value of the accessible tree navigation you can navigate through the accessible tree by the following methods and attributes. nsiaccessible.parent to get the parent accessible nsiaccessible.nextsibling, nsiaccessible.previoussibling to get sibling accessibles nsiaccessible.firstchild, nsiaccessible.lastchild to get first and last child nsiaccessible.children, nsiaccessible.getchildat(), nsiaccessible.childcount to navigate through the children by index accessible position you can use...
...ccessible.relationscount. focus and selection in order to focus an accessible or get focused child accessible use nsiaccessible.takefocus() and nsiaccessible.focusedchild. to select an accessible you can use nsiaccessible.setselected(), nsiaccessible.takeselection() and nsiaccessible.extendselection(). actions you can prepare actions on some accessibles (for example on button accessible). the following methods are intended for this nsiaccessible.actioncount, nsiaccessible.getactionname(), nsiaccessible.getactiondescription() and nsiaccessible.doaction(). descriptions nsiaccessible.description and nsiaccessible.help provides additional text information about accessible. attributes many accessibles exposes attributes to provide more details that cannot be fit into existing api methods, please ...
...ible.help provides additional text information about accessible. attributes many accessibles exposes attributes to provide more details that cannot be fit into existing api methods, please refer to attributes documentation for more information. you can use nsiaccessible.attributes to get a map of attributes. keyboard shortcuts some actions on accessibles can be performed by keyboard shortcuts. following methods are used to get them nsiaccessible.defaultkeybinding(), nsiaccessible.getkeybindings(), nsiaccessible.keyboardshortcut. size and screen position you can use nsiaccessible.getbounds() to get size and coordinates of the accessible. layout oriented methods nsiaccessible.getchildatpoint() to get child accessible from point nsiaccessible.getaccessibletoleft(), nsiaccessible.getaccessib...
...And 2 more matches
nsIClipboardDragDropHooks
e added. adding the same hook to the same window will not add a second call. each hook can only be called once per user action/api. not all hooks are guaranteed to be called. if there are multiple hooks set for a window, any of them has an opportunity to cancel the action so no further processing will occur. if any errors occur (without setting the boolean result) the default action will occur. ...
... per user action/api. not all hooks are guaranteed to be called. if there are multiple hooks set for a window, any of them has an opportunity to cancel the action so no further processing will occur. if any errors occur (without setting the boolean result) the default action will occur. allowdrop() will be called many times during drag so ensure that it is efficient. ...
...ere are multiple hooks set for a window, any of them has an opportunity to cancel the action so no further processing will occur. if any errors occur (without setting the boolean result) the default action will occur. allowdrop() will be called many times during drag so ensure that it is efficient. method overview boolean allowdrop(in nsidomevent event, in nsidragsession session); boolean allowstartdrag(in nsidomevent event); boolean oncopyordrag(in nsidomevent aevent, in nsitransferable trans); boolean onpasteordrop(in nsidomevent event, in nsitransferable trans); methods allowdrop() tells gecko whether a drop is allowed on this content area. boolean allowdrop( in nsidomevent event, in nsidragsession session ); parameters event the dom event (drag gesture). session the dra...
...And 2 more matches
nsIMsgFolder
ed long numfolders); nsisupportsarray getallfolderswithflag(in unsigned long aflag); void getexpansionarray(in nsisupportsarray expansionarray); acstring geturiformsg(in nsimsgdbhdr msghdr); void deletemessages(in nsisupportsarray messages,in nsimsgwindow msgwindow, in boolean deletestorage, in boolean ismove, in nsimsgcopyservicelistener listener, in boolean allowundo); void copymessages(in nsimsgfolder srcfolder, in nsisupportsarray messages,in boolean ismove, in nsimsgwindow msgwindow,in nsimsgcopyservicelistener listener, in boolean isfolder, in boolean allowundo); void copyfolder(in nsimsgfolder srcfolder, in boolean ismovefolder,in nsimsgwindow msgwindow, in nsimsgcopyservicelistener listener ); void copyfilemessage(in nsifi...
... boolean readonly: returns true if this folder has sub folders. messages nsisimpleenumerator readonly: returns a list of components.interfaces.nsimsgdbhdr. numsubfolders unsigned long readonly: returns the number of sub folders that this folder has. invfeditsearchscope boolean readonly customidentity nsimsgidentity readonly: this allows a folder to have a special identity. e.g., you might want to associate an identity with a particular newsgroup, or for imap shared folders in the other users namespace, you might want to create a delegated identity. gettingnewmessages boolean are we running a url as a result of the user clicking get msg. filepath nsilocalfile local path of this folder. base...
...h of this folder. basemessageuri acstring readonly charset acstring the charset of this folder. charsetoverride boolean biffstate unsigned long locked boolean readonly flags unsigned long direct access to the set/get all the flags at once. knowssearchnntpextension boolean readonly allowsposting boolean readonly relativepathname acstring readonly sizeondisk unsigned long size of this folder on disk (not including .msf file) for imap, it's the sum of the size of the messages. username acstring readonly hostname acstring readonly expungedbytes unsigned long readonly deletable boolean rea...
...And 2 more matches
nsIProcessScriptLoader
: mozilla-central/source/dom/base/nsimessagemanager.idl inherits from: nsisupports this interface is used by parent process message managers to load scripts into a child process. the scripts run only once per process. the global object for process scripts is a contentprocessmessagemanager. ...
... in boolean aallowdelayedload) void removedelayedprocessscript(in astring aurl); jsval getdelayedprocessscripts(); loadprocessscript() load a script in the child process. process scripts are loaded as soon as loadprocessscript() is called. if this function is called on a chromemessagebroadcaster, : it will load the process script into all child processes. if aallowdelayedload is true, then the script will also be loaded into any new child processes created after the loadprocessscript() call. otherwise it will only be loaded into child processes that exist at the time of the call. ...
...it's possible that the child process for this chromemessagesender is not yet available at the time of the loadprocessscript() call, and if you pass false in this situation, your process script won't be loaded. ...
...And 2 more matches
nsISHistoryListener
ge(in long anumentries); boolean onhistoryreload(in nsiuri areloaduri, in unsigned long areloadflags); methods onhistorygoback() called when navigating to a previous session history entry, for example due to an nsiwebnavigation.goback() call. boolean onhistorygoback( in nsiuri abackuri ); parameters abackuri the uri of the session history entry being navigated to. ...
...onhistorygotoindex() called when navigating to a session history entry by index, for example, when nsiwebnavigation.gotoindex() is called. boolean onhistorygotoindex( in long aindex, in nsiuri agotouri ); parameters aindex the index in session history of the entry to be loaded. ...
...proceed or false to cancel it. onhistorygotoindex() called when navigating to a session history entry by index, for example, when nsiwebnavigation.gotoindex() is called. boolean onhistorygotoindex( in long aindex, in nsiuri agotouri ); parameters aindex the index in session history of the entry to be loaded. agotouri the uri of the session history entry to be loaded. return value true to allow the operation to proceed or false to cancel it. onhistorynewentry() called when a new document is added to session history. new documents are added to session history by the docshell when new pages are loaded in a frame or content area; for example by calling nsiwebnavigation.loaduri(). note: you can't cancel this operation. void onhistorynewentry( in nsiuri anewuri ); parameters anewuri the ...
...And 2 more matches
nsITelemetry
toolkit/components/telemetry/nsitelemetry.idlscriptable a service to gather performance data that can be tracked over time to allow generating histograms. 1.0 66 introduced gecko 6.0 inherits from: nsisupports last changed in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) implemented by: @mozilla.org/base/telemetry;1 as a service: let telemetry = components.classes["@mozilla.org/base/telemetry;1"] .getservice(components.interfaces.nsitelemetry); method overview jsval gethistogrambyid(in acstring id); jsval snapshothistograms(in uint32_t adataset, in boolean asubsession, in boolean aclear); jsval getkeyedhistogrambyid(in acstring id); void capturestack(in acstring name); jsval...
...oryname, in jsval ascalardata); void clearevents(); test only attributes attribute type description canrecordbase boolean a flag indicating if telemetry can record base data (fhr data). this is true if the fhr data reporting service or the self-support service is enabled. canrecordextended boolean a flag indicating if telemetry is allowed to record extended data. returns false if the user has not opted into "extended telemetry" on the release channel, when the user has explicitly opted out of telemetry on nightly/aurora/beta or if manually set to false during tests. canrecordreleasedata readonly boolean a flag indicating whether telemetry is recording release data. does not indicate whether telemetry will send any...
...ata readonly boolean a flag 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...
...And 2 more matches
nsITreeView
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 ); parameters index the ...
...fore -1 drop_on 0 drop_after 1 indropbefore 0 obsolete since gecko 1.8 indropon 1 obsolete since gecko 1.8 indropafter 2 obsolete since gecko 1.8 methods candrop() methods used by the drag feedback code to determine if a drag is allowable at the current location. 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 ); parameters index the index of the row. orientation the position around the given row. defined i...
... boolean candrop( in long index, in long orientation, in nsidomdatatransfer datatransfer ); parameters index the index of the row. orientation the position around the given row. defined in constants. datatransfer this parameter, added in gecko 1.9.2, provides the data being dragged, so that it can be examined to determine if a drop is possible. ...
...And 2 more matches
nsIWebProgressListener
r describe the entity for which the state transition is occurring. these flags are not mutually exclusive (that is an onstatechange() event may indicate some combination of these flags). constant value description state_is_request 0x00010000 this flag indicates that the state transition is for a request, which includes but is not limited to document requests. (see below for a description of document requests.) other types of requests, such as requests for inline content (for example images and stylesheets) are considered normal requests. state_is_document 0x00020000 this flag indicates that the state transition is for a document request. this flag is set in addition to state_is_request. a document request supports the nsichannel interface and...
...lag indicates an unknown security state. this may mean that the request is being loaded as part of a page in which some content was received over an insecure channel. state_is_secure 0x00000002 this flag indicates that the data corresponding to the request was received over a secure channel. the degree of security is expressed by state_secure_high, state_secure_med, or state_secure_low. security strength flags these flags describe the security strength and accompany state_is_secure in a call to the onsecuritychange() method. these flags are mutually exclusive. these flags are not meant to provide a precise description of data transfer security. these are instead intended as a rough indicator that may be used to, for example, color code a security indicator or otherwise...
...ugh indicator that may be used to, for example, color code a security indicator or otherwise provide basic data transfer security feedback to the user. constant value description state_secure_high 0x00040000 this flag indicates a high degree of security. state_secure_med 0x00010000 this flag indicates a medium degree of security. state_secure_low 0x00020000 this flag indicates a low degree of security. state identity flags these flags describe the level of identity verification in a call to the onsecuritychange() method. constant value description state_identity_ev_toplevel 0x00100000 state bits for ev == extended validation == high assurance. the topmost document uses an ev cert. ...
...And 2 more matches
Using the Multiple Accounts API
.announce +- netscape.public.mozilla.mail-news relevant api calls: nsimsgaccount.incomingserver nsimsgaccountmanager.allservers: a list of all servers held by all accounts. identities identities are used in the compose window. if identities are shared between accounts, you will only see that identity once in the list. in the above example, the list of identities would be as follows: alec flett <alecf@mywork.com>) alec flett <alecf@myisp.com>) alec flett <alecfnospam@myisp.com>) relevant api calls: nsimsgaccount.identities nsimsgaccountmanager.allservers: a list of all servers across all accounts storage the accounts are stored in the preferences. the accounts, identities, and servers are all linked via keys. keys are simply internal strings that uniquel...
...s possible to create and modify accounts through the account manager api. the account manager is responsible for the creation of all accounts, incoming servers, and identities. you should not use createinstance() to create any of the relevant objects because the account manager needs to keep track of all of these objects as they are created. to create accounts using the api, you should do the following: create a fresh identity with createidentity(); assign values to the various identity properties as necessary. create a fresh incoming server with createincomingserver(). you will need to pass it the server type as a string, from the list above. assign values to the various server properties as necessary. the most important properties here are the username and the hostname. create a...
...assword - boolean, should we remember the password? preference: mail.server.server.download_on_biff. - boolean, should we download new messags on biff (true) or just alert user that there is new mail (false) preference: mail.server.server.directory - local platform-specific path to store messages and folder indexes preference: mail.server.server.name - user-visible name of server the following are specific to imap: preference: mail.server.server.admin_url - administration url for server preference: mail.server.server.using_subscription - boolean, should we use subscriptions? (i.e. use lsub instead of list) preference: mail.server.server.cleanup_inbox_on_exit - boolean, should we purge the inbox when we quit? preference: mail.server.server.dual_use_folders - boolean - can...
...And 2 more matches
Working with windows in chrome code
ndow. so, for example, to access the dom document corresponding to the window, you can use win.document. note however, that the open() call returns before the window is fully loaded, so some calls, like win.document.getelementbyid() will fail. to overcome this difficulty, you can move the initialization code to a load handler of the window being opened or pass a callback function, as described below. you can get a window object from a document using document.defaultview. content windows when a xul window contains a widget capable of displaying a page, such as <browser> or <iframe>, the document in that widget is, naturally, separate from the document of the chrome window itself. there also is a window object for each sub-document, although there's no window in a common sense for the sub-d...
...e>, the document in that widget is, naturally, separate from the document of the chrome window itself. there also is a window object for each sub-document, although there's no window in a common sense for the sub-document. the same holds for chrome windows opened inside a tab of <tabbrowser>. the elements above the chrome document opened in the tab are separate from your chrome document. the following two subsections describe how to cross chrome-content boundaries in either way, i.e. accessing elements which are ancestors of your chrome document, or accessing elements which are descendants of your chrome document (but nevertheless in a different context). accessing content documents assume you have a document loaded in a <tabbrowser>, <browser>, or <iframe> element inside your document. y...
...m tree, as shown by the dom inspector, can look like this: #document window main-window ... browser #document window myextensionwindow where the child window is where your code runs in. your task is to access elements above your chrome document, i.e. to break out of your chrome window and access the ancestors. ...
...And 2 more matches
Using js-ctypes
before you can use js-ctypes, you need to import the ctypes.jsm code module. this is as simple as including the following line of code in the desired javascript scope: components.utils.import("resource://gre/modules/ctypes.jsm") loading a native library once you've imported the code module, you can call the ctypes.open() method to load each native library you wish to use. on windows, for example, you might load the system user32 library like this: var lib = ctypes.open("user32.dll"); on mac os x, you can load the core foundation library from the core foundation framework like this: var corefoundation = ctypes.open("/system/library/frameworks/corefoundation.framework/corefoundation"); the returned object is a library object that you use to declare functions and data types for use wi...
...directly. instead, you'll need to create a shim library that uses c functions that then call into the c++ library for you. examples can be found here: bugzilla :: bug 505907 - support c++ calling from jsctypes library search paths if you specify a full path, that path is used to load the library. otherwise, the system looks for the library in its standard locations. windows on windows, the following locations are searched for the library, in this order: the application's directory. the system directory. the 16-bit system directory. the windows directory. the current working directory the directories listed in the path environment variable. note: this information comes from this article on msdn. after you're done when you're finished using a library, you should close it by call...
...pcaption, _in_ uint utype ); so we read this article here on defining types and replicate it: declaring types var lib = ctypes.open("user32.dll"); or even without the extension. var lib = ctypes.open("user32"); calling carbon routines on mac os x this example demonstrates how to use ctypes to call a carbon function on mac os x. ...
...And 2 more matches
Streams - Plugins
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 *stream, npbool seekable, uint16* stype); the instance parameter refers to the plug-in instance receiving the stream; the type parameter represents the stream's mime type. the stream parameter is a pointer to the new stream, which is valid until the stream is destroyed. the seekable parameter specifies whether the stre...
...iority 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 series of calls to npp_writeready and npp_write. the browser calls npp_writeready be...
...ges the mode to np_seek. for streams that are not inherently seekable: the stream must be put in np_seek mode initially, because the browser must cache all the stream data on disk in order to access it randomly. for streams that are not inherently seekable and not initially in mode np_seek: npn_requestread returns the error code nperr_stream_not_seekable. the npn_requestread method has the following syntax: nperror npn_requestread(npstream *stream, npbyterange *rangelist); the stream parameter is the stream from which to read bytes; the rangelist parameter specifies the range of bytes in the form of a linked list of npbyterange objects, which the plug-in must allocate. because these objects are copied by the browser, the plug-in can delete them as soon as the call to npn_requestread ret...
...And 2 more matches
URLs - Plugins
es, posting data to an http server, uploading files to an ftp server, and sending mail. uniform resource locator (url) protocols provide a means for locating and accessing resources that are available on the internet and on intranets. plug-ins can request and receive the data associated with urls of any type that the browser can handle, including http, ftp, news, mailto, and gopher. the table below summarizes urls supported by gecko. in addition, gecko may support urls not listed on this table. url scheme description about locates browser information or "fun" pages. file (host-specific filenames) locates files on a specific host computer rather than an internet resource. ftp (file transfer protocol) locates files and directories on internet h...
...host computer rather than an internet resource. ftp (file transfer protocol) locates files and directories on internet hosts for file download. gopher (gopher protocol) locates specified items on a gopher server. obsolete since gecko 2.0 http (hypertext transfer protocol) locates resources on the internet. javascript executes javascript code that follows the url. netscape-specific. mailto (electronic mail address) locates the internet mailing address of an individual or service. nethelp displays a nethelp topic in a nethelp window. browser-specific. news (usenet news) locates usenet news groups or individual usenet articles. nntp (usenet news using nntp access) locates usenet news groups or individ...
...y buffer, set the flag file to false, the buffer buf to the data to post, and len to the length of the buffer. possible url types include http (similar to an html form submission), mailto (sending mail), news (posting a news article), and ftp (uploading a file). for protocols in which the headers must be distinguished from the body, such as http, the buffer or file should contain the headers, followed by a blank line, then the body. if no custom headers are required, simply add a blank line ('\n') to the beginning of the file or buffer. note: you cannot use npn_posturl to specify headers (even a blank line) in a memory buffer. to do this, use npn_posturlnotify for this purpose. § the npn_posturlnotify function has all the same capabilities and works like npn_posturl in most ways except tha...
...And 2 more matches
Color vision simulation - Firefox Developer Tools
etinopathy, and other disorders of the retina; it can be age-related, congenital, or due to an injury. to enable this feature, you must have webrender enabled; it may be enabled by default, depending on your configuration of firefox. in the firefox configuration editor, make sure the gfx.webrender.all option is set to true. in the simulate menu, you can choose one option at a time from the following list: none — choose this to return to normal display protanomaly (low red) deuteranomaly (low green) tritanomaly (low blue) protanopia (no red) deuteranopia (no green) tritanopia (no blue) contrast loss these simulations are not completely medically accurate. however, they can give you a sense of what your web site looks like to users with vision problems, and therefore help you...
...uteranomaly (low green) tritanomaly (low blue) protanopia (no red) deuteranopia (no green) tritanopia (no blue) contrast loss these simulations are not completely medically accurate. however, they can give you a sense of what your web site looks like to users with vision problems, and therefore help you judge whether you need to make adjustments in your color or contrast choices. the following table shows a colorful image of a cat's face, and what it looks like in the various simulations. ...
...e. however, they can give you a sense of what your web site looks like to users with vision problems, and therefore help you judge whether you need to make adjustments in your color or contrast choices. the following table shows a colorful image of a cat's face, and what it looks like in the various simulations. ...
...And 2 more matches
Introduction to DOM Inspector - Firefox Developer Tools
see the dom structure of the mozilla.org home page. you should not use this approach to inspect chrome documents. instead, ensure that the document loads via normal means and use the inspect chrome document menupopup to select it for inspection. when you inspect a web page with this method, a browser pane at the bottom of the dom inspector window will open up, displaying the web page. this allows you to use the dom inspector without having to use a separate browser window, or without embedding a browser in your application at all. if you find that the browser pane takes up too much space, you may close it, but you will not be able to observe any of the visual consequences of your actions. using the dom inspector once you've opened the document for the page or chrome you are interested ...
... browser window, for example, and select nodes in the dom nodes viewer (other than the elements which have no visible ui as is the case with the endless list of script elements that are loaded into browser.xul), you will see the various parts of the browser interface being highlighted with a blinking red border. you can traverse the structure and go from the topmost parts parts of the dom tree to lower level nodes, such as the "search-go-button" icon that lets users perform a query using the selected search engine. now, once you have selected a node like the "search-go-button" node, you can select any one of several viewers to display information about that node in the object pane of the dom inspector application window, all of which are available from the menupopup accessed from the upper...
...rules viewer from this menu and see the various selectors and rules that have been applied. the rule that applies the search icon to the element uses a class simple selector and uses a list-style-image property to point to a file in the current theme. the list of viewers available from the viewer menu gives you some idea about how extensive the dom inspector's inspecting capabilities are. the following descriptions provide an overview of what these viewers are about: the dom nodes viewer shows attributes of nodes that can take them, or the text content of text nodes, comments, and processing instructions. the attributes and text contents may also be edited. the box model viewer gives various metrics about xul and html elements, including placement and size. the xbl bindings viewer lists t...
...And 2 more matches
UI Tour - Firefox Developer Tools
this article is a quick tour of the main sections of the javascript debugger's user interface. the ui is split vertically into three panels source list pane source pane the contents of the third pane depend on the current state of the debugger and may include the following sections: toolbar watch expressions breakpoints call stack scopes xhr breakpoints event listener breakpoints dom mutation breakpoints source list pane the source list pane lists all the javascript source files loaded into the page, and enables you to select one to debug. at the top level sources are organized by origin, and under that they're organized by the directory structure from which they are served. you can search for a file using ctrl + p (cmd + p on a mac). web extensi...
...igin, and under that they're organized by the directory structure from which they are served. you can search for a file using ctrl + p (cmd + p on a mac). web extensions are listed in the source list pane using the extension's name. there are several context menu options available for individual files and folders or groups; typically viewed by right-clicking on the item. for files, the following context menu options are available: copy source uri copies the full identifier of the file to the clipboard. ignore source causes the debugger to skip the file when "stepping into" functions; this can be helpful for avoiding stepping into libraries used by your code. when a file is ignored, it has a small eye icon next to it in place of its regular icon. download file opens a file dialo...
...he full identifier of the file to the clipboard. ignore source causes the debugger to skip the file when "stepping into" functions; this can be helpful for avoiding stepping into libraries used by your code. when a file is ignored, it has a small eye icon next to it in place of its regular icon. download file opens a file dialog so you can save the file locally. for folders and groups, the following context menu options are available: collapse all collapses all subfolders of the item. expand all expands all subfolders of the item. set directory root changes the source list view so that only that item and its children are visible. the name of the selected directory is shown at the top of the source list pane; clicking this name reverts the pane to showing all source items. ignore (...
...And 2 more matches
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. ...
...position of its grid lines and tracks: the overlay is still shown when you select other elements, so you can edit related css properties and see how the grid is affected. the layout view grid section when grids are included on a page, the css pane's layout view includes a "grid" section containing a number of options for viewing those grids. you can find out more about those in the section below. note: the layout view can be found underneath the layout tab on the right-hand pane of the page inspector. the above and below screenshots should give you further hints on how to get to this. grid options the grid section of the layout view looks like this: you'll see a number of options contained within: overlay grid: contains a checkbox for each grid present on the page, along with ...
... grid display settings: display line numbers: turn the line numbers shown for each grid overlay on and off (on by default). ...
...And 2 more matches
Frame rate - Firefox Developer Tools
a frame rate of 60fps is the target for smooth performance, giving you a time budget of 16.7ms for all the updates needed in response to some 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). ...
...eness 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. ...
...if it takes too long for the browser to process the frame, then the browser will appear momentarily unresponsive (janky). ...
...And 2 more matches
Waterfall - Firefox Developer Tools
perations, called markers, are shown as horizontal bars, laid out in a waterfall to reflect the serial nature of the browser's execution. when a marker is selected you'll see more information about it in a sidebar on the right. this includes the marker's duration and some more information that's specific to the marker type. markers the markers for operations are color-coded and labeled. the following operations are recorded: name and description color detailed information dom event javascript code that's executed in response to a dom event. event type for example, "click" or "message". event phase for example, "target" or "capture". javascript functions executed in the page are lab...
...nt a string indicating what kind of restyling is needed. the hint may be any of: self subtree latersiblings csstransitions cssanimations svgattranimations styleattribute styleattribute_animations force forcedescendants layout calculating the position and size of page elements. this operation is sometimes called "reflow". paint drawing pixels to the screen. garbage collection garbage collection event. non-incremental gc events are labeled "(non-incremental)". reason a string indicating the reason gc was performed. non-incremental reason if the gc event was non-incremental, the string indicates the reason non-increm...
...uses some javascript in the page to run. the javascript changes some of the page's dom or cssom. recalculate style: if the browser thinks the computed styles for page elements have changed, it must then recalculate them. layout: next, the browser uses the computed styles to figure out the position and geometry for the elements. this operation is labeled "layout" but is also sometimes called "reflow". paint: finally, the browser needs to repaint the elements to the screen. one last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process called "composition". this sequence needs to fit into a single frame, since the screen isn't updated until it is complete. it's commonly accepted that 60 frames per second is the...
...And 2 more matches
AudioParam - Web APIs
there are two kinds of audioparam, a-rate and k-rate parameters: an a-rate audioparam takes the current audio parameter value for each sample frame of the audio signal. ...
...mple frames. in other words, the same value applies to every frame in the audio as it's processed by the node. each audionode defines which of its parameters are a-rate or k-rate in the spec. each audioparam has a list of events, initially empty, that define when and how values change. when this list is not empty, changes using the audioparam.value attributes are ignored. this list of events allows us to schedule changes that have to happen at very precise times, using arbitrary timelime-based automation curves. 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 poss...
... defaultvalue. methods audioparam.setvalueattime() schedules an instant change to the value of the audioparam at a precise time, as measured against audiocontext.currenttime. the new value is given by the value parameter. audioparam.linearramptovalueattime() schedules a gradual linear change in the value of the audioparam. ...
...And 2 more matches
AuthenticatorAssertionResponse.authenticatorData - Web APIs
n arraybuffer containing information from the authenticator such as the relying party id hash (rpidhash), a signature counter, test of user presence, user verification flags, and any extensions processed by the authenticator. ...
...ast 37 bytes, containing the following fields: rpidhash (32 bytes) - a sha256 hash of the relying party id that was seen by the browser. the server will ensure that this hash matches a hash of its own origin in order to prevent phishing or other man-in-the-middle attacks. flags (1 bytes) - a bitfield that indicates various attributes that were asserted by the authenticator. the bits are as follows, where "bit 0" is the least significant bit and all bits not specifically mentioned below are "reserved for future use": bit 0, user presence (up) - if set, authenticator validated that the user was present through some test of user presence (tup), such as touching a button on the authenticator. bit 2, user verification (uv) - if set, authenticator verified the actual user, through a bi...
...r presence (up) - if set, authenticator validated that the user was present through some test of user presence (tup), such as touching a button on the authenticator. bit 2, user verification (uv) - if set, authenticator verified the actual user, through a biometric, pin, or other authentication method. bit 6, attested credential data (at) - if set, attestedcredentialdata will immediately follow the first 37 bytes of this authenticatordata. bit 7, extension data (ed) - if set, extension data is present. extension data will follow attestedcredentialdata if it is present, or will immediatelly follow the first 37 bytes of the authenticatordata if no attestedcredentialdata is present. signcount (4 bytes) - a signature count from the authenticator. the server will use this counter to...
...And 2 more matches
CSS.registerProperty() - Web APIs
syntax optional a domstring representing the expected syntax of the defined property. ...
... syntax optional a domstring representing the expected syntax of the defined property. ...
... syntax optional a domstring representing the expected syntax of the defined property. ...
...And 2 more matches
Drawing text - Web APIs
, left, right or center. the default value is start. textbaseline = value baseline alignment setting. possible values: top, hanging, middle, alphabetic, ideographic, bottom. the default value is alphabetic. direction = value directionality. possible values: ltr, rtl, inherit. the default value is inherit. these properties might be familiar to you, if you have worked with css before. ...
...abetic, ideographic, bottom. the default value is alphabetic. direction = value directionality. possible values: ltr, rtl, inherit. the default value is inherit. these properties might be familiar to you, if you have worked with css before. the following diagram from the whatwg demonstrates the various baselines supported by the textbaseline property. ...
... function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); var text = ctx.measuretext('foo'); // textmetri...
...And 2 more matches
Pixel manipulation with canvas - Web APIs
e haven't looked at the actual pixels of our canvas. with the imagedata object you can directly read and write a data array to manipulate pixel data. we will also look into how image smoothing (anti-aliasing) can be controlled and how to save images from your canvas. the imagedata object the imagedata object represents the underlying pixel data of an area of a canvas object. it contains the following read-only attributes: width the width of the image in pixels. height the height of the image in pixels. data a uint8clampedarray representing a one-dimensional array containing the data in the rgba order, with integer values between 0 and 255 (included). the data property returns a uint8clampedarray which can be accessed to look at the raw pixel data; each pixel is represented by fou...
..., with the top left pixel's red component being at index 0 within the array. pixels then proceed from left to right, then downward, throughout the array. the uint8clampedarray contains height × width × 4 bytes of data, with index values ranging from 0 to (height×width×4)-1. ...
...t you can use the putimagedata() method to paint pixel data into a context: ctx.putimagedata(myimagedata, dx, dy); the dx and dy parameters indicate the device coordinates within the context at which to paint the top left corner of the pixel data you wish to draw. for example, to paint the entire image represented by myimagedata to the top left corner of the context, you can simply do the following: ctx.putimagedata(myimagedata, 0, 0); grayscaling and inverting colors in this example we iterate over all pixels to change their values, then we put the modified pixel array back to the canvas using putimagedata(). the invert function simply subtracts each color from the max value 255. the grayscale function simply uses the average of red, green and blue. you can also use a weighted avera...
...And 2 more matches
Using images - Web APIs
age as the source! importing images into a canvas is basically a two step process: get a reference to an htmlimageelement object or to another canvas element as a source. it is also possible to use images by providing a url. draw the image on the canvas using the drawimage() function. let's take a look at how to do this. getting images to draw the canvas api is able to use any of the following data types as an image source: htmlimageelement these are images created using the image() constructor, as well as any <img> element. svgimageelement these are images embedded using the <image> element. htmlvideoelement using an html <video> element as your image source grabs the current frame from the video and uses it as an image. htmlcanvaselement you can use another <canvas> elem...
...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 of data urls is that the resulting image is available immediately without another round trip to the server. anoth...
...image() method to render it to the canvas. as we will see later the drawimage() method is overloaded and has several variants. in its most basic form it looks like this: drawimage(image, x, y) draws the canvasimagesource specified by the image parameter at the coordinates (x, y). svg images must specify a width and height in the root <svg> element. example: a simple line graph in the following example, we will use an external image as the backdrop for a small line graph. using backdrops can make your script considerably smaller because we can avoid the need for code to generate the background. in this example, we're only using one image, so i use the image object's load event handler to execute the drawing statements. the drawimage() method places the backdrop at the coordinate (0, ...
...And 2 more matches
Content Index API - Web APIs
the content index api allows developers to register their offline enabled content with the browser. concepts and 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...
...rectly. instead, you need to provide a url for a page that displays media, and which works offline. interfaces contentindex the contentindex interface provides functionality to register content available offline. contentindexevent the contentindexevent interface of the content index api defines the object used to represent the contentdelete event. service worker additions the following additions to the serviceworker have been specified in the content index api spec to provide an entry point for using content indexing. serviceworkerregistration.index read only returns a reference to the contentindex interface for indexing cached pages. serviceworkerglobalscope.oncontentdelete an event handler fired whenever a contentdelete event occurs. this happens when content i...
...ed in the content index api spec to provide an entry point for using content indexing. serviceworkerregistration.index read only returns a reference to the contentindex interface for indexing cached pages. serviceworkerglobalscope.oncontentdelete an event handler fired whenever a contentdelete event occurs. this happens when content is removed by the user agent. examples all the following examples assume a service worker has been registered. for more information see the service worker api. feature detection and interface access here we get a reference to the serviceworkerregistration, then check for the index property, which gives us access to the content index interface. // reference registration const registration = await navigator.serviceworker.ready; // feature detectio...
...And 2 more matches
DOMException - Web APIs
e read only returns a domstring that contains one of the strings associated with an error name. error names common error names are listed here. some apis define their own sets of names, so this is not necessarily a complete list. note: because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. indexsizeerror the index is not in the allowed range. for example, this can be thrown by the range object. (legacy code value: 1 and legacy constant name: index_size_err) hierarchyrequesterror the node tree hierarchy is not correct. (legacy code value: 3 and legacy constant name: hierarchy_request_err) wrongdocum...
...uesterror the node tree hierarchy is not correct. (legacy code value: 3 and legacy constant name: hierarchy_request_err) wrongdocumenterror the object is in the wrong document. (legacy code value: 4 and legacy constant name: wrong_document_err) invalidcharactererror the string contains invalid characters. (legacy code value: 5 and legacy constant name: invalid_character_err) nomodificationallowederror the object cannot be modified. (legacy code value: 7 and legacy constant name: no_modification_allowed_err) notfounderror the object cannot be found here. (legacy code value: 8 and legacy constant name: not_found_err) notsupportederror the operation is not supported. (legacy code value: 9 and legacy constant name: not_supported_err) invalidstateerror the object is in an invalid stat...
... is in an invalid state. (legacy code value: 11 and legacy constant name: invalid_state_err) syntaxerror the string did not match the expected pattern. (legacy code value: 12 and legacy constant name: syntax_err) invalidmodificationerror the object cannot be modified in this way. (legacy code value: 13 and legacy constant name: invalid_modification_err) namespaceerror the operation is not allowed by namespaces in xml. (legacy code value: 14 and legacy constant name: namespace_err) invalidaccesserror the object does not support the operation or argument. (legacy code value: 15 and legacy constant name: invalid_access_err) typemismatcherror the type of the object does not match the expected type. (legacy code value: 17 and legacy constant name: type_mismatch_err) this value is depre...
...And 2 more matches
Document.cookie - Web APIs
Web › API › Document › cookie
alue may be surrounded by whitespace (space and tab characters): in fact, rfc 6265 mandates a single space after each semicolon, but some user agents may not abide by this. write a new cookie document.cookie = newcookie; in the code above, newcookie is a string of form key=value. note that you can only set/update a single cookie at a time using this method. consider also that: any of the following cookie attribute values can optionally follow the key-value pair, specifying the cookie to set/update, and preceded by a semi-colon separator: ;path=path (e.g., '/', '/mydir') if not specified, defaults to the current path of the current document location. note: prior to gecko 6.0, paths with quotes were treated as if the quotes were part of the string, instead of as if they we...
...rict or none. the lax value value will send the cookie for all same-site requests and top-level navigation get requests. this is sufficient for user tracking, but it will prevent many csrf attacks. this is the default value in modern browsers. the strict value will prevent the cookie from being sent by the browser to the target site in all cross-site browsing contexts, even when following a regular link. the none value explicitly states no restrictions will be applied. the cookie will be sent in all requests—both cross-site and same-site. the cookie value string can use encodeuricomponent() to ensure that the string does not contain any commas, semicolons, or whitespace (which are disallowed in cookie values). some user agent implementations support the f...
...g a regular link. the none value explicitly states no restrictions will be applied. the cookie will be sent in all requests—both cross-site and same-site. the cookie value string can use encodeuricomponent() to ensure that the string does not contain any commas, semicolons, or whitespace (which are disallowed in cookie values). some user agent implementations support the following cookie prefixes: __secure- signals to the browser that it should only include the cookie in requests transmitted over a secure channel. __host- signals to the browser that in addition to the restriction to only use the cookie from a secure origin, the scope of the cookie is limited to a path attribute passed down by the server. if the server omits the path attribute the "directory" of...
...And 2 more matches
Examples of web and XML development using the DOM - Web APIs
this chapter provides some longer examples of web and xml development using the dom. wherever possible, the examples use common apis, tricks, and patterns in javascript for manipulating the document object. ...
...les individually using the stylesheet, style, and cssrule objects, as demonstrated in this example, which prints out all of the style rule selectors to the console. var ss = document.stylesheets; for(var i = 0; i < ss.length; i++) { for(var j = 0; j < ss[i].cssrules.length; j++) { dump( ss[i].cssrules[j].selectortext + "\n" ); } } for a document with a single stylesheet in which the following three rules are defined: body { background-color: darkblue; } p { font-face: arial; font-size: 10pt; margin-left: .125in; } #lumpy { display: none; } this script outputs the following: body p #lumpy example 5: event propagation this example demonstrates how events fire and are handled in the dom in a very simple way. when the body of this html document loads, an event listener is regist...
...ute or with javascript (e.g., elt.style.backgroundcolor="rgb(173, 216, 230)"). these latter types of styles can be retrieved with the more direct elt.style property, whose properties are listed in the dom css properties list. getcomputedstyle() returns a computedcssstyledeclaration object, whose individual style properties can be referenced with this object's getpropertyvalue() method, as the following example document shows. <!doctype html> <html lang="en"> <head> <title>getcomputedstyle example</title> <script> function cstyles() { var refdiv = document.getelementbyid("d1"); var txtheight = document.getelementbyid("t1"); var h_style = document.defaultview.getcomputedstyle(refdiv, null).getpropertyvalue("height"); txtheight.value = h_style; var txtwidth = document.getelementb...
...And 2 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
nce to this node object. to insert this text into your html page, you need to make this text node a child of some other node element. inserting elements with appendchild(..) so, by calling myp.appendchild(node_element), you are making the element a new child of the second <p> element. myp.appendchild(mytextnode); after testing this sample, note that the words hello and world are together: helloworld. so visually, when you see the html page it seems like the two text nodes hello and world are a single node, but remember that in the document model, there are two nodes. the second node is a new node of type text_node, and it is the second child of the second <p> tag. the following figure shows the recently created text node object inside the document tree. createtextnode() and appendchi...
...example, if you want to create a new <p> element as a child of the <body> element, you can use the mybody in the previous example and append a new element node. to create a node simply call document.createelement("tagname"). for example: mynewptagnode = document.createelement("p"); mybody.appendchild(mynewptagnode); removing nodes with the removechild(..) method nodes can be removed. the following code removes text node mytextnode (containing the word "world") from the second <p> element, myp. myp.removechild(mytextnode); text node mytextnode (containing the word "world") still exists. the following code attaches mytextnode to the recently created <p> element, mynewptagnode. mynewptagnode.appendchild(mytextnode); the final state for the modified object tree looks like this: cre...
... reviewing the html table structure creating element nodes and inserting them into the document tree the basic steps to create the table in sample1.html are: get the body object (first item of the document object). ...
...And 2 more matches
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...
...tbyid("output-box").innerhtml += "sorry! ...
...box" id="id-checkbox"/> </form> <div id="output-box"></div> result stopping keystrokes from reaching an edit field the following example demonstrates how invalid text input can be stopped from reaching the input field with preventdefault(). nowadays, you should usually use native html form validation instead. ...
...And 2 more matches
FileError - Web APIs
Web › API › FileError
you might encounter while accessing the file system using the asynchronous api. it extends the fileerror interface described in file writer and adds several new error codes. fileerror objects are passed to error callbacks. the objects have a code that shows the type of error that occurred. best practices most people don't read the page on errors and exceptions unless they're stumped. so the following are a few tips that could help you avoid some pitfalls. error callbacks are not optional for your sanity although error callbacks are optional, you should include them in the arguments of the methods for the sake of the sanity of your users. a web app could fail for various reasons, so you don't want to spend the rest of your day guessing what's going on and going through maddening troublesh...
...ot optional for your sanity although error callbacks are optional, you should include them in the arguments of the methods for the sake of the sanity of your users. a web app could fail for various reasons, so you don't want to spend the rest of your day guessing what's going on and going through maddening troubleshooting. don't run your app from file:// for security reasons, browsers do not allow you to run your app from file://. in fact, many of the powerful storage apis (such as file system, blobbuilder, and filereader) throw errors if you run the app locally from file://. when you're just testing your app, and you don't want to set up a web server, you can bypass the security restriction on chrome. just start chrome with the --allow-file-access-from-files flag. use the flag only for te...
...e values. error codes note: do not rely on the numeric values of the constants, which might change as the specifications continue to change. use the constant names instead. constant value description encoding_err 5 the url is malformed. make sure that the url is complete and valid. invalid_modification_err 9 the modification requested is not allowed. for example, the app might be trying to move a directory into its own child or moving a file into its parent directory without changing its name. invalid_state_err 7 the operation cannot be performed on the current state of the interface object. for example, the state that was cached in an interface object has changed since it was last read from disk. no_modification_al...
...And 2 more matches
FileHandle API - 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. the filehandle api allows for the manipulating of files, including creating files and modifying their content (unlike the file api). ...
...s and the behavior may change in the future. the filehandle api allows for the manipulating of files, including creating files and modifying their content (unlike the file api). because the files manipulated through that api can be physically stored on the device, the editing part uses a turn-based locking mechanism in order to avoid race issues. api overview this api is based on the following interfaces: idbdatabase.mozcreatefilehandle (was called idbdatabase.mozcreatefilehandle.) idbmutablefile (was previously filehandle.) lockedfile filerequest it also has connections with the file api, especially the file and blob interfaces. ...
...sm in order to avoid race issues. api overview this api is based on the following interfaces: idbdatabase.mozcreatefilehandle (was called idbdatabase.mozcreatefilehandle.) idbmutablefile (was previously filehandle.) lockedfile filerequest it also has connections with the file api, especially the file and blob interfaces. basic operations create a filehandle because the intent is to allow the storage of files through indexeddb, creating a filehandle instance requires an indexeddb database. var idbreq = indexeddb.open("myfilestoragedatabase"); idbreq.onsuccess = function(){ var db = this.result; var buildhandle = db.mozcreatefilehandle("test.txt", "plain/text"); buildhandle.onsuccess = function(){ var myfilehandle = this.result; console.log('handle', myfilehandle)...
...And 2 more matches
HTMLElement - Web APIs
the htmlelement interface represents any html element. some elements directly implement this interface, while others implement it via an interface that inherits it. ...
...element.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 offset calculations are currently compute...
...ent.title is a domstring containing the text that appears in a popup box when mouse is over the element. htmlelement.translate is a boolean representing the translation. event handlers most event handler properties, of the form onxyz, are defined on the documentandelementeventhandlers, globaleventhandlers or toucheventhandlers interfaces and implemented by htmlelement. in addition, the following handlers are specific to htmlelement. htmlelement.oncopy returns the event handling code for the copy event (bug 280959). htmlelement.oncut returns the event handling code for the cut event (bug 280959). htmlelement.onpaste returns the event handling code for the paste event (bug 280959). toucheventhandlers.ontouchstart returns the event handling code for the touchstart event...
...And 2 more matches
HTMLHyperlinkElementUtils.origin - Web APIs
e.g "blob:https://mozilla.org" will have "https://mozilla.org". ...
...e.g "blob:https://mozilla.org" will have "https://mozilla.org". ...
...e.g "blob:https://mozilla.org" will have "https://mozilla.org". ...
...And 2 more matches
HTMLSelectElement.disabled - Web APIs
the htmlselectelement.disabled is a boolean that reflects the disabled html attribute, which indicates whether the control is disabled. if it is disabled, it does not accept clicks. a disabled element is unusable and un-clickable. ...
... the htmlselectelement.disabled is a boolean that reflects the disabled html attribute, which indicates whether the control is disabled. if it is disabled, it does not accept clicks. a disabled element is unusable and un-clickable. ...
...syntax edit aselectelement.disabled = abool; example html <label> allow drinks? ...
...And 2 more matches
File drag and drop - Web APIs
lications to drag and drop files on a web page. this document describes how an application can accept one or more files that are dragged from the underlying platform's file manager and dropped on a web page. the main steps to drag and drop are to define a drop zone (i.e. a target element for the file drop) and to define event handlers for the drop and dragover events. these steps are described below, including example code snippets. the full source code is available in mdn's drag-and-drop repository (pull requests and/or issues are welcome). note: html drag and drop defines two different apis to support dragging and dropping files. one api is the datatransfer interface and the second api is the datatransferitem and datatransferitemlist interfaces. this example illustrates the use of both ap...
...drag and drop defines two different apis to support dragging and dropping files. one api is the datatransfer interface and the second api is the datatransferitem and datatransferitemlist interfaces. this example illustrates the use of both apis (and does not use any gecko specific interfaces). define the drop zone the target element of the drop event needs an ondrop global event handler. the following code snippet shows how this is done with a <div> element: <div id="drop_zone" ondrop="drophandler(event);"> <p>drag one or more files to this drop zone ...</p> </div> typically, an application will include a dragover event handler on the drop target element and that handler will turn off the browser's default drag behavior. to add this handler, you need to include a ondragover global event...
...vior. to add this handler, you need to include a ondragover global event handler: <div id="drop_zone" ondrop="drophandler(event);" ondragover="dragoverhandler(event);"> <p>drag one or more files to this drop zone ...</p> </div> lastly, an application may want to style the drop target element to visually indicate the element is a drop zone. ...
...And 2 more matches
Dragging and Dropping Multiple Items - Web APIs
getdata(), setdata() and cleardata() methods, however, they take an additional argument that specifies the index of the item to retrieve, modify or remove. the drag processing described in this document use the datatransfer interface. this processing does not use the datatransferitem interface nor the datatransferitemlist interface. setting and getting with indices the mozsetdataat() method allows you to add multiple items during a dragstart event. this function similarly to setdata() var dt = event.datatransfer; dt.mozsetdataat("text/plain", "data to drag", 0); dt.mozsetdataat("text/plain", "second data to drag", 1); this example adds two items to be dragged. the last argument specifies the index of the item to add. you should add them in order starting with 0 as you cannot add items ...
...p targets can expect consistent data. to check if multiple files are being dragged, check the mozitemcount property. it will be set to the number of items being dragged. if a particular drop target only supports dropping a single item, it could either reject the dragged items or it could just use just the first item. to reject the items, either don't cancel the dragover event, or set the effectallowed property to none. you may wish to do both in case another listener has already cancelled the event. to just take the first item being dropped, use the getdata() method as with a single item. this is convenient as drop targets which only need to support a single item do not need to do anything extra. however, use the mozgetdataat() method to retrieve a specific item from the data transfer. the...
...roperty to none. you may wish to do both in case another listener has already cancelled the event. to just take the first item being dropped, use the getdata() method as with a single item. this is convenient as drop targets which only need to support a single item do not need to do anything extra. however, use the mozgetdataat() method to retrieve a specific item from the data transfer. the following example retrieves a set of files being dragged and adds them to an array. function ondrop(event) { var files = []; var dt = event.datatransfer; for (var i = 0; i < dt.mozitemcount; i++) files.push(dt.mozgetdataat("application/x-moz-file", i)); } you may also wish to check if the desired format exists using the moztypesat method. as with the types property, it returns a list of str...
...And 2 more matches
IDBTransaction - Web APIs
n to set the mode of the transaction (e.g. is it readonly or readwrite), and you access an idbobjectstore to make a request. you can also use an idbtransaction object to abort transactions. note: this feature is available in web workers. ...
...up to the transaction object. also available via the onerror property. mode constants these constants are no longer available — they were removed in gecko 25. you should use the string constants directly instead. (bug 888598) transactions can have one of three modes: constant value description read_only "readonly" (0 in chrome) allows data to be read but not changed. read_write "readwrite" (1 in chrome) allows reading and writing of data in existing data stores to be changed. version_change "versionchange" (2 in chrome) allows any operation to be performed, including ones that delete and create object stores and indexes. this mode is for updating the version number...
...wn as "upgrade transactions." even if these constants are now deprecated, you can still use them to provide backward compatibility if required (in chrome the change was made in version 21). you should code defensively in case the object is not available anymore: var myidbtransaction = window.idbtransaction || window.webkitidbtransaction || { read_write: "readwrite" }; examples in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexed...
...And 2 more matches
LocalFileSystem - Web APIs
n the browser unless the app or the user removes it, but the user must grant you permission before you can use it. in contrast, temporary storage is automatically granted without any user permission, but it can be expunged by the browser at any time. to use persistent storage with the file system api, chrome exposes a requestquota api. so to request storage, you need to do something like the following: var requestedbytes = 1024*1024*10; // 10mb navigator.webkitpersistentstorage.requestquota ( requestedbytes, function(grantedbytes) { window.requestfilesystem(persistent, grantedbytes, oninitfs, errorhandler); }, function(e) { console.log('error', e); } ); your user must grant your app permission to store data locally before your app can use persistent storage. once your u...
...ur user must grant your app permission to store data locally before your app can use persistent storage. once your user grants it, you don't need to call requestquota() again. subsequent calls are a noop. another api, the quota management api, lets you query an origin's current quota usage and allocation using window.webkitpersistentstorage.queryusageandquota(). to learn more, see this stackoverflow answer. (an older version of the api is described at managing html5 offline storage.) working within a single origin the file system is sandboxed to a single origin. this means that your app cannot read, or write the files of another app's files. your app cannot access files in an arbitrary folder (such as, my pictures, my documents) on the user's hard drive either. for more information about ...
...tml5 offline storage.) working within a single origin the file system is sandboxed to a single origin. this means that your app cannot read, or write the files of another app's files. your app cannot access files in an arbitrary folder (such as, my pictures, my documents) on the user's hard drive either. for more information about restrictions, see the basic concepts article. example the following is a code snippet that shows how you can request a file system storage. //taking care of the browser-specific prefix window.requestfilesystem = window.requestfilesystem || window.webkitrequestfilesystem; // the first parameter defines the type of storage: persistent or temporary // next, set the size of space needed (in bytes) // initfs is the success callback // and the last one is the err...
...And 2 more matches
Location: origin - Web APIs
Web › API › Location › origin
e.g "blob:https://mozilla.org" will have "https://mozilla.org". ...
...e.g "blob:https://mozilla.org" will have "https://mozilla.org". ...
...e.g "blob:https://mozilla.org" will have "https://mozilla.org". ...
...And 2 more matches
MediaStreamAudioSourceNode - Web APIs
udio track. number of inputs 0 number of outputs 1 channel count defined by the first audio mediastreamtrack passed to the audiocontext.createmediastreamsource() method that created it. constructor new mediastreamaudiosourcenode() creates a new mediastreamaudiosourcenode object instance with the specified options. properties in addition to the following properties, mediastreamaudiosourcenode inherits the properties of its parent, audionode. mediastream read only the mediastream used when constructing this mediastreamaudiosourcenode. methods inherits methods from its parent, audionode. exceptions invalidstateerror the stream specified by the mediastream parameter does not contain any audio tracks. usage notes typically, you sho...
...idstateerror 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...
...iosourcenode, which provides similar capabilities but was better-defined upon being added to the specification, so it's more reliable. example in this example, we grab a media (audio + video) stream from navigator.getusermedia, feed the media into a <video> element to play then mute the audio, but then also feed the audio into a mediastreamaudiosourcenode. next, we feed this source audio into a low pass biquadfilternode (which effectively serves as a bass booster), then a audiodestinationnode. the range slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. var pre = document.queryselector('pre'); var video = do...
...And 2 more matches
Media Session API - Web APIs
media session concepts and usage the mediametadata interface lets a web site provide rich metadata to the platform ui for media that is playing. ...
... media session concepts and usage the mediametadata interface lets a web site provide rich metadata to the platform ui for media that is playing. ...
...ior is available. accessing the media session api the primary interface for the media session api is the mediasession interface. rather than creating your own mediasession instance, you access the api using the navigator.mediasession property. for example, to set the current state of the media session to playing: navigator.mediasession.playbackstate = "playing"; interfaces mediametadata allows a web page to provide rich media metadata, for display in a platform ui. mediasession allows a web page to provide custom behaviors, for standard media playback interactions. dictionaries mediaimage a mediaimage object contains information describing an image associated with the media. this might be a cd or dvd cover, a movie poster, a poster frame, or the like. mediapositionstate used...
...And 2 more matches
Transcoding assets for Media Source Extensions - Web APIs
agment 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. sample media if you're looking to follow the steps listed here, but don't have any media to experiment with, you can grab the trailer to big buck bunny [0] here. big buck bunny is licensed under the creative commons attribution 3.0 license. throughout this tutorial, you'll see the filename ...
... media to experiment with, you can grab the trailer to big buck bunny [0] here. big buck bunny is licensed under the creative commons attribution 3.0 license. throughout this tutorial, you'll see the filename trailer_1080p.mov which is the download. [0] (c) copyright 2008, blender foundation / www.bigbuckbunny.org / https://peach.blender.org/about/ tools required when working with mse, the following tools are a must have: ffmpeg — a command-line utility for transcoding your media into the required formats. you can download a version for your system at the download ffmpeg page. extract the executable from the archive file and add it's location to your path statement. osx users can also use homebrew to install ffmpeg. bento4 — a set of command-line utilities for getting asset metada...
...combinations. to check if the browser supports a particular container, you can pass a string of the mime type to the mediasource.istypesupported method: mediasource.istypesupported('audio/mp3'); // false mediasource.istypesupported('video/mp4'); // true mediasource.istypesupported('video/mp4; codecs="avc1.4d4028, mp4a.40.2"'); // true the string is the mime type of the container, optionally followed by a list of codecs. while the mime type is fairly simple to figure out, we can get the codec string using the mp4info utility. currently, mp4 containers with h.264 video 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 contain...
...And 2 more matches
Capabilities, constraints, and settings - Web APIs
ideal: 1.7777777778 } }, audio: { samplesize: 16, channelcount: 2 } }).then(stream => { videoelement.srcobject = stream; }).catch(handleerror); in this example, constraints are applied at getusermedia() time, asking for an ideal set of options with fallbacks for the video. you can specify one or more media input device ids to establish restrictions on which input sources are allowed. to collect a list of the available devices, you can call navigator.mediadevices.enumeratedevices(), then for each device which meets the desired criteria, add its deviceid to the mediaconstraints object that eventually gets passed into getusermedia(). you can also change the constraints of an existing mediastreamtrack on the fly, by calling the track's applyconstraints() method, passing into...
...le properties (as described in the documentation for mediatrackconstraints), while settings are the actual values of each constrainable property at the current time. getting the constraints in effect if at any time you need to fetch the set of constraints that are currently applied to the media, you can get that information by calling mediastreamtrack.getconstraints(), as shown in the example below. function switchcameras(track, camera) { let constraints = track.getconstraints(); constraints.facingmode = camera; track.applyconstraints(constraints); } this function accepts a mediastreamtrack and a string indicating the camera facing mode to use, fetches the current constraints, sets the value of the mediatrackconstraints.facingmode to the specified value, then applies the updated con...
...e pretty simple, and aren't shown here. you can look at the complete example by clicking here. html content <p>experiment with media constraints! edit the constraint sets for the video and audio tracks in the edit boxes on the left, then click the "apply constraints" button to try them out. the actual settings the browser selected and is using are shown in the boxes on the right. ...
...And 2 more matches
Navigator.registerProtocolHandler() - Web APIs
xt message links by passing the "sms" scheme. url a string containing the url of the handler. this url must include %s, as a placeholder that will be replaced with the escaped url to be handled. note: the handler url must us the https scheme. older browsers also supported http. title a human-readable title string for the handler. this will be displayed to the user, such as prompting “allow this site to handle [scheme] links?” or listing registered handlers in the browser’s settings. note: the title has been removed from the spec due to spoofing concerns, but all current browsers still require it. it is recommended to always set the title, since browsers that support the updated spec most likely will be backwards-compatible and still accept the title (but not use it). excep...
...er's url be over https. syntaxerror the %s placeholder is missing from the handler url. permitted schemes for security reasons, registerprotocolhandler() restricts which schemes can be registered. ...
...l. permitted schemes for security reasons, registerprotocolhandler() restricts which schemes can be registered. a custom scheme may be registered as long as: the custom scheme's name begins with web+ the custom scheme's name includes at least 1 letter after the web+ prefix the custom scheme has only lowercase ascii letters in its name. for example, web+burger, as shown in the example below. ...
...And 2 more matches
PaymentAddress - Web APIs
cifying 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 sorting code such as is used in france. note: properties for which values were not specified contain empty strings. obsolete properties the following properties are obsolete and should no longer be used, but may still be present in some browser versions. paymentaddress.languagecode read only a domstring indicating the language code of the address. this identifies the language in which the address is given, and is intended to aid in localization of the display of the address. methods paymentaddress.tojson() a standard serializer...
...rsions. paymentaddress.languagecode read only a domstring indicating the language code of the address. this identifies the language in which the address is given, and is intended to aid in localization of the display of the address. methods paymentaddress.tojson() a standard serializer that returns a json representation of the paymentaddress object's properties. examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options. the first of these three (supportedinstruments in...
...e paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options. the first of these three (supportedinstruments in the example below) contains a data property that has to conform to the structure defined by the basiccardrequest dictionary. const supportedinstruments = [ { supportedmethods: "basic-card", }, ]; const details = { total: { label: "donation", amount: { currency: "usd", value: "65.00" } }, displayitems: [ { label: "original donation amount", amount: { currency: "usd", value: "65.00" }, ...
...And 2 more matches
PerformanceNavigationTiming - Web APIs
ontiming 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. ...
... performanceentry.name read only returns the document's address. performanceentry.starttime read only returns a domhighrestimestamp with a value of "0". performanceentry.duration read only returns a timestamp ...
...-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">performancenavigationtiming</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface extends the following performanceentry properties for navigation performance entry types by qualifying and constraining them as follows: performanceentry.entrytype read only returns "navigation". performanceentry.name read only returns the document's address. performanceentry.starttime read only returns a domhighrestimestamp with a value of "0". performanceentry.duration read only returns a timestamp that is the difference between the performancenavigationtiming.loadeventend and performanceentry.starttime propertie...
...And 2 more matches
Using Performance Timeline - Web APIs
the performance timeline standard defines extensions to the performance interface to support client-side latency measurements within applications. the standard also includes interfaces that allow an application to be notified when specific performance events occur. together, these interfaces can be used to help identify an application's performance bottlenecks. performance extensions performance timeline extends the performance object with three methods that provide different mechanisms to get a set of performance records (metrics), depending on the specified filter criteria. the following example show the usage of these methods getentries(), getentriesbyname() and getentriesbytype(). function log(s) { var o = document.getelementsbytagname("output")[0]; o.innerhtml += s + " <br>"; } f...
...rk" entries named "begin" p = performance.getentriesbyname("begin", "mark"); for (var i=0; i < p.length; i++) { log ("begin and mark [" + i + "]"); print_perf_entry(p[i]); } } performanceentry interface the performanceentry interface encapsulates a single performance entry i.e. a single performance metric. this interface has four properties and a json serializer (tojson(). the following example shows the use of these properties. function print_performanceentry(ev) { var properties = ["name", "entrytype", "starttime", "duration"]; // create a few performance entries performance.mark("start"); do_work(50000); performance.mark("stop"); performance.measure("measure-1"); var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("perfentry[" + ...
... property in window.performance var supported = properties[j] in p[i]; if (supported) { var pe = p[i]; log("... " + properties[j] + " = " + pe[properties[j]]); } else { log("... " + properties[j] + " = not supported"); } } } } this interface also includes a tojson() method that returns the serialization of the performanceentry object. the following examples show the use of this method. function perfentry_tojson() { // create a few performance entries performance.mark("mark-1"); performance.mark("mark-2"); performance.measure("meas-1", "mark-1", "mark-2"); var pelist = performance.getentries(); var pe = pelist[0]; if (pe.tojson === undefined) { log ("performanceentry.tojson() is not supported"); return; } //...
...And 2 more matches
Pointer Lock API - Web APIs
raw mouse movement, locks the target of mouse events to a single element, eliminates limits on how far mouse movement can go in a single direction, and removes the cursor from view. it is ideal for first person 3d games, for example. more than that, the api is useful for any applications that require significant mouse input to control movements, rotate objects, and change entries, for example allowing users to control the viewing angle simply by moving the mouse around without any button clicking. the buttons are then freed up for other actions. other examples include apps for viewing maps or satellite imagery. pointer lock lets you access mouse events even when the cursor goes past the boundary of the browser or screen. for example, your users can continue to rotate or manipulate a 3d mod...
...rrying about leaving the game play area and accidentally clicking another application that would take mouse focus away from the game. basic concepts pointer lock is related to mouse capture. mouse capture provides continued delivery of events to a target element while a mouse is being dragged, but it stops when the mouse button is released. pointer lock is different from mouse capture in the following ways: it is persistent: pointer lock does not release the mouse until an explicit api call is made or the user uses a specific release gesture. it is not limited by browser or screen boundaries. it continues to send events regardless of mouse button state. it hides the cursor. method/properties overview this section provides a brief description of each property and method related to t...
...ent === canvas || document.mozpointerlockelement === canvas) { console.log('the pointer lock status is now locked'); } else { console.log('the pointer lock status is now unlocked'); } the document.exitpointerlock() method is used to exit pointer lock, and like requestpointerlock, works asynchronously using the pointerlockchange and pointerlockerror events, which you'll see more about below. document.exitpointerlock = document.exitpointerlock || document.mozexitpointerlock; // attempt to unlock document.exitpointerlock(); pointerlockchange event when the pointer lock state changes—for example, when calling requestpointerlock(), exitpointerlock(), the user pressing the esc key, etc.—the pointerlockchange event is dispatched to the document. this...
...And 2 more matches
Push API - Web APIs
Web › API › Push API
whether or not the web app is in the foreground, or even currently loaded, on a user agent. this lets developers deliver asynchronous notifications and updates to users that opt in, resulting in better engagement with timely new content. push concepts and usage when implementing pushmanager subscriptions, it is vitally important that you protect against csrf/xsrf issues in your app. see the following articles for more information: cross-site request forgery (csrf) prevention cheat sheet preventing csrf and xsrf attacks for an app to receive push messages, it has to have an active service worker. 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 ne...
...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 necessary to send a message to your application. the endpoint url therefore needs to be kept secret, ...
... a message to your application. the endpoint url therefore needs to be kept secret, or other applications might be able to send push messages to your application. activating a service worker to deliver a push message can result in increased resource usage, particularly of the battery. different browsers have different schemes for handling this, there is currently no standard mechanism. ...
...And 2 more matches
RTCPeerConnection.addIceCandidate() - Web APIs
f the value of the specified object's candidate is either missing or an empty string (""), it signals that all remote candidates have been delivered. the end-of-candidates notification is transmitted to the remote peer using a candidate with an a-line value of end-of-candidates. during negotiation, your app will likely receive many 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 objec...
...a-line, formatted simply like this: a=end-of-candidates deprecated parameters in older code and documentation, you may see a callback-based version of this function. this has been deprecated and its use is strongly discouraged. you should update any existing code to use the promise-based version of addicecandidate() instead. the parameters for this form of addicecandidate() are described below, to aid in updating existing code. successcallback a function to be called when the ice candidate has been successfully added. this function receives no input parameters and doesn't return a value. failurecallback a function to be called if attempting to add the ice candidate fails. receives as input a domexception object describing why failure occurred. return value a promise which ...
...exception object describing why failure occurred. return value a promise which is fulfilled when the candidate has been successfully added to the remote peer's description by the ice agent. the promise does not receive any input parameters. exceptions when an error occurs while attempting to add the ice candidate, the promise returned by this method is rejected, returning one of the errors below as the name attribute in the specified domexception object passed to the rejection handler. typeerror the specified candidate's sdpmid and sdpmlineindex are both null. invalidstateerror the rtcpeerconnection currently has no remote peer established (remotedescription is null). operationerror this can happen for a number of reasons: the value specified for sdpmid is non-null and doesn'...
...And 2 more matches
Request() - Web APIs
Web › API › Request › Request
the request() constructor creates a new request object. syntax var myrequest = new request(input[, init]); parameters input defines the resource that you wish to fetch. this can either be: a usvstring containing the direct url of the resource you want to fetch. a request object, effectively creating a copy. note the following behavioural updates to retain security while making the constructor less likely to throw exceptions: if this object exists on another origin to the constructor call, the request.referrer is stripped out. if this object has a request.mode of navigate, the mode value is converted to same-origin. init optional an options object containing any custom settings that you want to apply to the request. the possible options are: method: t...
...est using the get or head method cannot have a body. mode: the mode you want to use for the request, e.g., cors, no-cors, same-origin, or navigate. the default is cors. credentials: the request credentials you want to use for the request: omit, same-origin, or include. the default is same-origin. cache: the cache mode you want to use for the request. redirect: the redirect mode to use: follow, error, or manual. the default is follow. referrer: a usvstring specifying no-referrer, client, or a url. the default is about:client. integrity: contains the subresource integrity value of the request (e.g., sha256-bpfbw7ivv8q2jlit13fxdyae2tjllusrsz273h2nfse=). errors type description typeerror since firefox 43, request() will throw a typeerror if the url h...
... (see fetch request live) we create a new request object using the constructor, then fetch it using a globalfetch.fetch call. since we are fetching an image, we run body.blob on the response to give it the proper mime type so it will be handled properly, then create an object url of it and display it in an <img> element. ...
...And 2 more matches
Request - Web APIs
Web › API › Request
contains the subresource integrity value of the request (e.g., sha256-bpfbw7ivv8q2jlit13fxdyae2tjllusrsz273h2nfse=). request.method read only contains the request's method (get, post, etc.) request.mode read only contains the mode of the request (e.g., cors, no-cors, same-origin, navigate.) request.redirect read only contains the mode for how redirects are handled. ...
...read only contains the mode for how redirects are handled. it may be one of follow, error, or manual. request.referrer read only contains the referrer of the request (e.g., client). request.referrerpolicy read only contains the referrer policy of the request (e.g., no-referrer). request.url read only contains the url of the request. request implements body, so it also inherits the following properties: body read only a simple getter used to expose a readablestream of the body contents. bodyused read only stores a boolean that declares whether the body has been used in a response yet. methods request.clone() creates a copy of the current request object. ...
... body.blob() returns a promise that resolves with a blob representation of the request body. body.formdata() returns a promise that resolves with a formdata representation of the request body. ...
...And 2 more matches
Using the Resource Timing API - Web APIs
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 of the fetch and request start phases ...
...esource including the response header fields plus the response payload body. the encodedbodysize property returns the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. decodedbodysize returns the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings. the following example demonstrates using these three properties. function display_size_data(){ // check for support of the performanceresourcetiming.*size properties and print their values // if supported. if (performance === undefined) { console.log("= display size data: performance not supported"); return; } var list = performance.getentriesbytype("resource"); if (list === undefined)...
... developer manage the buffer size, resource timing defines two methods that extend the performance interface. the clearresourcetimings() method removes all "resource" type performance entries from the browser's resource performance entry buffer. the setresourcetimingbuffersize() method sets the resource performance entry buffer size to the specified number of resource performance entries. the following example demonstrates the usage of these two methods. function clear_resource_timings() { if (performance === undefined) { console.log("= performance.clearresourcetimings(): peformance not supported"); return; } // check if performance.clearresourcetiming() is supported console.log ("= print performance.clearresourcetimings()"); var supported = typeof performance.clearresourc...
...And 2 more matches
Storage Access API - Web APIs
the storage access api provides a way for embedded, cross-origin content to gain unrestricted access to storage that it would normally only have access to in a first-party context (we refer to this as an origin’s first-party storage). the api provides methods that allow embedded resources to check whether they currently have access to their first-party storage, and to request access to their first-party storage from the user agent. concepts and usage most browsers implement a number of storage access policies that restrict access to cookies and site data for embedded, cross-origin resources. these restrictions range from giving embedded resources under each top-level origin a unique storage space to outright blocking of storage access when resources are loaded in a third-party ...
... solve this problem; embedded cross-origin content can request unrestricted access to its first-party storage on a site-by-site basis via the document.requeststorageaccess() method, and check whether it already has access via the document.hasstorageaccess() method. in addition, sandboxed <iframe>s cannot be granted storage access by default for security reasons. the api therefore also adds the allow-storage-access-by-user-activation sandbox token. the embedding website needs to add this to allow storage access requests to be successful, along with allow-scripts and allow-same-origin to allow it to call the api, and execute in an origin that can have cookies: <iframe sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"> ... </i...
...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. ...
...And 2 more matches
Using readable streams - Web APIs
5+ 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 readable stream. this mixin is implemented by bo...
...s is the standard pattern you’ll see when using stream readers: you write a function that starts off by reading the stream. if there is no more stream to read, you return out of the function. if there is more stream to read, you process the current chunk then run the function again. you keep running the function recursively until there is no more stream to read, in which case step 2 is followed. creating your own custom readable stream the simple stream pump example we’ve been studying throughout this article includes a second part — once we’ve read the image from the fetch body in chunks, we then enqueue them into another, custom stream of our own creation. how do we create this? the readablestream() constructor. the readablestream() constructor it is easy to read from a s...
...etch body in chunks, we then enqueue them into another, custom stream of our own creation. how do we create this? the readablestream() constructor. the readablestream() constructor it is easy to read from a stream when the browser provides it for you as in the case of fetch, but sometimes you need to create a custom stream and populate it with your own chunks. the readablestream() constructor allows you to do this via a syntax that looks complex at first, but actually isn’t too bad. the generic syntax skeleton looks like this: const stream = new readablestream({ start(controller) { }, pull(controller) { }, cancel() { }, type, autoallocatechunksize }, { highwatermark, size() }); the constructor takes two objects as parameters. the first object is required, and cre...
...And 2 more matches
Streams API - Web APIs
concepts and usage streaming involves breaking a resource that you want to receive over a network down into small chunks, then processing it bit by bit. 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. ...
...eams readablestream represents a readable stream of data. it can be used to handle response streams of the fetch api, or developer-defined streams (e.g. a custom readablestream() constructor). readablestreamdefaultreader 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 u...
...yte 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 given a corresponding writablestreamdefaultcontroller instance to manipulate. related stream apis and operations bytelengthqueuingstrategy provides a built-in byte length queuing strategy that can be used when constructing streams. countqueuingstrategy provides a built-in chunk counting queu...
...And 2 more matches
TextRange - Web APIs
Web › API › TextRange
a textrange object represents a fragment of text in a document, similar to the standard defined range interface. this object is used to represent a specific piece of text in the document. ...
...ng the current state of the specified command. you can also see document.querycommandstate(). textrange.querycommandvalue() returns the domstring indicating the current value of the specified command. you can also see document.querycommandvalue(). textrange.scrollintoview() scroll the range to the visible range (top or bottom). it can be used as an alternative to element.scrollintoview in the lower version of ie. textrange.select() select the current range (i.e. the blue selection seen by the user). textrange.setendpoint() sets the end point of the current range based on the bounds of other textrange. example the following example is valid under ie9. the example gets the textrange through document.selection, and sets the specified element to be selected. ie9 supports the standard a...
... element = document.getelementbyid("test"); range.movetoelementtext(element); range.select(); // selected "sometexttobeselected" <!doctype html> <html> <head> <title>textrange example</title> </head> <body> <p id="test">sometexttobeselected</p> </body> </html> notes use textrange to operate the selection valid only under ie9. the selection interface should be used first, if the browser allows it. document.selection property returns a non-standard selection object, and the selection.createrange() method creates a textrange object consistent with the currently selection. var sel = document.selection; var range = sel.createrange(); alert(range.text); // output plaintext of the selection note that the createrange method does not create a reference. if you want to select the modified ...
...And 2 more matches
WebGLRenderingContext.vertexAttribPointer() - Web APIs
each component in the array. possible values: gl.byte: signed 8-bit integer, with values in [-128, 127] gl.short: signed 16-bit integer, with values in [-32768, 32767] gl.unsigned_byte: unsigned 8-bit integer, with values in [0, 255] gl.unsigned_short: unsigned 16-bit integer, with values in [0, 65535] gl.float: 32-bit ieee floating point number when using a webgl 2 context, the following values are available additionally: gl.half_float: 16-bit ieee floating point number normalized a glboolean specifying whether integer data values should be normalized into a certain range when being cast to a float. for types gl.byte and gl.short, normalizes the values to [-1, 1] if true. for types gl.unsigned_byte and gl.unsigned_short, normalizes the values to [0, ...
...if true. for types gl.float and gl.half_float, this parameter has no effect. stride a glsizei specifying the offset in bytes between the beginning of consecutive vertex attributes. cannot be larger than 255. if stride is 0, the attribute is assumed to be tightly packed, that is, the attributes are not interleaved but each attribute is in a separate block, and the next vertex' attribute follows immediately after the current vertex. offset a glintptr specifying an offset in bytes of the first component in the vertex attribute array. must be a multiple of the byte length of type. return value none. exceptions a gl.invalid_value error is thrown if offset is negative. a gl.invalid_operation error is thrown if stride and offset are not multiples of the size of the data type. a gl...
...aybuffer at runtime, you have free choice on how to structure the memory. for highest performance, interleave the attributes and use the smallest data type that still accurately represents your geometry. the maximum number of vertex attributes depends on the graphics card, and you can call gl.getparameter(gl.max_vertex_attribs) to get this value. on high-end graphics cards, the maximum is 16, on lower-end graphics cards, the value will be lower. attribute index for each attribute, you must specify its index. this is independent from the location inside the array buffer, so your attributes can be sent in a different order than how they are stored in the array buffer. you have two options: either you specify the index yourself. in this case, you call gl.bindattriblocation() to connect a n...
...And 2 more matches
Starting up and shutting down a WebXR session - Web APIs
le and your document's environment. thus the simplest code that fetches the xrsystem object is: const xr = navigator.xr; the value of xr will be null or undefined if webxr isn't available. webxr availability as a new and still in development api, webxr support is limited to specific devices and browsers; and even on those, it may not be enabled by default. there may be options available to allow you to experiment with webxr even if you don't have a compatible system, however. webxr polyfill the team designing the webxr specification has published a webxr polyfill which you can use to simulate webxr on browsers which don't have support for the webxr apis. if the browser supports the older webvr api, that is used. otherwise, the polyfill falls back to an implementation which uses google'...
...he readme file and make sure you're aware of the limitations before you begin. important: you should always test your code on actual ar and/or vr hardware before releasing or shipping a product! emulated, simulated, or polyfilled environments are not an adequate substitute for actual testing on physical devices. getting the extension download the webxr api emulator for your supported browser below: google chrome mozilla firefox the source code for the 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...
...ages you present. immersive-ar an augmented reality session in which images are added to the real world using a headset or similar apparatus. this option is not yet widely supported, as the ar specification is in flux. inline an on-screen presentation of the xr imagery within the context of the document window. if the session couldn't be created for some reason—such as feature policy disallowing its use or the user declining to grant permission to use the headset—the promise gets rejected. so a more complete function that starts up and returns a webxr session could look like this: async function createimmersivesession(xr) { try { session = await xr.requestsession("immersive-vr"); return session; } catch(error) { throw error; } } this function returns the new xrs...
...And 2 more matches
WebXR Device API - Web APIs
rs. webxr-compatible devices include fully-immersive 3d headsets with motion and orientation tracking, eyeglasses which overlay graphics atop the real world scene passing through the frames, and handheld mobile phones which augment reality by capturing the world with a camera and augment that scene with computer-generated imagery. ...
...he center of the room or surface. xrview represents a single view into the xr scene for a particular frame. each xrview corresponds to the video display surface used to present the scene to the user. for example, a given xr device might have two views: one for the left eye and one for the right. each view has an offset used to shift the position of the view relative to the camera, in order to allow for creating stereographic effects. xrviewport describes a viewport. a viewport is a rectangular portion of a graphic surface. in webxr, a viewport represents the area of a drawing surface corresponding to a particular xrview, such as the portion of the webgl framebuffer used to render one of the two eyes' perspectives on the scene. xrrigidtransform a transform defined using a position and or...
...nd other devices which are explicitly associated with the xr device. other input devices such as keyboards, mice, and gamepads are not presented as xrinputsource instances. xrwebgllayer a layer which serves as a webgl frame buffer into which a scene's view is rendered. using webgl to render the scene gains substantial performance benefits due to graphics acceleration. event interfaces the following interfaces are used to represent the events used by the webxr api. xrinputsourceevent sent when the state of an xrinputsource changes. this can happen, for example, when the position and/or orientation of the device changes, or when buttons are pressed or released. xrinputsourceschangeevent sent to indicate that the set of available input sources has changed for the xrsession. xrreferen...
...And 2 more matches
Using the Web Animations API - Web APIs
m eating itself up before the user has had the chance to click on it, we call animation.pause() on it immediately after it is defined, like so: nommingcake.pause(); we can now use the animation.play() method to run it whenever we’re ready: nommingcake.play(); specifically, we want to link it to alice’s animation, so she gets bigger as the cupcake gets eaten. we can achieve this via the following function: var growalice = function() { // play alice's animation. alicechange.play(); // play the cake's animation. nommingcake.play(); } when a user holds their mouse down or presses their finger on the cake on a touch screen, we can now call growalice to make all the animations play: cake.addeventlistener("mousedown", growalice, false); cake.addeventlistener("touchstart", growa...
...y(); // play the cake's animation. nommingcake.play(); } when a user holds their mouse down or presses their finger on the cake on a touch screen, we can now call growalice to make all the animations play: cake.addeventlistener("mousedown", growalice, false); cake.addeventlistener("touchstart", growalice, false); other useful methods in addition to pausing and playing, we can use the following animation methods: animation.finish() skips to the end of the animation. animation.cancel() aborts the animation and removes its effects. animation.reverse() sets the animation’s playback rate (animation.playbackrate) to a negative value so it runs backward. let’s take a look at playbackrate first — a negative playbackrate will cause an animation to run in reverse. when alice drin...
...listener("touchstart", shrinkalice, false); in through the looking-glass, alice travels to a world where she must run to stay in place — and run twice as fast to move forward! ...
...And 2 more matches
Using IIR filters - Web APIs
button that starts and pauses audio play, and a toggle that turns an iir filter on and off, altering the tone of the sound. it also provides a canvas on which is drawn the frequency response of the audio, so you can see what effect the iir filter has. you can check out the full demo here on codepen. also see the source code on github. it includes some different coefficient values for different lowpass frequencies — you can change the value of the filternumber constant to a value between 0 and 3 to check out the different available effects. browser support iir filters are supported well across modern browsers, although they have been implemented more recently than some of the more longstanding web audio api features, like biquad filters. the iirfilternode the web audio api now comes w...
... signal processing. the other type is fir — finite impulse response filter. there's a really good overview to iif filters and fir filters here. a biquad filter is actually a specific type of infinite impulse response filter. it's a commonly-used type and we already have it as a node in the web audio api. if you choose this node the hard work is done for you. ...
...and this is where the iir filter node is useful — you can create your own if none of the alaready available settings is right for what you want. ...
...And 2 more matches
WindowOrWorkerGlobalScope.fetch() - Web APIs
redentials the request credentials you want to use for the request: omit, same-origin, or include. to automatically send cookies for the current domain, this option must be provided. starting with chrome 50, this property also takes a federatedcredential instance or a passwordcredential instance. cache the cache mode you want to use for the request. redirect the redirect mode to use: follow (automatically follow redirects), error (abort with an error if a redirect occurs), or manual (handle redirects manually). in chrome the default is follow (before chrome 47 it defaulted to manual). referrer a usvstring specifying the referrer of the request. this can be a same-origin url, about:client, or an empty string. referrerpolicy specifies the referrer policy to use for the request...
...ecifies the referrer policy to use for the request. may be one of no-referrer, no-referrer-when-downgrade, same-origin, origin, strict-origin, origin-when-cross-origin, strict-origin-when-cross-origin, or unsafe-url. integrity contains the subresource integrity value of the request (e.g., sha256-bpfbw7ivv8q2jlit13fxdyae2tjllusrsz273h2nfse=). keepalive the keepalive option can be used to allow the request to outlive the page. fetch with the keepalive flag is a replacement for the navigator.sendbeacon() api. signal an abortsignal object instance; allows you to communicate with a fetch request and abort it if desired via an abortcontroller. return value a promise that resolves to a response object. exceptions aborterror the request was aborted due to a call to the abortco...
...ee fetch request live) we create a new request object using the relevant constructor, then fetch it using a fetch() call. since we are fetching an image, we run body.blob() on the response to give it the proper mime type so it will be handled properly, then create an object url of it and display it in an <img> element. ...
...And 2 more matches
Using the alert role - Accessibility
le must be used sparingly and only in situations where the user's immediate attention is required. dynamic changes that are less urgent should use a less aggressive method, such as aria-live="polite" or other live region roles. possible effects on user agents and assistive technology when the alert role is added to an element, or such an element becomes visible, the user agent should do the following: expose the element as having an alert role in the operating system's accessibility api. fire an accessible alert event using the operating system's accessibility api if it supports it. assistive technology products should listen for such an event and notify the user accordingly: screen readers may interrupt current output (whether it's speech or braille) and immediately announce or d...
...r braille) and immediately announce or display the alert message. screen magnifiers may visually indicate that an alert occurred and what the alert text was. note: opinons 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: adding the role in the html code the snippet below shows how the alert role is added directly into the html source code. the moment the element finishes loading the screen reader should be notified of the alert. if the element was already in the original source code when the page loaded, the screen reader will announce the error immediately after announcing the page title. <h2 role="alert">your form could not be submitted because of 3 validation...
... note: the same result can be achieved with less code when using a script library like jquery: $("<p role='alert'>you must agree with our terms of service to create an account.</p>").appendto(document.body); example 3: adding alert role to an existing element sometimes it's useful to add an alert role to an element that is already visible on the page rather than creating a new element. ...
...And 2 more matches
Architecture - Accessibility
to piece its text representation together. everything else uses whatever nsaccessible-derived implementation that's appropriate. if it has text siblings, then it gets exposed as the unicode char for an embedded object, which is '\xfffc' within the parent nshypertextaccessible. in addition, nsiaccessiblehyperlink is implemented on any non-text child inside a container that also has text. this allows at's to find its position within that text, because the hyperlink interface exposes a start and end index. in fact, the end index will always be 1 larger than the start index, because the object is always represented by a single '\xfffc' character. if you want to know that something is really a link, check to see if it is role_link. html containers are implemented by nshypertextaccessible. the...
...sed, but are redundant with the information in the parent object's nsiaccessibletext. this is done for backward compatibility with older msaa clients which didn't have access to a text interface. the children of a hypertext object are a superset of the links it exposes. the new system makes it easier to show caret positions etc., which will be an improvement in ia2 over msaa. example take the following html code: <div>hello<a href="http://www.mozilla.org/access">my link<img src="image.gif">is cool</a>bye</div> both the <a> and <img> are hyperlinks also, both the <div> and <a> are hypertexts so the <a> is both a hypertext and a hyperlink, because it contains text and is contained within text. this means that we have an exact mirror to the dom, but text lives in the parents instead of in the...
...irst character until a non-embed is found. otherwise, continue processing with offset = the index at the end of the line. if the character at the offset is an embed, proceed to its corresponding accessible and recurse on the first character until a non-embed is found. otherwise, the offset marks the start of a new line. navigating to the next word follows a similar pattern. navigating previous requires returning to the embed character in the parent accessible when the point of regard reaches the end of text in the corresponding child accessible for the embed. see http://svn.gnome.org/viewcvs/lsr/tru...py?view=markup for a bsd implementation. (e) to grab a subtree of content: although under windows text content is still exposed in leaf nodes of ro...
...And 2 more matches
Understandable - Accessibility
ot accessible via keyboard, nor are they reliably read out by screenreaders. a better way to handle this is to again provide links to glossary pages containing the acronym expansion and explanation, or at the very least include them in the surrounding text in context. see abbreviations. 3.1.5 reading level (aaa) if text is provided that requires a higher reading level that lower secondary education level (typically children around 11-14 years old), provide 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...
...an alternative style for poetic effect), or they have to be written in a strict style (e.g. ...
...s 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 a control that allows the reader to play back an audio file containing the correct pronounciation, and it also makes sense to include a textual pronounciation guide after difficult words, in the same way that you find in dictionary entries. see video and audio content, and pronunciation guide for english dictionary note: also see the wcag description for guideline 3.1 readable: make text content readab...
...And 2 more matches
Coordinate systems - CSS: Cascading Style Sheets
gin is located. dimensions in the coordinate systems used by web technologies, convention dictates that the horizontal offset is called the x-coordinate, where a negative value indicates a position to the left of the origin and a positive value is to the right of the origin. the y-coordinate specifies the vertical offset, with a negative value being above the origin and a positive value being below the origin. on the web, the default origin is the top-left corner of a given context (with positive y-coordinate values being below the origin). note that this is unlike most mathematical models, where the origin is at the bottom-left corner, with positive y-coordinate values being above the origin. when drawing 3d graphics, or using a third dimension to layer objects from front to back, the z-...
...away from the viewer if positive and toward the viewer if negative. it's actually possible to change the definitions 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 distan...
...e implementation is then quite simple. the variables idx and idy are set to strings with the names of the properties corresponding to the coordinates in the given coordinate system. for example, if the value of type is "page", then idx is "pagex" and idy is "pagey". handling the mouse events setcoords() is called by the event handler for the various mouse events, named update(); this is shown below. function update(e) { setcoords(e, "offset"); setcoords(e, "client"); setcoords(e, "page"); setcoords(e, "screen"); } inner.addeventlistener("mouseenter", update, false); inner.addeventlistener("mousemove", update, false); inner.addeventlistener("mouseleave", update, false); the event handler is in the update() method. it simply calls setcoords() once for each coordinate system, passin...
...And 2 more matches
Border-radius generator - CSS: Cascading Style Sheets
roup:before, .group:after { content: ""; display: table; } .group:after { clear:both; } .group { zoom: 1; /* for ie 6/7 (trigger haslayout) */ } /* grid column setup * ========================================================================== */ .col { display: block; float:left; margin: 1% 0 1% 1.6%; } .col:first-child { margin-left: 0; } /* all browsers except ie6 and lower */ /* * ui component */ .ui-input-slider-container { height: 20px; margin: 10px 0; font-family: "segoe ui", arial, helvetica, sans-serif; -moz-user-select: none; user-select: none; } .ui-input-slider-container * { float: left; height: 100%; line-height: 100%; } /* input slider */ .ui-input-slider > input { margin: 0; padding: 0; width: 50px; text-align: center; -moz-box-si...
...lect: none; } .ui-input-slider-container * { float: left; height: 100%; line-height: 100%; } /* input slider */ .ui-input-slider > input { margin: 0; padding: 0; width: 50px; text-align: center; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .ui-input-slider-info { width: 90px; padding: 0px 10px 0px 0px; text-align: right; text-transform: lowercase; } .ui-input-slider-left, .ui-input-slider-right { width: 16px; cursor: pointer; background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center left no-repeat; } .ui-input-slider-right { background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center right no-repeat; } .ui-input-slider-name { width: 90px; padding: 0 10px 0 0; text-align: right; text-tra...
...} .ui-input-slider-left, .ui-input-slider-right { width: 16px; cursor: pointer; background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center left no-repeat; } .ui-input-slider-right { background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center right no-repeat; } .ui-input-slider-name { width: 90px; padding: 0 10px 0 0; text-align: right; text-transform: lowercase; } .ui-input-slider-btn-set { width: 25px; background-color: #2c9fc9; border-radius: 5px; color: #fff; font-weight: bold; line-height: 14px; text-align: center; } .ui-input-slider-btn-set:hover { background-color: #379b4a; cursor: pointer; } /* * ui component */ /* checkbox */ .ui-checkbox { text-align: center; font-size: 16px; font-family: "segoe ui", arial, helvetica, s...
...And 2 more matches
Spanning and Balancing Columns - CSS: Cascading Style Sheets
he property column-span with a value of all. this will cause the element to span all of the columns. any descendant element of the multicol container may become a spanner including both direct and indirect children. for example, a heading nested directly inside the container could become a spanner, as could a heading nested inside a section nested inside the multicol container. in the example below, the h2 element is set to column-span: all and spans all of the columns. in this second example, the heading is inside an <article> element, yet still spans the content as expected. when a spanner is introduced, it breaks the flow of columns and columns restart after the spanner, effectively creating a new set of column boxes. the content does not jump over a spanning element. limitations ...
...the value none is the initial value and means the item does not span, remaining within a column. the value all means the item spans all of the columns. ...
...pan, remaining within a column. the value all means the item spans all of the columns. you cannot cause an item to span two out of three columns for example. things to watch out for if the spanning element is inside another element which has margins, padding and a border or a background color, it is possible to end up with the top of the box appearing above the spanner and the rest displaying below, as shown in the next example. for this reason, some care should be taken when deciding to make an element a spanner and ensure this scenario is accounted for. additionally, if a spanning element appears later in the content it can cause unexpected or unwanted behaviour when there is not enough content to create columns after the spanner. use spanning carefully and test at various breakpoints ...
...And 2 more matches
Using feature queries - CSS: Cascading Style Sheets
ule, which also contains the media query @media rule; when you use feature queries, you will find they behave in a similar way to media queries. the difference is that with a media query you are testing something about the environment in which the web page is running, whereas with feature queries you are testing browser support for css features. a feature query consists of the @supports rule, followed by the property name and value you would like to test for. you may not test for a bare property name such as display; the rule requires a property name and a value: @supports (property: value) { css rules to apply } if you want to check if a browser supports the row-gap property, for example, you would write the following feature query. it doesn't matter which value you use in a lot of case...
...are often additional values added to properties in css, and so the fact that you have to test for property and value means that you can detect support for these values. testing for lack of support in addition to asking the browser if it supports a feature, you can test for the opposite by adding in the not keyword: @supports not (property: value) { css rules to apply } the css inside the following example feature query will run if the browser does not support row-gap. testing for more than one feature you may need to test support for more than one property in your feature query. to do so, you can include a list of features to test for, separated by and keywords: @supports (property1: value) and (property2: value) { css rules to apply } for example, if the css you want to run req...
...to test support for more than one property in your feature query. to do so, you can include a list of features to test for, separated by and keywords: @supports (property1: value) and (property2: value) { css rules to apply } for example, if the css you want to run requires that the browser supports css shapes and css grid, you could create a rule which checks for both of these things. the following rule will only return true if both shape-outside: circle() and display: grid are supported by the browser. you can also use or, if one property out of a selection could match to enable the css you want to use: @supports (property1: value) or (property2: value) { css rules to apply } this can be particularly useful if a feature is vendor prefixed, as you can test for the standard propert...
...And 2 more matches
Backwards Compatibility of Flexbox - CSS: Cascading Style Sheets
candidate recommendation that we have today. as a candidate recommendation we should not see large changes at this point to the spec, however this has not been the case with past flexbox iterations. flexbox was implemented in an experimental way in several web browsers. at the time the method of creating experimental implementations was to use a vendor prefix. the idea of these prefixes was to allow implementations of the spec to be tested and explored by browser engineers and web developers alike without clashing with other implementations. the idea was not to use the experimental implementations in production code. however, prefixes ultimately were used in production code, and changes to the experimental specification caused people to need to update their sites to keep up. in 2009, the sp...
... display property, when needing to support very old browsers which do not support flexbox at all, fallbacks can be created by overwriting one layout method with another. the specification defines what happens if you use other layout methods on an element which then becomes a flex item. floated items “float and clear do not create floating or clearance of flex item, and do not take it out-of-flow.” - 3. flex containers in the following live example, i have floated two blocks and then set display: flex on the container. the items are now flex items, which means they stretch to equal height. any float behaviour does not apply. you can test the fallback behaviour by removing display: flex from the wrapper. display: inline-block once an inline-block item becomes a flex item, it is bl...
...ne-block like preserving white space between items no longer applies. remove display: flex to see the fallback behavior. you'll see white space added between the items, which is what happens when using display: inine-block as it prefers white space like other inline items. display: table- the css table display properties are potentially very useful as a fallback, due to the fact that they allow design patterns such as full height columns and vertical centering and work back as far as internet explorer 8. if you use display: table-cell on an item in your html it takes on the styling of an html table cell. css creates anonymous boxes to represent these items so that you do not need to wrap each item in a wrapper to represent the html table row, and a second one to represent the table ele...
...And 2 more matches
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
n has. there are also substantial differences between what shipped in ie10 and the current specification, even where the properties and values appear the same. this early implementation is also the version of grid layout implemented in edge up to version 15. the ie/edge (≤15) version of the specification is prefixed with an -ms prefix and the properties implemented in ie/edge (≤15) are as follows: grid-template-columns as -ms-grid-columns grid-template-rows as -ms-grid-rows grid-row-start as -ms-grid-row grid-column-start as -ms-grid-column align-self as -ms-grid-row-align justify-self as -ms-grid-column-align the ie version has additional properties not required in the new specification of -ms-grid-column-span and -ms-grid-row-span. this version does not include auto-placement...
...r method. overwriting of legacy methods with grid layout works surprisingly well, due to the way grid interacts with these other methods. floats we have typically used floats to create multiple column layouts. if you have floated an item, which is also a grid item in a supporting browser, the float will no longer apply to the item. the fact is that a grid item takes precedence. in the example below, i have a simple media object. in a non-supporting browser, i use float, however i have also defined the container as a grid container, in order to use the alignment properties that are implemented in css grids. the float no longer applies, and i can use the css box alignment property align-self to align my content to the end of the container: * {box-sizing: border-box;} img { max-width: 1...
... float: left; width: 150px; margin-right: 20px; } .media .text { padding: 10px; align-self: end; } <div class="media"> <div class="image"><img src="https://udn.realityripple.com/samples/89/f993f273dd.png" alt="placeholder"></div> <div class="text">this is a media object example. i am using floats for older browsers and grid for new ones.</div> </div> the image below shows the media object in a non-supporting browser on the left, and a supporting one on the right: using feature queries the above example is very simple, and we can get away without needing to write code that would be a problem to browsers that do not support grid, and legacy code is not an issue to our grid supporting browsers. however, things are not always so simple. in this next example...
...And 2 more matches
Grid template areas - CSS: Cascading Style Sheets
rid-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 location of that area in the value of the grid-template-areas property. you can choose what you would like to name your area. for example, if i wish to create the layout shown below i can identify four main areas. a header a footer a sidebar the main content with the grid-area property i can assign each of these areas a name. this will not yet create any layout, but we now have named areas to use in a layout. .header { grid-area: hd; } .footer { grid-area: ft; } .content { grid-area: main; } .sidebar { grid-area: sd; } having defined these names...
...rties in one go, they also act to reset things to their initial values that you do not, or cannot set in the shorthand. therefore if you use a shorthand, be aware that it may reset things you have applied elsewhere. the two shorthands for the grid container are the explicit grid shorthand grid-template and the grid definition shorthand grid. ...
...tion shorthand grid. grid-template the grid-template property sets the following properties: grid-template-rows grid-template-columns grid-template-areas the property is referred to as the explicit grid shorthand because it is setting those things that you control when you define an explicit grid, and not those which impact any implicit row or column tracks that might be created. the following code creates a layout using grid-template that is the same as the layout created earlier in this guide. .wrapper { display: grid; grid-template: "hd hd hd hd hd hd hd hd hd" minmax(100px, auto) "sd sd sd main main main main main main" minmax(100px, auto) "ft ft ft ft ft ft ft ft ft" minmax(100px, auto) / 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1f...
...And 2 more matches
The stacking context - CSS: Cascading Style Sheets
y this space in priority order based on element attributes. the stacking context in the previous part of this article, using z-index, the rendering order of certain elements is influenced by their z-index value. this occurs because these elements have special properties which cause them to form a stacking context. a stacking context is formed, anywhere in the document, by any element in the following scenarios: root element of the document (<html>). element with a position value absolute or relative and z-index value other than auto. element with a position value fixed or sticky (sticky for all mobile browsers, but not older desktop). element that is a child of a flex (flexbox) container, with z-index value other than auto. element that is a child of a grid (grid) container, with z-...
...sticky for all mobile browsers, but not older desktop). element that is a child of a flex (flexbox) container, with z-index value other than auto. element that is a child of a grid (grid) container, with z-index value other than auto. element with a opacity value less than 1 (see the specification for opacity). element with a mix-blend-mode value other than normal. element with any of the following properties with value other than none: transform filter perspective clip-path mask / mask-image / mask-border element with a isolation value isolate. element with a -webkit-overflow-scrolling value touch. element with a will-change value specifying any property that would create a stacking context on non-initial value (see this post). element with a contain value of ...
...e hierarchy of html elements because only certain elements create stacking contexts. we can say that elements that do not create their own stacking contexts are assimilated by the parent stacking context. the example in this example, every positioned element creates its own stacking context, because of their positioning and z-index values. the hierarchy of stacking contexts is organized as follows: root div #1 div #2 div #3 div #4 div #5 div #6 it is important to note that div #4, div #5 and div #6 are children of div #3, so stacking of those elements is completely resolved within div#3. once stacking and rendering within div #3 is completed, the whole div #3 element is passed for stacking in the root element with respect to its sibling's...
...And 2 more matches
Shapes from box values - CSS: Cascading Style Sheets
a straightforward way to create a shape is to use a value from the css box model. this article explains how to do this. the box values allowable as a shape value are: content-box padding-box border-box margin-box the border-radius values are also supported, this means that you can have something in your page with a curved border, and your shape can follow the created shape. css box model the values listed above correspond to the various parts of the css box model. a box in css has content, padding, border, and margin. by using box values for shapes we can wrap our content around the edges defined by these values. ...
...orted, this means that you can have something in your page with a curved border, and your shape can follow the created shape. css box model the values listed above correspond to the various parts of the css box model. a box in css has content, padding, border, and margin. by using box values for shapes we can wrap our content around the edges defined by these values. in all of the examples below i am using an element which has padding, a border, and a margin defined in order that you can see the different ways in which content will flow. ...
... defined by these values. in all of the examples below i am using an element which has padding, a border, and a margin defined in order that you can see the different ways in which content will flow. margin-box the margin-box is the shape defined by the outside margin edge and includes the corner radius of the shape, should border-radius have been used in defining the element. in the example below, we have a circular purple item which is a <div> with a height, width, and background colour. the border-radius property has been used to create a circle by setting border-radius: 50%. as the element has a margin, you can see that the content is flowing around the circular shape and the margin applied to it. border-box the border-box value is the shape defined by the outside border edge. this...
...And 2 more matches
Microsoft CSS extensions - CSS: Cascading Style Sheets
(avoid using on websites) note: these properties will only work in microsoft applications, and are not on a standards track. ...
... websites) note: these properties will only work in microsoft applications, and are not on a standards track. ...
...ock-progression -ms-content-zoom-chaining -ms-content-zooming -ms-content-zoom-limit -ms-content-zoom-limit-max -ms-content-zoom-limit-min -ms-content-zoom-snap -ms-content-zoom-snap-points -ms-content-zoom-snap-type -ms-filter -ms-flow-from -ms-flow-into -ms-high-contrast-adjust -ms-hyphenate-limit-chars -ms-hyphenate-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-rail...
...And 2 more matches
Syntax - CSS: Cascading Style Sheets
Web › CSS › Syntax
the css syntax reflects this goal and its basic building blocks are: the property which is an identifier, that is a human-readable name, that defines which feature is considered. the value which describe how the feature must be handled by the engine. each property has a set of valid values, defined by a formal grammar, as well as a semantic meaning, implemented by the browser engine. css declarations setting css properties to specific values is the core function of the css language. ...
...t, and to style it. both properties and values are case-insensitive by default in css. the pair is separated by a colon, ':' (u+003a colon), and white spaces before, between, and after properties and values, but not necessarily inside, are ignored. there are more than 100 different properties in css and a nearly infinite number of different values. not all pairs of properties and values are allowed and each property defines what are the valid values. when a value is not valid for a given property, the declaration is deemed invalid and is wholly ignored by the css engine. css declaration blocks declarations are grouped in blocks, that is in a structure delimited by an opening brace, '{' (u+007b left curly bracket), and a closing one, '}' (u+007d right curly bracket). blocks sometimes can...
...emicolon). 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 attribute. css rulesets if style sheets could only apply a declaration to each element of a web page, they would be pretty useless. the real goal is to apply different declarations to different parts of the document. css ...
...And 2 more matches
align-content - 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. this property has no effect on single line flex containers (i.e. ones with flex-wrap: nowrap). ...
... end the items are packed flush to each other against the end edge of the alignment container in the cross ...
...s than the size of the alignment container, any auto-sized items have their size increased equally (not proportionally), while still respecting the constraints imposed by max-height/max-width (or equivalent functionality), so that the combined size exactly fills the alignment container along the cross axis. safe used alongside an alignment keyword. if the chosen keyword means that the item overflows the alignment container causing data loss, the item is instead aligned as if the alignment mode were start. unsafe used alongside an alignment keyword. regardless of the relative sizes of the item and alignment container and whether overflow which causes data loss might happen, the given alignment value is honored. formal definition initial valuenormalapplies tomulti-line flex containersinh...
...And 2 more matches
align-self - CSS: Cascading Style Sheets
normal the effect of this keyword is dependent of the layout mode we are in: in absolutely-positioned layouts, the keyword behaves like start on replaced absolutely-positioned boxes, an...
... end side in the cross axis. flex-start the cross-start margin edge of the flex item is flushed with the cross-start edge of the line. flex-end the cross-end margin edge of the flex item is flushed with the cross-end edge of the line. center the flex item's margin box is centered within the line on the cross-axis. if the cross-size of the item is larger than the flex container, it will overflow equally in both directions. baseline first baseline last baseline specifies participation in first- or last-baseline alignment: aligns the alignment baseline of the box’s first or last baseline set with the corresponding baseline in the shared first or last baseline set of all the boxes in its baseline-sharing group. the fallback alignment for first baseline is start, the one for last base...
...s along the cross axis is less than the size of the alignment container and the item is auto-sized, its size is increased equally (not proportionally), while still respecting the constraints imposed by max-height/max-width (or equivalent functionality), so that the combined size of all auto-sized items exactly fills the alignment container along the cross axis. safe if the size of the item overflows the alignment container, the item is instead aligned 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 ...
...And 2 more matches
animation-timing-function - CSS: Cascading Style Sheets
perty. as a result, an animation-timing-function specified on the 100% or to keyframe will never be used. values <timing-function> the timing function that corresponds to a given animation, as determined by animation-name. the non-step keyword values (ease, linear, ease-in-out, etc.) each represent cubic bézier curve with fixed four point values, with the cubic-bezier() function value allowing for a non-predefined value. the step timing functions divides the input time into a specified number of intervals that are equal in length. it is defined by a number of steps and a step position. ease equal to cubic-bezier(0.25, 0.1, 0.25, 1.0), the default value, increases in velocity towards the middle of the animation, slowing back down at the end. linear equal to cubic-bezier(0.0, 0.
...of intervals that are equal in length. it is defined by a number of steps and a step position. ease equal to cubic-bezier(0.25, 0.1, 0.25, 1.0), the default value, increases in velocity towards the middle of the animation, slowing back down at the end. linear equal to cubic-bezier(0.0, 0.0, 1.0, 1.0), animates at an even speed. ease-in equal to cubic-bezier(0.42, 0, 1.0, 1.0), starts off slowly, with the speed of the transition of the animating properting increasing until complete. ease-out equal to cubic-bezier(0, 0, 0.58, 1.0), starts quickly, slowing down the animation continues. • ease-in-out equal to cubic-bezier(0.42, 0, 0.58, 1.0), with the animating properties slowly transitioning, speeding up, and then slowing down again. cubic-bezier(p1, p2, p3, p4) an author defined...
...stops along the transition, displaying each stop for equal lengths of time. for example, if n is 5, there are 5 steps. whether the animation holds temporarily at 0%, 20%, 40%, 60% and 80%, on the 20%, 40%, 60%, 80% and 100%, or makes 5 stops between the 0% and 100% along the animation, or makes 5 stops including the 0% and 100% marks (on the 0%, 25%, 50%, 75%, and 100%) depends on which of the following jump terms is used: jump-start denotes a left-continuous function, so that the first jump happens when the animation begins; jump-end denotes a right-continuous function, so that the last jump happens when the animation ends; jump-none there is no jump on either end. instead, holding at both the 0% mark and the 100% mark, each for 1/n of the duration. jump-both includes pause...
...And 2 more matches
animation - CSS: Cascading Style Sheets
Web › CSS › animation
keyframes duration | timing-function | delay | iteration-count | direction | fill-mode | play-state | name */ animation: 3s ease-in 1s 2 reverse both paused slidein; /* @keyframes name | duration | timing-function | delay */ animation: 3s linear 1s slidein; /* @keyframes name | duration */ animation: slidein 3s; <div class="grid"> <div class="col"> <div class="note"> given the following animation: <pre>@keyframes slidein { from { transform: scalex(0); } to { transform: scalex(1); } }</pre> </div> <div class="row"> <div class="cell"> <button class="play" title="play"></button> </div> <div class="cell flx"> <div class="overlay">animation: 3s ease-in 1s 2 reverse both paused slidein;</div> <div class="animation a1"></...
...estart'); } .grid { width: 100%; height: 100%; display: flex; background: #eee; font: 1em monospace; } .row { display: flex; flex: 1 auto; flex-direction: row; flex-wrap: wrap; justify-content: space-between; } .col { display: flex; flex: 1 auto; flex-direction: column; } .cell { box-sizing: border-box; margin: .5em; padding: 0; background-color: #fff; overflow: hidden; text-align: left; } .flx { flex: 1 0; } .note { background: #fff3d4; padding: 1em; margin: .5em; font: .8em sans-serif; text-align: left; flex: none; } .overlay { padding: .5em; } @keyframes slidein { from { transform: scalex(0); } to { transform: scalex(1); } } .a1 { animation: 3s ease-in 1s 2 reverse both paused slidein; } .a2 { animation: 3s linear 1s slidein;...
...end', function () { togglebutton(button[index], 'restart'); }); }); button.foreach(function (btn, index) { btn.addeventlistener('click', function () { playpause(index); }); }); }) a description of which properties are animatable is available; it's worth noting that this description is also valid for css transitions. ...
...And 2 more matches
<basic-shape> - CSS: Cascading Style Sheets
nts a shape used in the clip-path, shape-outside, and offset-path properties. 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 <basic-shape> data type is defined with one of the basic shape functions listed below. ...
...all <basic-shape> values use functional notation and are defined here using the value definition syntax. inset() inset( <shape-arg>{1,4} [round <border-radius>]? ) defines an inset rectangle. ...
...alues use functional notation and are defined here using the value definition syntax. inset() inset( <shape-arg>{1,4} [round <border-radius>]? ) defines an inset rectangle. when all of the first four arguments are supplied they represent the top, right, bottom and left offsets from the reference box inward that define the positions of the edges of the inset rectangle. these arguments follow the syntax of the margin shorthand, that let you set all four insets with one, two or four values. the optional <border-radius> argument(s) define rounded corners for the inset rectangle using the border-radius shorthand syntax. a pair of insets in either dimension that add up to more than the used dimension (such as left and right insets of 75% apiece) define a shape enclosing no area. for t...
...And 2 more matches
calc() - CSS: Cascading Style Sheets
Web › CSS › calc
the calc() css function lets you perform calculations when specifying css property values. it 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. syntax /* property: calc(expression) */ width: calc(100% - 80px); the calc() function takes a single expression as its parameter, with the expression's result used as the value. the expression can be any simple expression combining the following operators, using standard operator precedence rules: + addition. - subtraction. * multiplication. at least one o...
... / division. the right-hand side must be a <number>. the operands in the expression may be any <length> syntax value. you can use different units for each value in your expression, if you wish. you may also use parentheses to establish computation order when needed. notes the + and - operators must be surrounded by whitespace. for instance, calc(50% -8px) will be parsed as a percentage followed by a negative length — an invalid expression — while calc(50% - 8px) is a percentage followed by a subtraction operator and a length. likewise, calc(8px + -50%) is treated as a length followed by an addition operator and a negative percentage. the * and / operators do not require whitespace, but adding it for consistency is both allowed and recommended. division by zero results in an erro...
...object on screen with a margin calc() makes it easy to position an object with a set margin. in this example, the css creates a banner that stretches across the window, with a 40-pixel gap between both sides of the banner and the edges of the window: .banner { position: absolute; left: 40px; width: calc(100% - 80px); border: solid black 1px; box-shadow: 1px 2px; background-color: yellow; padding: 6px; text-align: center; box-sizing: border-box; } <div class="banner">this is a banner!</div> automatically sizing form fields to fit their container another use case for calc() is to help ensure that form fields fit in the available space, without extruding past the edge of their container, while maintaining an appropriate margin. let's look at some css: input { paddin...
...And 2 more matches
<display-inside> - CSS: Cascading Style Sheets
ment’s inner display type, which defines the type of formatting context that lays out its contents (assuming it is a non-replaced element). 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. ...
...ype of formatting context that lays out its contents (assuming it is a non-replaced element). 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). ...
...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. otherwise it generates a block container box. depending on the value of other properties (such as position, float, or overflow) and whether it is itself participating in a block or inline formatting context, it either establishes a new block formatting context (bfc) for its contents or integrates its contents into its parent formatting context. flow-root the element generates a block element box that establishes a new block formatting context, defining where the formatting root lies. table these elements behave lik...
...And 2 more matches
font-family - CSS: Cascading Style Sheets
nient to use the shorthand property font to set font-size and other font related properties all at once. you should always include at least one generic family name in a font-family list, since there's no guarantee that any given font is available. this lets the browser select an acceptable fallback font when necessary. the font-family property specifies a list of fonts, from highest priority to lowest. font selection does not simply stop at the first font in the list that is on the user's system. rather, font selection is done one character at a time, so that if an available font does not have a glyph for a needed character, the latter fonts are tried. (however, this doesn't work in internet explorer 6 or earlier.) when a font is only available in some styles, variants, or sizes, those prop...
...amily: ui-sans-serif; font-family: ui-monospace; font-family: ui-rounded; font-family: emoji; font-family: math; font-family: fangsong; /* global values */ font-family: inherit; font-family: initial; font-family: unset; the font-family property lists one or more font families, separated by commas. each font family is specified as either a <family-name> or a <generic-name> value. the example below lists two font families, the first with a <family-name> and the second with a <generic-name>: font-family: gill sans extrabold, sans-serif; values <family-name> the name of a font family. for example, "times" and "helvetica" are font families. font family names containing whitespace should be quoted. <generic-name> generic font families are a fallback mechanism, a means of preserving so...
... are font families. font family names containing whitespace should be quoted. <generic-name> generic font families are a fallback mechanism, a means of preserving some of the style sheet author's intent when none of the specified fonts are available. generic family names are keywords and must not be quoted. a generic font family should be the last item in the list of font family names. the following keywords are defined: serif glyphs have finishing strokes, flared or tapering ends, or have actual serifed endings. e.g. lucida bright, lucida fax, palatino, "palatino linotype", palladio, "urw palladio", serif. sans-serif glyphs have stroke endings that are plain. e.g. "open sans", "fira sans", "lucida sans", "lucida sans unicode", "trebuchet ms", "liberation sans", "nimbus san...
...And 2 more matches
font-variation-settings - 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. ...
...tings: initial; font-variation-settings: unset; values this property's value can take one of two forms: normal text is laid out using default settings. <string> <number> when rendering text, the list of variable font axis names is passed to the text layout engine to enable or disable font features. ...
...you should only use it when no basic properties exist to set those features (e.g. font-weight, font-style). ...
...And 2 more matches
justify-content - 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. ...
... end the items are packed flush to each other toward the end edge of the alignment container in the...
...ve their size increased equally (not proportionally), while still respecting the constraints imposed by max-height/max-width (or equivalent functionality), so that the combined size exactly fills the alignment container along the main axis. note: stretch is not supported by flexible boxes (flexbox). safe used alongside an alignment keyword. if the chosen keyword means that the item overflows the alignment container causing data loss, the item is instead aligned as if the alignment mode were start. unsafe used alongside an alignment keyword. regardless of the relative sizes of the item and alignment container, and regardless of whether overflow which causes data loss might happen, the given alignment value is honored. formal definition initial valuenormalapplies toflex container...
...And 2 more matches
offset-path - CSS: Cascading Style Sheets
the offset-path css property specifies a motion path for an element to follow and defines the element's positioning within the parent container or svg coordinate system. syntax /* default */ offset-path: none; /* function values */ offset-path: ray(45deg closest-side contain); /* url */ offset-path: url(#path); /* shapes */ offset-path: circle(50% at 25% 25%); offset-path: inset(50% 50% 50% 50%); offset-path: polygon(30% 0%, 70% 0%, 100% 50%, 30% 100%, 0% 70%, 0% 30%); offset-path: path('m 0,200 q 200,200 260,80 q 290,20 400,0 q 300,100 400,200'); /* geometry boxes */ offset-path: margin-box; offset-path: stroke-box; /* global values */ offset-path: inherit; offset-path: initial; offset-path: unset; values ray() taking up to three values, defines a path that is a line segment ...
... of an svg shape -- circle, ellipse, line, path, polygon, polyline, or rect -- using the shape's geometry as the path. <basic-shape> specifies a css shape including circle(), ellipse(), 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 p...
...as were they not positioned along the starting point of the motion path defined by offset-path. ...
...And 2 more matches
scroll-snap-stop - CSS: Cascading Style Sheets
/* keyword values */ scroll-snap-stop: normal; scroll-snap-stop: always; /* global values */ scroll-snap-type: inherit; scroll-snap-type: initial; scroll-snap-type: unset; syntax values normal when the visual viewport of this element's scroll container is scrolled, it may "pass over" possible snap positions. always the scroll container must not "pass over" a possible snap position; and must snap to the first of this elements' snap positions. ...
...ions. 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. ...
...ed valueas specifiedanimation typediscrete formal syntax normal | always examples snapping in different axes this example is duplicated from scroll-snap-type with minor variances. ...
...And 2 more matches
shape-outside - CSS: Cascading Style Sheets
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, ...
...r 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 shaping rules for the outside of the border. padding-box defines the shape enclosed by the outside padding edge. the shape follows the normal border radius shaping rules for the inside of the border. content-box defines the shape enclosed by the outside content edge. each corner radius of this box is the larger of 0 or border-radius - border-width - p...
...hape-outside value. when fetching, user agents must use "anonymous" mode, set the referrer source to the stylesheet's url, and set the origin to the url of the containing document. if this results in network errors such that there is no valid fallback image, the effect is as if the value none had been specified. interpolation when animating between one <basic-shape> and a second, the rules below are applied. the values in the shape functions interpolate as a simple list. the list values interpolate as <length>, <percentage>, or calc() where possible. if list values are not one of those types but are identical (such as finding nonzero in the same list position in both lists), those values do interpolate. both shapes must use the same reference box. if both shapes are the same type, th...
...And 2 more matches
transition-timing-function - CSS: Cascading Style Sheets
ming-function: initial; transition-timing-function: unset; values <timing-function> each <timing-function> represents the timing function to link to the corresponding property to transition, as defined in transition-property. the non-step keyword values (ease, linear, ease-in-out, etc.) each represent cubic bézier curve with fixed four point values, with the cubic-bezier() function value allowing for a non-predefined value. the step timing functions divides the input time into a specified number of intervals that are equal in length. it is defined by a number of steps and a step position. ease equal to cubic-bezier(0.25, 0.1, 0.25, 1.0), the default value, increases in velocity towards the middle of the transition, slowing back down at the end. linear equal to cubic-bezier(0...
...s that are equal in length. it is defined by a number of steps and a step position. ease equal to cubic-bezier(0.25, 0.1, 0.25, 1.0), the default value, increases in velocity towards the middle of the transition, slowing back down at the end. linear equal to cubic-bezier(0.0, 0.0, 1.0, 1.0), transitions at an even speed. ease-in equal to cubic-bezier(0.42, 0, 1.0, 1.0), starts off slowly, with the transition speed increasing until complete. ease-out equal to cubic-bezier(0, 0, 0.58, 1.0), starts transitioning quickly, slowing down the transition continues. • ease-in-out equal to cubic-bezier(0.42, 0, 0.58, 1.0), starts transitioning slowly, speeds up, and then slows down again. cubic-bezier(p1, p2, p3, p4) an author defined cubic-bezier curve, where the p1 and p3 ...
...ps along the transition, displaying each stop for equal lengths of time. for example, if n is 5, there are 5 steps. whether the transition holds temporarily at 0%, 20%, 40%, 60% and 80%, on the 20%, 40%, 60%, 80% and 100%, or makes 5 stops between the 0% and 100% along the transition, or makes 5 stops including the 0% and 100% marks (on the 0%, 25%, 50%, 75%, and 100%) depends on which of the following jump terms is used: jump-start denotes a left-continuous function, so that the first jump happens when the transition begins; jump-end denotes a right-continuous function, so that the last jump happens when the animation ends; jump-none there is no jump on either end. instead, holding at both the 0% mark and the 100% mark, each for 1/n of the duration jump-both inclu...
...And 2 more matches
Rich-Text Editing in Mozilla - Developer guides
consult the more up-to-date document available at making content editable. mozilla 1.3 introduces an implementation of microsoft® internet explorer's designmode feature. the rich-text editing support in mozilla 1.3 supports the designmode feature which turns html documents into rich-text editors. starting in firefox 3, mozilla also supports internet explorer's contenteditable attribute which allows any element to become editable or non-editable (the latter for when preventing change to fixed elements in an editable environment). setting up rich-text editing rich-text editing is initialized by setting the designmode property of a document to "on", such as the document inside an iframe. once designmode has been set to "on", the document becomes a rich-text editing area and the user can typ...
...ting the designmode property of a document to "on", such as the document inside an iframe. once designmode has been set to "on", the document becomes a rich-text editing area and the user can type into it as if it were a textarea. the most basic keyboard commands such as copy and paste are available, all others need to be implemented by the website. similarly, setting contenteditable to "true" allows you to make individual elements of a document editable. executing commands when an html document has been switched to designmode, the document object exposes the document.execcommand method which allows one to run commands to manipulate the contents of the editable region. most commands affect the document's selection (bold, italics, etc), while others insert new elements (adding a link) or af...
...ng section of migrate apps from internet explorer to mozilla. examples please note: the example files are still being migrated from another site. they are not available at this time. --fumble 18:13, 24 apr 2005 (pdt) example 1 the first example is an html document setting its own designmode to "on". this makes the entire document editable in mozilla 1.3. internet explorer, however, does not allow javascript to change the current document's designmode. for it to work in internet explorer, the contenteditable attribute of the body tag needs to be set to "true". figure 2 : first example html: <body contenteditable="true" onload="load()"> javascript: function load(){ window.document.designmode = "on"; } example 2 the second example is a simple rich text editing page, where text can be...
...And 2 more matches
The HTML autocomplete attribute - HTML: Hypertext Markup Language
f the suggested values is generally up to the browser; typically values come from past values entered by the user, but they may also come from pre-configured values. for instance, a browser might let the user save their name, address, phone number, and email addresses for autocomplete purposes. perhaps the browser offers the ability to save encrypted credit card information, for autocompletion following an authentication procedure. if an <input>, <select> or <textarea> element has no autocomplete attribute, then browsers use the autocomplete attribute of the element's form owner, which is either the <form> element that the element is a descendant of, or the <form> whose id is specified by the form attribute of the element. for more information, see the autocomplete attribute in <form>. in...
...ity concerns require that the field's value not be automatically entered. note: in most modern browsers, setting autocomplete to "off" will not prevent a password manager from asking the user if they would like to save username and password information, or from automatically filling in those values in a site's login form. see the autocomplete attribute and login fields. "on" the browser is allowed to automatically complete the input. no guidance is provided as to the type of data expected in the field, so the browser may use its own judgement. "name" the field expects the value to be a person's full name. using "name" rather than breaking the name down into its components is generally preferred because it avoids dealing with the wide diversity of human names and how they are structured...
...he input. no guidance is provided as to the type of data expected in the field, so the browser may use its own judgement. "name" the field expects the value to be a person's full name. using "name" rather than breaking the name down into its components is generally preferred because it avoids dealing with the wide diversity of human names and how they are structured; however, you can use the following autocomplete values if you do need to break the name down into its components: "honorific-prefix" the prefix or title, such as "mrs.", "mr.", "miss", "ms.", "dr.", or "mlle.". "given-name" the given (or "first") name. "additional-name" the middle name. "family-name" the family (or "last") name. "honorific-suffix" the suffix, such as "jr.", "b.sc.", "phd.", "mbasw", or "iv...
...And 2 more matches
HTML attribute: pattern - HTML: Hypertext Markup Language
ion, when matched against the value, must have its start anchored to the start of the string and its end anchored to the end of the string, which is slightly different from javascript regular expressions: in the case of pattern attribute, we are matching against the entire value, not just any subset, as if a ^(?: were implied at the start of the pattern and )$ at the end. ...
... 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). ...
...iditystate.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 example below restricts the value to 4-8 characters and requires that it contain only lower-case letters. ...
...And 2 more matches
<form> - HTML: Hypertext Markup Language
Web › HTML › Element › form
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 possible to use the :valid and :invalid css pseudo-classes to style a <form> element based on whether or not the elements inside the form are valid. ...
...f 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 possible to use the :valid and :invalid css pseudo-classes to style a <form> element based on whether or not the elements inside the form are valid. ...
... and :invalid css pseudo-classes to style a <form> element based on whether or not the elements inside the form are valid. content categories flow content, palpable content permitted content flow content, but not containing <form> elements tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content implicit aria role form if the form has an accessible name, otherwise no corresponding role permitted aria roles search, none or presentation dom interface htmlformelement attributes this element includes the global attributes. accept comma-separated content types the server accepts. this attribute was removed in html5 and should not be u...
...And 2 more matches
<input type="image"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › image
eight, formaction, formenctype, formmethod, formnovalidate, formtarget idl attributes none. methods none. value <input type="image"> elements do not accept value attributes. the path to the image to be displayed is specified in the src attribute. ...
..."> and <button> elements. formenctype a string that identifies the encoding method to use when submitting the form data to the server. there are three permitted values: application/x-www-form-urlencoded this, the default value, sends the form data as a string after url encoding the text using an algorithm such as encodeuri(). multipart/form-data uses the formdata api to manage the data, allowing for files to be submitted to the server. you must use this encoding type if your form includes any <input> elements of type file (<input type="file">). text/plain plain text; mostly useful only for debugging, so you can easily see the data that's to be submitted. if specified, the value of the formenctype attribute overrides the owning form's action attribute. this attribute is also avail...
...ecifying the height, in css pixels, at which to draw the image specified by the src attribute. src a string specifying the url of the image file to display to represent the graphical submit button. when the user interacts with the image, the input is handled like any other button input. width a number indicating the width at which to draw the image, in css pixels. obsolete attributes the following attribute was defined by html 4 for image inputs, but was not implemented by all browsers and has since been deprecated: attribute description usemap the name of an image map (<map>) element to use with the image; this is obsolete. use the <img> element to create image maps instead usemap if usemap is specified, it must be the name of an image map element, ...
...And 2 more matches
<meta>: The Document-level Metadata element - HTML: Hypertext Markup Language
Web › HTML › Element › meta
permitted content none, it is an empty element. tag omission as it is a void element, the start tag must be present and the end tag must not be present. permitted parents <meta charset>, <meta http-equiv>: a <head> element. ...
...ta charset>, <meta http-equiv>: a <head> element. if the http-equiv is not an encoding declaration, it can also be inside a <noscript> element, itself inside a <head> element. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlmetaelement the type of metadata provided by the meta element can be one of the following: if the name attribute is set, the meta element provides document-level metadata, applying to the whole page. if the http-equiv attribute is set, the meta element is a pragma directive, providing information equivalent to what can be given by a similarly-named http header. if the charset attribute is set, the meta element is a charset declaration, giving the character encoding in which th...
... attributes. charset this attribute declares the document's character encoding. if the attribute is present, its value must be an ascii case-insensitive match for the string "utf-8". content this attribute contains the value for the http-equiv or name attribute, depending on which is used. http-equiv defines a pragma directive. the attribute is named http-equiv(alent) because all the allowed values are names of particular http headers: content-security-policy allows page authors to define a content policy for the current page. content policies mostly specify allowed server origins and script endpoints which help guard against cross-site scripting attacks. content-type if specified, the content attribute must have the value "text/html; charset=utf-8". note: can onl...
...And 2 more matches
itemscope - HTML: Hypertext Markup Language
a boolean global attribute that defines the scope of associated metadata. specifying the itemscope attribute for an element creates a new item, which results in a number of name-value pairs that are associated with the element. a related attribute, itemtype, is used to specify the valid url of a vocabulary (such as schema.org) that describes the item and its properties context. in each of the following examples, the vocabulary is from schema.org. every html element may have an itemscope attribute specified. an itemscope element that does not have an associated itemtype must have an associated itemref. note: find more about itemtype attributes at http://schema.org/thing simple example html the following example specifies the itemscope attribute. the example specifies the itemtype as "h...
...hema.org/movie", and specifies three related itemprop attributes. <div itemscope itemtype="http://schema.org/movie"> <h1 itemprop="name">avatar</h1> <span>director: <span itemprop="director">james cameron</span> (born august 16, 1954)</span> <span itemprop="genre">science fiction</span> <a href="https://youtu.be/0ay1xikx7by" itemprop="trailer">trailer</a> </div> structured data the following table shows the structured data from the preceding example. itemscope itemtype movie itemprop (itemprop name) (itemprop value) itemprop director james cameron itemprop genre science fiction itemprop name avatar itemprop https://youtu.be/0ay1xikx7by trailer itemscope id attributes when you specify...
...s://youtu.be/0ay1xikx7by trailer itemscope id attributes when you specify the itemscope attribute for an element, a new item is created. the item consists of a group of name-value pairs. for elements with an itemscope attribute and an itemtype attribute, you may also specify an id attribute. you can use the id attribute to set a global identifier for the new item. ...
...And 2 more matches
Preloading content with rel="preload" - HTML: Hypertext Markup Language
the benefits can be seen much more clearly the later resources are discovered and the larger they are. for example: resources that are pointed to from inside css, like fonts or images. resources that javascript can request, like json, imported scripts, or web workers. larger images and video files. preload has other advantages too. using as to specify the type of content to be preloaded allows the browser to: prioritize resource loading more accurately. store in the cache for future requests, reusing the resource if appropriate. apply the correct content security policy to the resource. set the correct accept request headers for it. what types of content can be preloaded? many different content types can be preloaded. the possible as attribute values are: audio: audio file...
...as="font" type="font/woff2" crossorigin> <link href="style.css" rel="stylesheet"> </head> <body> … </body> not only are we providing the mime type hints in the type attributes, but we are also providing the crossorigin attribute to handle the cors issue. including media one nice feature of <link> elements is their ability to accept media attributes. ...
...off2" crossorigin> <link href="style.css" rel="stylesheet"> </head> <body> … </body> not only are we providing the mime type hints in the type attributes, but we are also providing the crossorigin attribute to handle the cors issue. including media one nice feature of <link> elements is their ability to accept media attributes. ...
...And 2 more matches
Browser detection using the user agent - HTTP
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 regexps // do not use /(?<=[a-z])/. it will cause a syntax error i...
...wer columns of information in a longer page on smaller screens while having more columns with a shorter page on larger screen sizes. this effect can be easily achieved using css flexboxes, sometimes with floats as a partial fallback. also try to move less relevant/important information down to the bottom and group the page's content together meaningfully. although it is off-topic, perhaps the following detailed example might give you insights and ideas that persuade you to forgo user agent sniffing. let us imagine a page composed of boxes of information; each box is about a different feline breed or canine breed. each box has an image, an overview, and a historical funfact. the pictures are kept to a maximum reasonable size even on large screens. for the purposes of grouping the content mean...
...the source code, that all the cat boxes are at the bottom of the source code, and that all these boxes have the same parent element. there a single instance of a dog box immediately above a cat box, of course. the first method uses horizontal flexboxes to group the content such that when the page is displayed to the end user, all the dogs boxes are at the top of the page and all the cat boxes are lower on the page. the second method uses a column layout and resents all the dogs to the left and all the cats to the right. only in this particular scenario, it is appropriate to provide no fallback for the flexboxes/multicolumns, resulting in a single column of very wide boxes on old browsers. also consider the following. if more people visit the webpage to see the cats, then it might be a good id...
...And 2 more matches
HTTP conditional requests - HTTP
lidation 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 side may vary. http uses strong validation by default, and it specifies when weak validation can be used. strong validation strong validation consists of guaranteeing that the resource is, byte to byte, identical to the one it is compared too. this is mandatory for some conditional headers, and the default for the oth...
...ike if the request wasn't conditional and the client uses this new resource (and caches it). besides the setting of the validators on the server side, this mechanism is transparent: all browsers manage a cache and send such conditional requests without any special work to be done by web developers. integrity of a partial download partial downloading of files is a functionality of http that allows to resume previous operations, saving bandwidth and time, by keeping the already obtained information: a server supporting partial downloads broadcasts this by sending the accept-ranges header. once this happens, the client can resume a download by sending a ranges header with the missing ranges: the principle is simple, but there is one potential problem: if the downloaded resource has be...
...rio: if-range: this solution is more efficient, but slightly less flexible, as only one etag can be used in the condition. rarely is such additional flexibility needed. avoiding the lost update problem with optimistic locking a common operation in web applications is to update a remote document. this is very common in any file system or source control applications, but any application that allows to store remote resources needs such a mechanism. common web sites, like wikis and other cms, have such a need. with the put method you are able to implement this. the client first reads the original files, modifies them, and finally pushes them to the server: unfortunately, things get a little inaccurate as soon as we take into account concurrency. while a client is locally modifying its ne...
...And 2 more matches
Using HTTP cookies - HTTP
Web › HTTP › Cookies
h the response. the cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a cookie http header. an expiration date or duration can be specified, after which the cookie is no longer sent. additional restrictions to a specific domain and path can be set, limiting where the cookie is sent. for details about the header attributes mentioned below, refer to the set-cookie reference article. the set-cookie and cookie headers the set-cookie http response header sends cookies from the server to the user agent. a simple cookie is set like this: set-cookie: <cookie-name>=<cookie-value> this shows the server sending headers to tell the client to store a pair of cookies: http/2.0 200 ok content-type: text/html set-cookie: yummy_cookie=choco ...
...have the httponly attribute. this precaution helps mitigate cross-site scripting (xss) attacks. here is an example: set-cookie: id=a3fwa; expires=wed, 21 oct 2021 07:28:00 gmt; secure; httponly define where cookies are sent the domain and path attributes define the scope of the cookie: what urls the cookies should be sent to. domain attribute the domain attribute specifies which hosts are allowed to receive the cookie. if unspecified, it defaults to the same origin that set the cookie, excluding subdomains. if domain is specified, then subdomains are always included. therefore, specifying domain is less restrictive than omitting it. however, it can be helpful when subdomains need to share information about a user. for example, if domain=mozilla.org is set, then cookies are available on...
...s-origin requests (where site is defined by the registrable domain), which provides some protection against cross-site request forgery attacks (csrf). it takes three possible values: strict, lax, and none. with strict, the cookie is sent only to the same site as the one that originated it; lax is similar, with an exception for when the user navigates to a url from an external site, such as by following a link; none has no restrictions on cross-site requests. here is an example: set-cookie: mykey=myvalue; samesite=strict the values of samesite attribute are case-insensitive. browsers are migrating to have cookies default to samesite=lax. if a cookie is needed to be sent cross-origin, opt out of the samesite restriction by using the none directive. the none directive requires that the sec...
...And 2 more matches
CSP: child-src - HTTP
d browsing contexts loaded using elements such as <frame> and <iframe>. for workers, non-compliant requests are treated as fatal network errors by the user agent. csp version 2 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the child-src policy: content-security-policy: child-src <source>; content-security-policy: child-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wil...
... mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a schema such as 'http:' or 'https:'. the colon is required, single quotes shouldn't be used. you can also specify data schemas (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin fr...
...urce. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows to enable specific inline event handlers. ...
...And 2 more matches
CSP: plugin-types - HTTP
ntiation of an <embed>, <object> or <applet> element will fail if: the element to load does not declare a valid mime type, the declared type does not match one of specified types in the plugin-types directive, the fetched resource does not match the declared type. csp version 2 directive type document directive default-src fallback no. not setting this allows anything. syntax one or more mime types can be set for the plugin-types policy: content-security-policy: plugin-types <type>/<subtype>; content-security-policy: plugin-types <type>/<subtype> <type>/<subtype>; <type>/<subtype> a valid mime type. examples disallowing plugins to disallow all plugins, the object-src directive should be set to 'none' which will disallow plugins. the...
...can be set for the plugin-types policy: content-security-policy: plugin-types <type>/<subtype>; content-security-policy: plugin-types <type>/<subtype> <type>/<subtype>; <type>/<subtype> a valid mime type. examples disallowing plugins to disallow all plugins, the object-src directive should be set to 'none' which will disallow plugins. the plugin-types directive is only used if you are allowing plugins with object-src at all. ...
...olicy: plugin-types <type>/<subtype> <type>/<subtype>; <type>/<subtype> a valid mime type. examples disallowing plugins to disallow all plugins, the object-src directive should be set to 'none' which will disallow plugins. the plugin-types directive is only used if you are allowing plugins with object-src at all. ...
...And 2 more matches
CSP: worker-src - HTTP
e fetch directive fallback if this directive is absent, the user agent will first look for the child-src directive, then the script-src directive, then finally for the default-src directive, when governing worker execution. chrome 59 and higher skips the child-src directive. edge 17 skips the script-src directive (bug). syntax one or more sources can be allowed for the worker-src policy: content-security-policy: worker-src <source>; content-security-policy: worker-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a ...
... mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol. <scheme-source> a schema such as 'http:' or 'https:'. the colon is required, single quotes shouldn't be used. you can also specify data schemas (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and definitely not for scripts. mediastream: allows mediastream: uris to be used as a content source. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin fr...
...urce. blob: allows blob: uris to be used as a content source. filesystem: allows filesystem: uris to be used as a content source. 'self' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows to enable specific inline event handlers. ...
...And 2 more matches
Content-Security-Policy-Report-Only - HTTP
these violation reports consist of json documents sent via an http post request to the specified uri. for more information, see also this article on content security policy (csp). header type response header forbidden header name no this header is not supported inside a <meta> element. syntax content-security-policy-report-only: <policy-directive>; <policy-directive> directives the directives of the content-security-policy header can also be applied to content-security-policy-report-only. ...
...content-security-policy-report-only: default-src https:; report-uri /csp-violation-report-endpoint/ if you still want to receive reporting, but also want to enforce a policy, use the content-security-policy header with the report-uri directive. content-security-policy: default-src https:; report-uri /csp-violation-report-endpoint/ violation report syntax the report json object contains the following data: blocked-uri the uri of the resource that was blocked from loading by the content security policy. if the blocked uri is from a different origin than the document-uri, then the blocked uri is truncated to contain just the scheme, host, and port. disposition either "enforce" or "report" depending on whether the content-security-policy header or the content-security-policy-report-only...
...on occurred. script-sample the first 40 characters of the inline script, event handler, or style that caused the violation. status-code the http status code of the resource on which the global object was instantiated. violated-directive the name of the policy section that was violated. sample violation report let's consider a page located at http://example.com/signup.html. it uses the following policy, disallowing everything but stylesheets from cdn.example.com. content-security-policy-report-only: default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports the html of signup.html looks like this: <!doctype html> <html> <head> <title>sign up</title> <link rel="stylesheet" href="css/style.css"> </head> <body> ... content ... </body> </html> can y...
...And 2 more matches
Feature-Policy: accelerometer - HTTP
the http feature-policy header accelerometer directive controls whether the current document is allowed to gather information about the acceleration of the device through the accelerometer interface. syntax feature-policy: accelerometer <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
...origins should be separated by a space. ...
...origins should be separated by a space. ...
...And 2 more matches
Feature-Policy: ambient-light-sensor - HTTP
the http feature-policy header ambient-light-sensor directive controls whether the current document is allowed to gather information about the amount of light in the environment around the device through the ambientlightsensor interface. syntax feature-policy: ambient-light-sensor <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
...origins should be separated by a space. ...
...origins should be separated by a space. ...
...And 2 more matches
Feature-Policy: battery - HTTP
the http feature-policy header battery directive controls whether the current document is allowed to gather information about the acceleration of the device through the batterymanager interface obtained via navigator.getbattery(). syntax feature-policy: battery <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
...origins should be separated by a space. ...
...origins should be separated by a space. ...
...And 2 more matches
Feature-Policy: camera - HTTP
the http feature-policy header camera directive controls whether the current document is allowed to use video input devices. when this policy is enabled, the promise returned by mediadevices.getusermedia() will reject with a notallowederror. syntax feature-policy: camera <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
...origins should be separated by a space. ...
...origins should be separated by a space. ...
...And 2 more matches
Feature-Policy: document-domain - HTTP
the http feature-policy header document-domain directive controls whether the current document is allowed to set document.domain. when this policy is enabled, attempting to set document.domain will fail and cause a securityerror domexception to be be thrown. syntax feature-policy: document-domain <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
...origins should be separated by a space. ...
...origins should be separated by a space. ...
...And 2 more matches
Feature-Policy: magnetometer - HTTP
the http feature-policy header magnetometer directive controls whether the current document is allowed to gather information about the orientation of the device through the magnetometer interface. syntax feature-policy: magnetometer <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
...origins should be separated by a space. ...
...origins should be separated by a space. ...
...And 2 more matches
Feature-Policy: microphone - HTTP
the http feature-policy header microphone directive controls whether the current document is allowed to use audio input devices. when this policy is enabled, the promise returned by mediadevices.getusermedia() will reject with a notallowederror. syntax feature-policy: microphone <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
...origins should be separated by a space. ...
...origins should be separated by a space. ...
...And 2 more matches
web-share - HTTP
the http feature-policy header web-share directive controls controls whether the current document is allowed to use the navigator.share() of web share api to share text, links, images, and other content to arbitrary destiations of user's choice. syntax feature-policy: web-share <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
...origins should be separated by a space. ...
...origins should be separated by a space. ...
...And 2 more matches
PATCH - HTTP
Web › HTTP › Methods › PATCH
he resource in the same state. for example if an auto-incrementing counter field is an integral part of the resource, then a put will naturally overwrite it (since it overwrites everything), but not necessarily so for patch. patch (like put) may have side-effects on other resources. ...
...state. for example if an auto-incrementing counter field is an integral part of the resource, then a put will naturally overwrite it (since it overwrites everything), but not necessarily so for patch. patch (like put) may have side-effects on other resources. ...
...urce, then a put will naturally overwrite it (since it overwrites everything), but not necessarily so for patch. patch (like put) may have side-effects on other resources. to find out whether a server supports patch, a server can advertise its support by adding it to the list in the allow or access-control-allow-methods (for cors) response headers. ...
...And 2 more matches
A typical HTTP session - HTTP
Web › HTTP › Session
n the underlying transport layer, usually this is tcp. with tcp the default port, for an http server on a computer, is port 80. other ports can also be used, like 8000 or 8080. the url of a page to fetch contains both the domain name, and the port number, though the latter can be omitted if it is 80. see identifying resources on the web for more details. note: the client-server model does not allow the server to send data to the client without an explicit request for it. to work around this problem, web developers use several techniques: ping the server periodically via the xmlhttprequest, fetch apis, using the websockets api, or similar protocols. sending a client request once the connection is established, the user-agent can send the request (a user-agent is typically a web browser, but...
...chniques: ping the server periodically via the xmlhttprequest, fetch apis, using the websockets api, or similar protocols. sending a client request once the connection is established, the user-agent can send the request (a user-agent is typically a web browser, but can be anything else, a crawler, for example). a client request consists of text directives, separated by crlf (carriage return, followed by line feed), divided into three blocks: the first line contains a request method followed by its parameters: the path of the document, i.e. an absolute url without the protocol or domain name the http protocol version subsequent lines represent an http header, giving the server information about what type of data is appropriate (e.g., what language, what mime types), or othe...
.... http://developer.mozilla.org/, and telling the server that the user-agent would prefer the page in french, if possible: get / http/1.1 host: developer.mozilla.org accept-language: fr observe that final empty line, this separates the data block from the header block. as there is no content-length provided in an http header, this data block is presented empty, marking the end of the headers, allowing the server to process the request the moment it receives this empty line. for example, sending the result of a form: post /contact_form.php http/1.1 host: developer.mozilla.org content-length: 64 content-type: application/x-www-form-urlencoded name=joe%20user&request=send%20me%20one%20of%20your%20catalogue request methods http defines a set of request methods indicating the desired actio...
...And 2 more matches
HTTP
Web › HTTP
http is a stateless protocol, meaning that the server does not keep any data (state) between two requests. ...
...ts are http requests for resources from a different domain than the domain of the resource making the request. for instance, an html page from domain a (http://domaina.example/) makes a request for an image on domain b (http://domainb.foo/image.jpg) via the img element. web pages today very commonly load cross-site resources, including css stylesheets, images, scripts, and other resources. cors allows web developers to control how their site reacts to cross-site requests. evolution of http a brief description of the changes between the early versions of http, to the modern http/2, the emergent http/3 and beyond. mozilla web security guidelines a collection of tips to help operational teams with creating secure web applications. http messages describes the type and structure of the...
...ief description of the changes between the early versions of http, to the modern http/2, the emergent http/3 and beyond. mozilla web security guidelines a collection of tips to help operational teams with creating secure web applications. http messages describes the type and structure of the different kind of messages of http/1.x and http/2. a typical http session shows and explains the flow of a usual http session. connection management in http/1.x describes the three connection management models available in http/1.x, their strengths, and their weaknesses. reference browse through detailed http reference documentation. http headers http message headers are used to describe a resource, or the behavior of the server or the client. custom proprietary headers can be added us...
...And 2 more matches
CSS Houdini
houdini is a group of apis that give developers direct access to the css object model (cssom), enabling developers to write code the browser can parse as css, thereby creating new css features without waiting for them to be implemented natively in browsers. advantages of houdini houdini enables faster parse times than using javascript .style for style changes. browsers parse the cssom — including layout, paint, and composite processes — before applying any style updates found in scripts. ...
... module contains registerpaint() functions, which register completely configurable worklets. the css paint() function parameters include the name of the worklet, along with optional parameters. the worklet also has access to the element's custom properties: they don't need to be passed as function arguments. li { background-image: paint(mycomponent, stroke, 10px); --highlights: blue; --lowlights: green; } note: with 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 k...
... 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 features. css parser api an api exposing the css parser more directly, for parsing ar...
...And 2 more matches
Keyed collections - JavaScript
« previousnext » this chapter introduces collections of data which are indexed by a key; map and set objects contain elements which are iterable in the order of insertion. maps map object ecmascript 2015 introduces a new data structure to map values to values. a map object is a simple key/value map and can iterate its elements in insertion order. the following code shows some basic operations with a map. see also the map reference page for more examples and the complete api. you can use a for...of loop to return an array of [key, value] for each iteration. let sayings = new map(); sayings.set('dog', 'woof'); sayings.set('cat', 'meow'); sayings.set('elephant', 'toot'); sayings.size; // 3 sayings.get('dog'); // woof sayings.get('fox'); // undefined sayings.has('bird'); /...
...yings.get('dog'); // woof sayings.get('fox'); // undefined sayings.has('bird'); // false sayings.delete('dog'); sayings.has('dog'); // false for (let [key, value] of sayings) { console.log(key + ' goes ' + value); } // "cat goes meow" // "elephant goes toot" sayings.clear(); sayings.size; // 0 object and map compared traditionally, objects have been used to map strings to values. objects allow you to set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. map objects, however, have a few more advantages that make them better maps. the keys of an object are strings or symbols, where they can be of any value for a map. you can get the size of a map easily, while you have to manually keep track of size for an object. the iteration of m...
...eakmap 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 the privates weakmap object. everything exposed on the instance and prototype is public; everything else is inaccessible from the outside world because privates is not exported from the module. const privates = new weak...
...And 2 more matches
Character classes - JavaScript
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. ...
...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. ...
...tches "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 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 matche...
...And 2 more matches
Using Promises - JavaScript
inal result: ${finalresult}`); }) .catch(failurecallback); important: always return results, otherwise callbacks won't catch the result of a previous promise (with arrow functions () => x is short for () => { return x; }). chaining after a catch it's possible to chain after a failure, i.e. a catch, which is useful to accomplish new actions even after an action failed in the chain. ...
...actions even after an action failed in the chain. read the following example: new promise((resolve, reject) => { console.log('initial'); resolve(); }) .then(() => { throw new error('something failed'); console.log('do this'); }) .catch(() => { console.error('do that'); }) .then(() => { console.log('do this, no matter what happened before'); }); this will output the following text: initial do that do this, no matter what happened before note: the text do this is not displayed because the something failed error caused a rejection. error propagation you might recall seeing failurecallback three times in the pyramid of doom earlier, compared to only once at the end of the promise chain: dosomething() .then(result => dosomethingelse(result)) .then(newresult => do...
... the old way. the most obvious example is the settimeout() function: settimeout(() => saysomething("10 seconds passed"), 10*1000); mixing old-style callbacks and promises is problematic. if saysomething() fails or contains a programming error, nothing catches it. settimeout is to blame for this. luckily we can wrap settimeout in a promise. best practice is to wrap problematic functions at the lowest possible level, and then never call them directly again: const wait = ms => new promise(resolve => settimeout(resolve, ms)); wait(10*1000).then(() => saysomething("10 seconds")).catch(failurecallback); basically, the promise constructor takes an executor function that lets us resolve or reject a promise manually. since settimeout() doesn't really fail, we left out reject in this case. com...
...And 2 more matches
Memory Management - JavaScript
low-level languages like c, have manual memory 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. ...
...mpression 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 value initialization in order to not bother the programmer with allocations, javascript will automatically allocate memory when values are initially declared. var n = 123; // allocates memory for a number var s = 'azerty'; // allocates memory for a string var o = { a: 1, b: null }; /...
... 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 allocation and determine when a block of allocated memory is no l...
...And 2 more matches
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
string.split is deprecated; use string.prototype.split instead warning: string.startswith is deprecated; use string.prototype.startswith instead warning: string.substr is deprecated; use string.prototype.substr instead warning: string.substring is deprecated; use string.prototype.substring instead warning: string.tolocalelowercase is deprecated; use string.prototype.tolocalelowercase instead warning: string.tolocaleuppercase is deprecated; use string.prototype.tolocaleuppercase instead warning: string.tolowercase is deprecated; use string.prototype.tolowercase instead warning: string.touppercase is deprecated; use string.prototype.touppercase instead warning: string.trim is deprec...
...ed; use string.prototype.trimleft instead warning: string.trimright is deprecated; use string.prototype.trimright instead error type warning. javascript execution won't be halted. what went wrong? the non-standard generic string methods are deprecated and have been removed in firefox 68 and later. ...
...ed. what went wrong? ...
...And 2 more matches
JavaScript error reference - JavaScript
for a beginner's introductory tutorial on fixing javascript errors, see what went wrong? troubleshooting javascript. list of errors in this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). ...
... for a beginner's introductory tutorial on fixing javascript errors, see what went wrong? troubleshooting javascript. ...
...m in your code. for a beginner's introductory tutorial on fixing javascript errors, see what went wrong? troubleshooting javascript. list of errors in this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). together, these two properties provide a starting point toward understanding and resolving the error. ...
...And 2 more matches
Array.from() - 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 array.from(arraylike [, mapfn [, thisarg]]) parameters arraylike an array-like or iterable object to convert to an array. mapfn optional map function to call on every element of the array. thisarg optional value to use as this when executing mapfn. return value a new array instance. ...
...ional map function to call on every element of the array. thisarg optional value to use as this when executing mapfn. return value a new array instance. description array.from() lets you create arrays from: array-like objects (objects with a length property and indexed elements); or iterable objects (objects such as map and set). array.from() has an optional parameter mapfn, which allows you to execute a map() function on each element of the array being created. more clearly, array.from(obj, mapfn, thisarg) has the same result as array.from(obj).map(mapfn, thisarg), except that it does not create an intermediate array. this is especially important for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into t...
...rom(obj, mapfn, thisarg) has the same result as array.from(obj).map(mapfn, thisarg), except that it does not create an intermediate array. this is especially important for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type. the length property of the from() method is 1. in es2015, the class syntax allows sub-classing of both built-in and user-defined classes. as a result, static methods such as array.from() are "inherited" by subclasses of array, and create new instances of the subclass, not array. polyfill array.from() 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...
...And 2 more matches
Array.prototype.shift() - JavaScript
lly generic; this method can be called or applied to objects resembling arrays. objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. array.prototype.pop() has similar behavior to shift, but applied to the last element in an array. ...
...in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. array.prototype.pop() has similar behavior to shift, but applied to the last element in an array. examples removing an element from an array the following code displays the myfish array before and after removing its first element. ...
....pop() has similar behavior to shift, but applied to the last element in an array. examples removing an element from an array the following code displays the myfish array before and after removing its first element. ...
...And 2 more matches
Function.prototype.apply() - JavaScript
undefined will be replaced with the global object, and primitive values will be boxed. this argument is required. argsarray optional an array-like object, specifying the arguments with which func should be called, or null or undefined if no arguments should be provided to the function. starting with ecmascript 5 these arguments can be a generic array-like object instead of an array. see below for browser compatibility information. return value the result of calling the function with the specified this value and arguments. description note: while the syntax of this function is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments. note: when the first argument is undefined or ...
... but it does not append to the existing array—it instead creates and returns a new array. but you wanted to append to the existing array... so what now? write a loop? surely 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. as an example, here are math.max/math.min, used to find out the maximum/minimum value in an array. // min/max number in an array const numbers = [5, 6, 2, 3, 7]; // using math.min/math.max apply let max = math.max.apply(null, numbers); // this about equal to math.max(...
...um = 32768; for (var i = 0, len = arr.length; i < len; i += quantum) { var submin = math.min.apply(null, arr.slice(i, math.min(i+quantum, len))); min = math.min(submin, min); } return min; } let min = minofarray([5, 6, 2, 3, 7]); using apply to chain constructors you can use apply to chain constructors for an object (similar to java). in the following example we will create a global function method called construct, which will enable you to use an array-like object with a constructor instead of an arguments list. function.prototype.construct = function(aargs) { let onew = object.create(this.prototype); this.apply(onew, aargs); return onew; }; note: the object.create() method used above is relatively new. for alternative methods, p...
...And 2 more matches
Intl.Collator() constructor - 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 new intl.collator([locales[, options]]) parameters locales optional. a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. the following unicode extension keys are allowed: co variant collations for certain locales. possible values include: "big5han", "dict", "direct", "ducet", "gb2312", "phonebk", "phonetic", "pinyin", "reformed", "searchjl", "stroke", "trad", "unihan". the "standard" and "search" values are ignored; they are replaced by the options property usage (see below). kn whether numeric collation should be ...
... "standard" and "search" values are ignored; they are replaced by the options property usage (see below). kn whether numeric collation should be used, such that "1" < "2" < "10". possible values are "true" and "false". this option can be set through an options property or through a unicode extension key; if both are provided, the options property takes precedence. kf whether upper case or lower case should sort first. possible values are "upper", "lower", or "false" (use the locale's default). this option can be set through an options property or through a unicode extension key; if both are provided, the options property takes precedence. options optional. an object with some or all of the following properties: localematcher the locale matching algorithm to use. possibl...
...efault is false. numeric whether numeric collation should be used, such that "1" < "2" < "10". possible values are true and false; the default is false. this option can be set through an options property or through a unicode extension key; if both are provided, the options property takes precedence. implementations are not required to support this property. ...
...And 2 more matches
Intl.DateTimeFormat() constructor - JavaScript
request. syntax new intl.datetimeformat([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings. to use the browser's default locale, omit this argument or pass undefined. unicode extension are supported (for example "en-us-u-ca-buddhist"). for the general form and interpretation of the locales argument, see the intl page. the following unicode extension keys are allowed: nu numbering system. possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt". ca calendar. possible values include: "buddhist", "chinese", "coptic", "ethiopia", "ethiopic", "gregory", "hebrew"...
... "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt". ca calendar. possible values include: "buddhist", "chinese", "coptic", "ethiopia", "ethiopic", "gregory", "hebrew", "indian", "islamic", "iso8601", "japanese", "persian", "roc". hc hour cycle. possible values include: "h11", "h12", "h23", "h24". options optional an object with some or all of the following properties: datestyle the date formatting style to use when calling format(). possible values include: "full" "long" "medium" "short" timestyle the time formatting style to use when calling format(). possible values include: "full" "long" "medium" "short" fractionalseconddigits the number of fractional seconds to apply when calling forma...
...on in case both are present. hourcycle the hour cycle to use. possible values are "h11", "h12", "h23", or "h24". this option overrides the hc language tag, if both are present, and the hour12 option takes precedence in case both options have been specified. formatmatcher the format matching algorithm to use. possible values are "basic" and "best fit"; the default is "best fit". ...
...And 2 more matches
Intl.Locale.prototype.numberingSystem - JavaScript
em is a system for expressing numbers. the numberingsystem property helps to represent the different numeral systems used by various countries, regions, and cultures around the world. as with most internationalization schemas, the numeral systems that can be represented in a locale object by numberingsystem are standardized by unicode. a table of the standard unicode numeral systems can be seen below. ...
...be represented in a locale object by numberingsystem are standardized by unicode. a table of the standard unicode numeral systems can be seen below. ...
...n a locale object by numberingsystem are standardized by unicode. a table of the standard unicode numeral systems can be seen below. ...
...And 2 more matches
Intl - JavaScript
e identifier consists of a language code, (optionally) a script code, (optionally) a region (or country) code, (optionally) one or more variant codes, and (optionally) one or more extension sequences, with all present components separated by hyphens. locale identifiers are case-insensitive ascii. however, it's conventional to use title case (first letter capitalized, successive letters lower case) for script code, upper case for region codes, and lower case for everything else. for example: "hi": hindi (language) "de-at": german (language) as used in austria (region) "zh-hans-cn": chinese (language) written in simplified characters (script) as used in china (region) "en-emodeng": english (language) in the "early modern english" dialect (variant) the subtags identifying lan...
... dialect (variant) the subtags identifying languages, scripts, regions (including countries), and (rarely used) variants in unicode bcp 47 locale identifiers are registered in the iana language subtag registry. this registry is periodically updated over time, and implementations may not always be up to date, so be careful not to rely too much on tags being universally supported. bcp 47 also allows for extensions, each consisting of a single digit or letter (other than "x") and one or more two- to eight-letter or digit tags, all separated by hyphens. javascript internationalization functions use the "u" (unicode) extension, which can be used to request additional customization of collator, numberformat, or datetimeformat objects. examples: "de-de-u-co-phonebk": use the phonebook variant...
...lendar in date and time formatting, so that 2013 is expressed as the year 25 of the heisei period, or 平成25. "en-gb-u-ca-islamic": use british english with the islamic (hijri) calendar, where the gregorian date 14 october, 2017 is the hijri date 24 muharram, 1439. other bcp 47 extension tags can be found in the unicode cldr project. finally, an extension using the letter "x" may appear, followed by one or one- to eight-letter or digit tags. this extension allows applications to encode information for their own private use, that will be ignored by all intl operations. locale negotiation the list of locales specified by the locales argument, after unicode extensions have been removed from them, is interpreted as a prioritized request from the application. the runtime compares it again...
...And 2 more matches
Promise.prototype.then() - JavaScript
function has one argument, the rejection reason. if it is not a function, it is internally replaced with a "thrower" function (it throws an error it received as argument). return value once a promise is fulfilled or rejected, the respective handler function (onfulfilled or onrejected) will be called asynchronously (scheduled in the current thread loop). the behavior of the handler function follows a specific set of rules. if a handler function: returns a value, the promise returned by then gets resolved with the returned value as its value. doesn't return anything, the promise returned by then gets resolved with an undefined value. throws an error, the promise returned by then gets rejected with the thrown error as its value. returns an already fulfilled promise, the promise returne...
...se returned by then gets rejected with that promise's value as its value. returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. also, the resolved value of the promise returned by then will be the same as the resolved value of the promise returned by the handler. following, an example to demonstrate the asynchronicity of the then method. // using a resolved promise, the 'then' block will be triggered instantly, // but its handlers will be triggered asynchronously as demonstrated by the console.logs const resolvedprom = promise.resolve(33); let thenprom = resolvedprom.then(value => { console.log("this gets called after the end of the main stack. the value r...
....catch() methods return promises, they can be chained — an operation called composition. examples using the then method var p1 = new promise((resolve, reject) => { resolve('success!'); // or // reject(new error("error!")); }); p1.then(value => { console.log(value); // success! }, reason => { console.error(reason); // error! }); chaining the then method returns a promise which allows for method chaining. if the function passed as handler to then returns a promise, an equivalent promise will be exposed to the subsequent then in the method chain. the below snippet simulates asynchronous code with the settimeout function. promise.resolve('foo') // 1. receive "foo", concatenate "bar" to it, and resolve that to the next then .then(function(string) { return new promise(f...
...And 2 more matches
RegExp.prototype.exec() - JavaScript
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 regexobj.exec(str) parameters str the string against which to match the regular expression. ...
..., the exec() method returns an array (with extra properties index and input; see below) and updates the lastindex property of the regular expression object. the returned array has the matched text as the first item, and then one item for each parenthetical capture group of the matched text. if the match fails, the exec() method returns null, and sets lastindex to 0. ...
...extra properties index and input; see below) and updates the lastindex property of the regular expression object. the returned array has the matched text as the first item, and then one item for each parenthetical capture group of the matched text. if the match fails, the exec() method returns null, and sets lastindex to 0. ...
...And 2 more matches
String.prototype.indexOf() - JavaScript
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 any fromindex value greater than 11) will return -1, as the search is started at position 11, a position after the end of t...
...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. ...
...1 'blue whale'.indexof('whale', 0) // returns 5 'blue whale'.indexof('whale', 5) // returns 5 'blue whale'.indexof('whale', 7) // returns -1 'blue whale'.indexof('') // returns 0 'blue whale'.indexof('', 9) // returns 9 'blue whale'.indexof('', 10) // returns 10 'blue whale'.indexof('', 11) // returns 10 the indexof() method is case sensitive. for example, the following expression returns -1: 'blue whale'.indexof('blue') // returns -1 checking occurrences note that 0 doesn't evaluate to true and -1 doesn't evaluate to false. therefore, when checking if a specific string exists within another string, the correct way to check would be: 'blue whale'.indexof('blue') !== -1 // true 'blue whale'.indexof('bloe') !== -1 // false ~('blue whale'.indexof('bloe')...
...And 2 more matches
String.prototype.substring() - JavaScript
g. description substring() extracts characters from indexstart up to but not including indexend. in particular: if indexend is omitted, substring() extracts characters to the end of the string. if indexstart is equal to indexend, substring() returns an empty string. if indexstart is greater than indexend, then the effect of substring() is as if the two arguments were swapped; see example below. ...
...ring() returns an empty string. if indexstart is greater than indexend, then the effect of substring() is as if the two arguments were swapped; see example below. any argument value that is less than 0 or greater than stringname.length is treated as if it were 0 and stringname.length, respectively. any argument value that is nan is treated as if it were 0. ...
...this method may be easier to remember, given that you don't need to know the starting and ending indices as you would in the above examples. // displays 'illa' the last 4 characters let anystring = 'mozilla' let anystring4 = anystring.substring(anystring.length - 4) console.log(anyst...
...And 2 more matches
String - JavaScript
eated as primitives, from string literals, or as objects, using the string() constructor: const string1 = "a string primitive"; const string2 = 'also a string primitive'; const string3 = `yet another string primitive`; const string4 = new string("a string object"); string primitives and string objects can be used interchangeably in most situations. see "string primitives and string objects" below. string literals can be specified using single or double quotes, which are treated identically, or using the backtick character `. this last form specifies a template literal: with this form you can interpolate expressions. character access there are two ways to access an individual character in a string. the first is the charat() method: return 'cat'.charat(1) // returns "a" the other way ...
....log(a + ' is less than ' + b) } else if (a > b) { console.log(a + ' is greater than ' + b) } else { console.log(a + ' and ' + b + ' are equal.') } a similar result can be achieved using the localecompare() method inherited by string instances. note that a == b compares the strings in a and b for being equal in the usual case-sensitive way. if you wish to compare without regard to upper or lower case characters, use a function similar to this: function isequal(str1, str2) { return str1.touppercase() === str2.touppercase() } // isequal upper case is used instead of lower case in this function, due to problems with certain utf-8 character conversions. string primitives and string objects note that javascript distinguishes between string objects and primitive string values. (the ...
...g 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). string.prototype.tolocalelowercase( [locale, ...locales]) the characters within a string are converted to lowercase while respecting the current locale. for most languages, this will return the same as tolowercase(). string.prototype.tolocaleuppercase( [locale, ...locales]) the characters within a string are converted to uppercase while respecting the current locale. for most languages, this will return the same...
...And 2 more matches
Destructuring assignment - JavaScript
r syntax, but on the left-hand side of the assignment to define what values to unpack from the sourced variable. const x = [1, 2, 3, 4, 5]; const [y, z] = x; console.log(y); // 1 console.log(z); // 2 this capability is similar to features present in languages such as perl and python. examples array destructuring basic variable assignment const foo = ['one', 'two', 'three']; const [red, yellow, green] = foo; console.log(red); // "one" console.log(yellow); // "two" console.log(green); // "three" assignment separate from declaration a variable can be assigned its value via destructuring separate from the variable's declaration. let a, b; [a, b] = [1, 2]; console.log(a); // 1 console.log(b); // 2 default values a variable can be assigned a default, in the case that the value unpac...
...sole.log(b); // 2 default values a variable can be assigned a default, in the case that the value unpacked from the array is undefined. let a, b; [a=5, b=7] = [1]; console.log(a); // 1 console.log(b); // 7 swapping variables two variables values can be swapped in one destructuring expression. without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the xor-swap trick). let a = 1; let b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1 const arr = [1,2,3]; [arr[2], arr[1]] = [arr[1], arr[2]]; console.log(arr); // [1,3,2] parsing an array returned from a function it's always been possible to return an array from a function. destructuring can make working with an array return value more concise. in this e...
...ot have a trailing comma // always consider using rest operator as the last element unpacking values from a regular expression match when the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed. function parseprotocol(url) { const parsedurl = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url); if (!parsedurl) { return false; } console.log(parsedurl); // ["https://developer.mozilla.org/web/javascript", "https", "developer.mozilla.org", "en-us/web/javascript"] const [, protocol, ful...
...And 2 more matches
Logical OR (||) - JavaScript
ed a boolean operator since its return value can always be converted to a boolean primitive. to explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double not operator or the boolean constructor. short-circuit evaluation the logical or expression is evaluated left to right, it is tested for possible "short-circuit" evaluation using the following rule: (some truthy expression) || expr is short-circuit evaluated to the truthy expression. 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 ex...
...s 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, because the && operator is executed before the || operator (see operator precedence). true || false && false // returns true, because && is executed first (true || false) && false // returns false, because operator precedence cannot apply examples using or the following code shows examples of the || (logical or) operator. o1 = t...
...ns false o9 = false || '' // f || f returns "" o10 = false || varobject // f || object returns varobject note: if you use this operator to provide a default value to some variable, be aware that any falsy value will not be used. if you only need to filter out null or undefined, consider using the nullish coalescing operator. ...
...And 2 more matches
Operator precedence - JavaScript
operator precedence determines how operators are parsed concerning each other. 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. observe how multiplication has higher precedence than addition and execut...
...on operator (**) console.log(echo("left", 2) ** echo("right", 3)); evaluating the left side evaluating the right side 8 the difference in associativity comes into play when there are multiple operators of the same precedence. with only one operator or operators of different precedences, associativity doesn't affect the output, as seen in the example above. in the example below, observe how associativity affects the output when multiple of the same operator are used. code output function echo(name, num) { console.log("evaluating the " + name + " side"); return num; } // notice the division operator (/) console.log(echo("left", 6) / echo("middle", 2) / echo("right", 3)); evaluating the left side evaluating the middle side...
... ** 2). thus, doing (2 ** 3) ** 2 changes the order and results in the 64 seen in the table above. remember that precedence comes before associativity. so, mixing division and exponentiation, the exponentiation comes before the division. for example, 2 ** 3 / 3 ** 2 results in 0.8888888888888888 because it is the same as (2 ** 3) / (3 ** 2). note on grouping and short-circuiting in the table below, grouping is listed as having the highest precedence. however, that does not always mean the expression within the grouping symbols ( … ) is evaluated first, especially when it comes to short-circuiting. short-circuiting is jargon for conditional evaluation. for example, in the expression a && (b + c), if a is falsy, then the sub-expression (b + c) will not even get evaluated, even if it is in...
...And 2 more matches
break - JavaScript
the break statement terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement. 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. the labeled statement can be any block statement; it does not have ...
...ent. 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. the labeled statement 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) { ...
...a break statement must be nested within any label it references. notice that inner_block is nested within outer_block. ...
...And 2 more matches
for - 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 for ([initialization]; [condition]; [final-expression]) statement initialization an expression (including assignment expressions) or variable declaration evaluated once before the loop begins. ...
...variables declared with let are local to the statement. the result of this expression is discarded. condition an expression to be evaluated before each loop iteration. if this expression evaluates to true, statement is executed. this conditional test is optional. if omitted, the condition always evaluates to true. if the expression evaluates to false, execution skips to the first expression following the for construct. final-expression an expression to be evaluated at the end of each loop iteration. this occurs before the next evaluation of condition. generally used to update or increment the counter variable. statement a statement that is executed as long as the condition evaluates to true. to execute multiple statements within the loop, use a block statement ({ ... }) to group those ...
... occurs before the next evaluation of condition. generally used to update or increment the counter variable. statement a statement that is executed as long as the condition evaluates to true. to execute multiple statements within the loop, use a block statement ({ ... }) to group those statements. to execute no statement within the loop, use an empty statement (;). examples using for the following for statement starts by declaring the variable i and initializing it to 0. it checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop. for (let i = 0; i < 9; i++) { console.log(i); // more statements } optional for expressions all three expressions in the head of the for loop are optional. for example, in the in...
...And 2 more matches
import - JavaScript
t "module-name"; var promise = import("module-name"); defaultexport name that will refer to the default export from the module. module-name the module to import from. this is often a relative or absolute path name to the .js file containing the module. certain bundlers may permit or require the use of the extension; check your environment. only single quoted and double quoted strings are allowed. name name of the module object that will be used as a kind of namespace when referring to the imports. exportn name of the exports to be imported. aliasn names that will refer to the named imports. description the name parameter is the name of the "module object" which will be used as a kind of namespace to refer to the exports. the export parameters specify individual named exports, ...
... a kind of namespace when referring to the imports. exportn name of the exports to be imported. aliasn names that will refer to the named imports. description the name parameter is the name of the "module object" which will be used as a kind of namespace to refer to the exports. the export parameters specify individual named exports, while the import * as name syntax imports all of them. below are examples to clarify the syntax. import an entire module's contents this inserts mymodule into the current scope, containing all the exports from the module in the file located in /modules/my-module.js. import * as mymodule from '/modules/my-module.js'; here, accessing the exports means using the module name ("mymodule" in this case) as a namespace. for example, if the module imported abo...
...t. (async () => { if (somethingistrue) { const { default: mydefault, foo, bar } = await import('/modules/my-module.js'); } })(); dynamic imports the standard import syntax is static and will always result in all code in the imported module being evaluated at load time. in situations where you wish to load a module conditionally or on demand, you can use a dynamic import instead. ...
...And 2 more matches
throw - JavaScript
ed 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 throw expression; expression the expression to throw. description use the throw statement to throw an exception. when you throw an exception, expression specifies the value of the exception. ...
... function userexception(message) { this.message = message; this.name = 'userexception'; } function getmonthname(mo) { mo = mo - 1; // adjust ...
...ror('required'); // generates an error object with the message of required also note that the throw statement is affected by automatic semicolon insertion (asi) as no line terminator between the throw keyword and the expression is allowed. 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'; } function getmonthname(mo) { mo = mo - 1; // adjust month number for array index (1 = jan, 12 = dec) var months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; if (...
...And 2 more matches
Media container formats (file types) - Web media technologies
the encoded audio and video tracks directly from one peer to another using mediastreamtrack objects to represent each track. see codecs used by webrtc for information about codecs commonly used for making webrtc calls, as well as browser compatibility information around codec support in webrtc. common container formats while there are a vast number of media container formats, the ones listed below are the ones you are most likely to encounter. some support only audio while others support both audio and video. the mime types and extensions for each are listed.the most commonly used containers for media on the web are probably mpeg-4 (mp4), quicktime movie (mov), and the wavefile audio file format (wav). however, you may also encounter mp3, ogg, webm, avi, and other formats. not all of these...
...dio and/or video that is specifically intended for transmission over cellular networks for consumption on mobile devices. the format was designed for use on 3g mobile phones, but can still be used on more modern phones and networks. however, the improved bandwidth availability and increased data caps on most networks has reduced the need for the 3gp format. however, this format is still used for slower networks and for lower-performance phones. this media container format is derived from the iso base media file format and mpeg-4, but is specifically streamlined for lower bandwidth scenarios. base 3gp media mime types audio video audio/3gpp video/3gpp audio/3gpp2 video/3gpp2 audio/3gp2 video/3gp2 these mime types are the fundamental...
...s a different thing than recording and/or editing it. if you're going to be manipulating the media data, using an uncompressed format can improve performance, while using a lossless compressed format at least prevent the accumulation of noise as compression artifacts are multiplied with each re-compression that occurs. if your target audience is likely to include users on mobile, especially on lower-end devices or on slow networks, consider providing a version of your media in a 3gp container with appropriate compression. if you have any specific encoding requirements, make sure the container you choose supports the appropriate codecs. if you want your media to be in a non-proprietary, open format, consider using one of the open container formats such as flac (for audio) or webm (for vid...
...And 2 more matches
Animation performance and frame rate - Web Performance
s sensitive to the particular system and its load, performance tools can help you understand the work the browser's doing to render your site, and help you prevent and diagnose problems when they occur. users expect all interface interactions to be smooth and all user interfaces to be responsive. animation can help make a site feel faster and responsive, but animations can also make a site feel slower and janky if not done correctly. responsive user interfaces have a frame rate of 60 frames per second (fps). while it is not always possible to maintain 60fps, it is important to maintain a high and steady frame rate for all animations. let's take a look at how we can use browser tools to inspect the frame rate. we'll also discuss some tips to create and maintain a fast and steady frame rate. ...
...and to drop frames if necessary. however, the performance cost of modifying a css property can vary from one property to another. it's commonly accepted that 60 frames per second is the rate at which animations will appear smooth. for a rate of 60 frames per second, the browser has 16.7 milliseconds to execute scripts, recalculate styles and layout if needed, and repaint the area being updated. ...
...s to execute scripts, recalculate styles and layout if needed, and repaint the area being updated. slow scripts and animating expensive css properties can result in jank as the browser struggles to hit a smooth frame rate. the rendering waterfall the process a browser uses to paint changes to a page when an element is animating css properties can be described as a waterfall consisting of the following steps: recalculate style: when a property for an element changes, the browser must recalculate computed styles. layout: next, the browser uses the computed styles to figure out the position and geometry for the elements. this operation is labeled "layout" but is also sometimes called "reflow". paint: finally, the browser needs to repaint the elements to the screen. one last step is not ...
...And 2 more matches
Introduction to progressive web apps - Progressive web apps (PWAs)
iscussing what they are and the advantages they offer over regular web apps. what is a progressive web app? the term "progressive web app" isn't a formal or official name. it's just a shorthand used initially by google for the concept of creating a flexible, adaptable app using only web technologies. pwas are web apps developed using a number of specific technologies and standard patterns to allow them to take advantage of both web and native app features. for example, web apps are more discoverable than native apps; it's a lot easier and faster to visit a website than to install an application, and you can also share web apps by simply sending a link. on the other hand, native apps are better integrated with the operating system and therefore offer a more seamless experience for the user...
...s offline, and users love tapping their icons to easily access their favorite apps, rather than navigating to it using a browser. pwas give us the ability to create web apps that can enjoy these same advantages. it's not a brand new concept—such ideas have been revisited many times on the web platform with various approaches in the past. progressive enhancement and responsive design already allow us to build mobile friendly websites. pwas, however, provide all this and more without losing any of the existing features that make the web great. what makes an app a pwa? as we hinted at above, pwas are not created with a single technology. they represent a new philosophy for building web apps, involving some specific patterns, apis, and other features. it's not that obvious if a web app is ...
...se benefits. the best-known success story is probably that of flipkart lite. india's largest e-commerce site was rebuilt as a progressive web app in 2015, which resulted in 70% increase in conversions. the aliexpress pwa has also seen much better results than either the web or the native app, with a 104% increase in conversion rates for new users. given their profit increase, and the relatively low amount of work required for the conversion of these apps to pwas, the advantage is clear. early stage emerging startups like couponmoto have also started using progressive web apps to drive more consumer engagement, showing that they can help small as well as big companies to (re-)engage users more effectively. you can check the list at pwa.rocks for more examples. particularly worth mentioni...
...And 2 more matches
SVG Presentation Attributes - SVG: Scalable Vector Graphics
rsor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events shape-rendering solid-color solid-opacity stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering transform unicode-bidi vector-effect visibility word-spacing writing-mode attributes alignment-baseline it specifies how an ob...
...endering transform unicode-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: non...
... how to optimize its color interpolation and compositing operations. value: auto|optimizespeed|optimizequality|inherit; animatable: yes cursor it specifies the mouse cursor displayed when the mouse pointer is over an element. value: <funciri>|<keywords>|inherit; animatable: yes direction it specifies the base writing direction of text. value: ltr|rtl|inherit; animatable: yes display it allows to control the rendering of graphical or container elements. value: see css display; animatable: yes dominant-baseline it defines the baseline used to align the box’s text and inline-level contents. value: auto|text-bottom|alphabetic|ideographic|middle|central| mathematical|hanging|text-top; animatable: yes enable-background deprecated since svg 2 it tells the browser how to manage the a...
...And 2 more matches
begin - SVG: Scalable Vector Graphics
Web › SVG › Attribute › begin
the begin attribute defines when an animation should begin or when an element should be discarded. the attribute value is a semicolon separated list of values. the interpretation of a list of start times is detailed in the smil specification in "evaluation of begin and end time lists". each individual value can be one of the following : <offset-value>, <syncbase-value>, <event-value>, <repeat-value>, <accesskey-value>, <wallclock-sync-value> or the keyword indefinite. six elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, <discard>, and <set> animate, animatecolor, animatemotion, animatetransform, set for <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set>, begin defines when the element should begin, i.e. become activ...
...nimate, animatecolor, animatemotion, animatetransform, set for <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set>, begin defines when the element should begin, i.e. become active. value <begin-value-list> default value 0s animatable no the <begin-value-list> is a semicolon-separated list of values. each value can be one of the following: <offset-value> this value defines a clock-value that represents a point in time relative to the beginning of the svg document (usually the load or domcontentloaded event). negative values are valid. <syncbase-value> this value defines a syncbase and an optional offset from that syncbase. the element's animation start time is defined relative to the begin or active end of another animati...
... relative to the beginning of the svg document (usually the load or domcontentloaded event). negative values are valid. <syncbase-value> this value defines a syncbase and an optional offset from that syncbase. the element's animation start time is defined relative to the begin or active end 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 t...
...And 2 more matches
display - SVG: Scalable Vector Graphics
Web › SVG › Attribute › display
<clippath> element will prevent the given child element from contributing to the clipping path. note: as a presentation attribute, display can be used as a css property. see css display for further information. as a presentation attribute, it can be applied to any element. ...
...as a css property. see css display for further information. as a presentation attribute, it can be applied to any element. ...
...y for further information. as a presentation attribute, it can be applied to any element. ...
...And 2 more matches
stroke-linecap - SVG: Scalable Vector Graphics
the stroke-linecap attribute is a presentation attribute defining the shape to be used at the end of open subpaths when they are stroked. note: as a presentation attribute stroke-linecap can be used as a css property. ...
...on a zero length...
...th, the path will not be rendered at all. ...
...And 2 more matches
Namespaces crash course - SVG: Scalable Vector Graphics
s and still be considered to be the same parameter, independently of the element with which they are used. a very good example of this is the href parameter defined by the xlink specification. this parameter is commonly used by other xml dialects as a means to link to external resources. but how do you tell the user agent which dialect the parameter belongs to, in this case xlink? consider the following example. <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <script xlink:href="cool-script.js" type="text/ecmascript"/> </svg> this example has the rather unusual looking parameter xmlns:xlink. as you may guess from the first 'xmlns' part, this is another namespace declaration. however, instead of setting the default namespace, this namespace declara...
...hers, so it's a good idea to always include the xlink declaration in your documents. as an aside, it's useful to know that namespace prefixes can also be used for element names. this tells the user agent that that particular element (but not its children this time!) belongs to the namespace assigned to the prefix. ...
... level 1 recommendation was created before the original namespaces in xml recommendation was released; therefore, dom1 isn't namespace aware. this causes problems for namespaced xml such as svg. to resolve these problems, dom level 2 core added namespace aware equivalents of all the applicable dom level 1 methods. when scripting svg, it is important to use the namespace aware methods. the table below lists the dom1 methods that shouldn't be used in svg, along with their equivalent dom2 counterparts that should be used instead. dom1 (don't use) dom2 (use these instead!) createattribute createattributens createelement createelementns getattributenode getattributenodens getattribute getattributens getelementsbytagname getel...
...And 2 more matches
Clipping and masking - SVG: Scalable Vector Graphics
« previousnext » erasing part of what one has created might at first sight look contradictory. but when you try to create a semicircle in svg, you will find out the use of the following properties quickly. clipping refers to removing parts of elements defined by other parts. in this case, any half-transparent effects are not possible, it's an all-or-nothing approach. masking on the other hand allows soft edges by taking transparency and grey values of the mask into account. creating clips we create the above mentioned semicircle based on a circle element: <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <clippath id="cut-off-bottom"> <rect x="0" y="0" width="200" height="100" /> </clippath> </defs...
...> 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. then every part of the target lying in a transparent area of the resulting clippath's content will not be rendered. color, opacity an...
...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 ...
...And 2 more matches
Transport Layer Security - Web security
encryption technology needed to be specified to ensure interoperability among all web browsers and servers. the internet engineering task force (ietf) specified tls 1.0 in rfc 2246 in january, 1999. the current version of tls is 1.3 (rfc 8446). despite the fact that the web now uses tls for encryption, many people still refer to it as "ssl" out of habit. although tls can be used on top of any low-level transport protocol, the original goal of the protocol was to encrypt http traffic. http encrypted using tls is commonly referred to as https. tls-encrypted web traffic is by convention exchanged on port 443 by default, while unencrypted http uses port 80 by default. https remains an important use case for tls. http over tls tls provides three primary services that help ensure the safety a...
... should try to limit cipher support to the newest ciphers possible which are compatible with the browsers you want to be able to connect to your site. the mozilla opsec guide to tls configurations provides more information on recommended configurations. to assist you in configuring your site, mozilla provides a helpful tls configuration generator that will generate configuration files for the following web servers: apache nginx lighttpd haproxy amazon web services cloudformation elastic load balancer using the configurator is a recommended way to create the configuration to meet your needs; then copy and paste it into the appropriate file on your server and restart the server to pick up the changes. the configuration file may need some adjustments to include custom settings, so be s...
...es of tls 1.2. include strong security analysis in the design. improve privacy by encrypting more of the protocol. reduce the time needed to complete a handshake. tls 1.3 changes much of the protocol fundamentals, but preserves almost all of the basic capabilities as 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 ...
...And 2 more matches
Web security
ameters, which can have a substantial impact on the security and reliability of data. this article provides an overview of tls and the kinds of decisions you need to make when securing your content. https https (hypertext transfer protocol secure) is an encrypted version of the http protocol. it uses ssl or tls to encrypt all communication between a client and a server. this secure connection allows clients to be sure that they are connected with the intended server, and to exchange sensitive data. http strict-transport-security the strict-transport-security: http header lets a website specify that it may only be accessed using https. certificate transparency certificate transparency is an open framework designed to protect against and monitor for certificate misissuances. newly issued ...
...ow a document or script loaded from one origin can interact with a resource from another origin. it helps isolate potentially malicious documents, reducing possible attack vectors. subresource integrity subresource integrity (sri) is a security feature that enables browsers to verify that resources they fetch (for example, from a cdn) are delivered without unexpected manipulation. it works by allowing you to provide a cryptographic hash that a fetched resource must match. http access-control-allow-origin the access-control-allow-origin response header indicates whether the response can be shared with requesting code from the given origin. http x-content-type-options the x-content-type-options response http header is a marker used by the server to indicate that the mime types advertise...
...this is a way to opt out of mime type sniffing, or, in other words, to say that the mime types are deliberately configured. clickjacking protection in clickjacking, a user is fooled into clicking on a ui element that performs some action other than what the user expects. ...
...And 2 more matches
Index - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Index
t the page info. or use a download tool, those usually tell the mime type. 3 index index, reference, xslt found 54 pages: 4 pi parameters xslt no summary! 5 the xslt/javascript interface in gecko xslt no summary! 6 advanced example xslt this advanced example sorts several divs based on their content. the example allows sorting the content multiple times, alternating between ascending and descending order. the javascript loads the .xsl file only on the first sort and sets the xslloaded variable to true once it has finished loading the file. using the xsltprocessor.getparameter() method, the code can figure whether to sort in ascending or descending order. it defaults to ascending if the parameter is empty (the ...
...inked by a network. 14 an overview needshelp, needsmarkupwork, 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. 15 for further reading needscontent, needshelp, transforming_xml_with_xslt, xml, xslt http://www.amazon.com/xslt-programme.../dp/0764543814 16 resources extensions, needscontent, needsexample, needslivesample, xml, xsl no summary! 17 the netscape xslt/xpath reference netscape, reference, xslt, axes no summary! 18 using th...
... 20 <xsl:apply-imports> element, reference, xslt, apply-imports the <xsl:apply-imports> element is fairly arcane, used mostly in complex stylesheets. import precedence requires that template rules in main stylesheets have higher precedence than template rules in imported stylesheets. sometimes, however, it is useful to be able to force the processor to use a template rule from the (lower precedence) imported stylesheet rather than an equivalent rule in the main stylesheet. 21 <xsl:apply-templates> element, reference, xslt, apply-templates the <xsl:apply-templates> element selects a set of nodes in the input tree and instructs the processor to apply the proper templates to them. 22 <xsl:attribute-set> element, reference, xslt, attribute-set ...
...And 2 more matches
Content Scripts - Archive of obsolete content
web content into separate scripts that are called content scripts. this page describes how to develop and implement content scripts. content scripts can be one of the more confusing aspects of working with the sdk, but you're very likely to have to use them. ...
...that use content scripts, like page-mod and tabs, provide functions that enable the add-on's main code to load content scripts into web pages content scripts can be loaded in as strings, but are more often stored as separate files under the add-on's "data" directory. jpm doesn't make a "data" directory by default, so you must add it and put your content scripts in there. a message-passing api allows the main code and content scripts to communicate with each other this complete add-on illustrates all of these principles. its "main.js" attaches a content script to the current tab using the tabs module. in this case the content script is passed in as a string. the content script simply replaces the content of the page: // main.js var tabs = require("sdk/tabs"); var contentscriptstring = 'do...
....js" attaches a content script to the current tab using the tabs module. in this case the content script is passed in as a string. the content script simply replaces the content of the page: // main.js var tabs = require("sdk/tabs"); var contentscriptstring = 'document.body.innerhtml = "<h1>this page has been eaten</h1>";' tabs.activetab.attach({ contentscript: contentscriptstring }); the following high-level sdk modules can use content scripts to modify web pages: page-mod: enables you to attach content scripts to web pages that match a specific url pattern. tabs: exports a tab object for working with a browser tab. the tab object includes an attach() function to attach a content script to the tab. page-worker: lets you retrieve a web page without displaying it. you can attach cont...
...the main add-on code and the the main add-on code sends the message to the other content script. this will work regardless of the context in which the content script was loaded. in the special case where the two content scripts are loaded into the same exact page, it is possible for the content scripts to communicate directly to each other using the dom postmessage() api or a customevent. the following add-on shows a content script added by page-mod receiving a customevent sent from a context-menu item when the context menu item is clicked. the page-mod script will then issue an alert with the url of the link on which the context menu was displayed. the url is passed to the page-mod script in the customevent. var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org...
Content Processes - Archive of obsolete content
is article, it's probably best to read it as if content and add-on processes actually exist. to communicate between add-on and content processes, the sdk uses something called content scripts. these are explained in the first section. content scripts communicate with add-on code using something called event emitters. these are explained in the next section. content workers combine these ideas, allowing you to inject a content script into a content process, and automatically set up a communication channel between them. these are explained in the third section. in the next section, we will look at how content scripts interact with the dom in a content process. there are several caveats here, all of them related to security, that might cause things to not behave in the way you might expect. t...
...eferred to as a pipe. content workers a content worker is an object that is used to inject content scripts into a content process, and to provide a pipe between each content script and the main add-on script. the idea is to use a single content worker for each content process. the constructor for the content worker takes an object containing one or more named options. ...
...ch content script and the main add-on script. the idea is to use a single content worker for each content process. the constructor for the content worker takes an object containing one or more named options. among other things, this allows us to specify one or more content scripts to be loaded. when a content script is first loaded, the content worker automatically imports a messaging api that allows it to emit messages over a pipe. on the add-on side, this pipe is exposed via the the port property on the worker. in addition to the port property, workers also support the web worker api, which allows scripts to send messages to each other using the postmessage function. this function uses the same pipe internally, and causes a 'message' event to be emitted on the other side. as explained ear...
...unction. this function uses the same pipe internally, and causes a 'message' event to be emitted on the other side. as explained earlier, firefox doesn't yet use separate processes for tabs or add-ons, so instead, each content script is loaded in a sandbox. sandboxes were explained this article. accessing the dom the global for the content sandbox has the window object as its prototype. this allows the content script to access any property on the window object, even though that object lives outside the sandbox. recall that the window object inside the sandbox is actually a wrapper to the real object. a potential problem with the content script having access to the window object is that a malicious page could override methods on the window object that it knows are being used by the...
Module structure of the SDK - Archive of obsolete content
local modules: each of the javascript files under your add-on's "lib" directory. external modules: reusable modules developed and maintained outside the sdk, but usable by sdk-based add-ons. sdk modules the modules supplied by the sdk are divided into two sorts: high-level modules like panel and page-mod provide relatively simple, stable apis for the most common add-on development tasks. ...
...e-mod provide relatively simple, stable apis for the most common add-on development tasks. low-level modules like heritage and namespace provide more powerful functionality, and are typically less stable and more complex. to use sdk modules, you can pass require() a complete path, starting with "sdk", to the module you want to use. for high-level modules this is just sdk/<module_name>, and for low-level modules it is sdk/<path_to_module>/<module_name>: // load the high-level "tabs" module var tabs = require("sdk/tabs"); // load the low-level "uuid" module var uuid = require('sdk/util/uuid'); the path to specify for a low-level module is given along with the module name itself in the title of the module's documentation page (for example, system/environment). although the sdk repository...
...u 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 module, specify a path relative to the importing module. ...
..."); // attempting to define a new property // will fail, or throw an exception in strict mode self.foo = 1; // attempting to modify an existing property // will fail, or throw an exception in strict mode self.data = "foo"; using modules from outside the add-on sdk you can use commonjs modules outside the add-on sdk, in any environment where you can use components.utils.import. just call the following: const { require } = cu.import("resource://gre/modules/commonjs/toolkit/require.js", {}) this will import require() into your scope. you can then use that to import commonjs modules. you can import sdk modules in just the same way you could from an sdk add-on: // import the sdk's base64 module var base64 = require("sdk/base64"); base64.encode("hello"); // "agvsbg8=" you can import other ...
content/loader - Archive of obsolete content
with web content, such as panel and page-mod. usage the module exports a constructor for the loader object, which inherits on(), once(), and removelistener() functions that enable its users to listen to events. loader adds code to initialize and validate a set of properties for managing content scripts: contenturl contentscript contentscriptfile contentscriptwhen contentscriptoptions allow when certain of these properties are set, the loader emits a propertychange event, enabling its users to take the appropriate action. the loader is used by modules that use content scripts but don't themselves load content, such as page-mod. modules that load their own content, such as panel and page-worker, use the symbiont module instead. symbiont inherits from loader but contains its own f...
...enabling its users to take the appropriate action. the loader is used by modules that use content scripts but don't themselves load content, such as page-mod. modules that load their own content, such as panel and page-worker, use the symbiont module instead. symbiont inherits from loader but contains its own frame into which it loads content supplied as the contenturl option. ...
... local file urls of content scripts to load. content scripts specified by this property are loaded before those specified by the contentscript property. contentscript the texts of content scripts to load. content scripts specified by this property are loaded after those specified by the contentscriptfile property. contentscriptwhen when to load the content scripts. ...
...he domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires contentscriptoptions read-only value exposed to content scripts under self.options property. any kind of jsonable value (object, array, string, etc.) can be used here. optional. contenturl the url of the content loaded. allow permissions for the content, with the following keys: ...
core/promise - Archive of obsolete content
promises conside...
...t that represents a eventual result, either successful or failed. this object is a promise, both figuratively and by name, to eventually resolve. we can call a function on the promise to observe either its fulfillment or rejection. if the promise is rejected and the rejection is not explicitly observed, any derived promises will be implicitly rejected for the same reason. in the add-on sdk we follow commonjs promises/a specification and model a promise as an object with a then method, which can be used to get the eventual return (fulfillment) value or thrown exception (rejection): foo().then(function success(value) { // ... }, function failure(reason) { // ... }); if foo returns a promise that gets fulfilled with the value, success callback (the value handler) will be called with that ...
...d be enough to doing almost anything you may think of with promises, but once you start using promises extensively you may discover some missing pieces and this section of documentation may help you to discover them. doing things concurrently so far we have being playing with promises that do things sequentially, but there are many cases where one would need to do things concurrently. ...
... a reasonable time. in such cases it's useful to put a timer on such tasks: function timeout(promise, ms) { let deferred = defer(); promise.then(deferred.resolve, deferred.reject); delay(ms, 'timeout').then(deferred.reject); return deferred.promise; } var tweets = readasync(url); timeout(tweets, 20).then(function(data) { ui.display(data); }, function() { alert('network is being too slow, try again later'); }); alternative promise apis there may be cases where you will want to provide more than just then method on your promises. in fact some other promise frameworks do that. such use cases are also supported. earlier described defer may be passed optional prototype argument, in order to make the returned promise and all the subsequent promises decendents of that prototype: let...
lang/functional - Archive of obsolete content
er methods. some of these functions implement apis from jeremy ashkenas's underscore.js and all credits go to him and his contributors. globals functions method(lambda) takes a function and returns a method associated with an object. when the method is invoked on an instance of the object, the original function is called. it is passed the object instance (i.e. this) as the first parameter, followed by any parameters passed into the method. let { method } = require("sdk/lang/functional"); let mynumber = { times: method(times), add: method(add), number: 0 }; function times (target, x) { return target.number *= x; } function add (target, x) { return target.number += x; } console.log(mynumber.number); // 0 mynumber.add(10); // 10 mynumber.times(2); // 20 mynumber.add(3); // 23 p...
...ne = partial(add, 1); addone(5); // 6 addone(10); // 11 partial(add, addone(20))(2); // 23 parameters fn : function function on which partial application is to be performed. arguments... : mixed additional arguments returns function : the partial function. compose(fn...) returns the composition of a list of functions, where each function consumes the return value of the function that follows. in math terms, composing the functions f(), g(), and h() produces f(g(h())). let { compose } = require("sdk/lang/functional"); let welcome = compose(exclaim, greet); welcome('moe'); // "hi: moe!"; function greet (name) { return "hi: " + name; } function exclaim (statement) { return statement + "!"; } parameters fn... : function takes a variable number of functions as arguments and compos...
...aim, greet); welcome('moe'); // "hi: moe!"; function greet (name) { return "hi: " + name; } function exclaim (statement) { return statement + "!"; } parameters fn... : function takes a variable number of functions as arguments and composes them from right to left. returns function : the composed function. wrap(fn, wrapper) returns the first function passed as an argument to the second, allowing you to adjust arguments, run code before and after, and conditionally execute the original function. let { wrap } = require("sdk/lang/functional"); let wrappedhello = wrap(hello, function (fn, name) { return "before, " + fn(name) + "after"; }); wrappedhello("moe"); // "before, hello: moe, after" function hello (name) { return "hello: " + name; } parameters fn : function the function t...
...r function. identity(value) returns the same value that is used as the argument. in math: f(x) = x. let { identity } = require("sdk/lang/functional"); let x = 5; identity(x); // 5 parameters value : mixed the value to be returned. returns mixed : the value that was originally passed in. memoize(fn, hasher) memoizes a given function by caching the computed result. useful for speeding up slow-running computations. if passed an optional hashfunction, it will be used to compute the hash key for storing the result, based on the arguments to the original function. the default hashfunction just uses the first argument to the memoized function as the key. let { memoize } = require("sdk/lang/functional"); let memoizedfn = memoize(primefactorization); memoizedfn(50); // returns [2, 5, 5], ...
ui/frame - Archive of obsolete content
o a frame event: var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); frame.on("message", pong) function pong(e) { if (e.data == "ping") { // message only the sender, and not any frames attached to other browser windows e.source.postmessage("pong", "*"); } } parameters event : string the name of the event to listen to. frame supports the following events: attach, detach, load, ready, and message. listener : function the listener function. this is passed an event object which always contains a source property, which has a postmessage() function modeled after window.postmessage(). you can use this to communicate only with the specific frame instance that generated the event, and not to any frame instance attached to other browser windo...
...hich always contains a source property, which has a postmessage() function modeled after window.postmessage(). you can use this to communicate only with the specific frame instance that generated the event, and not to any frame instance attached to other browser windows. once(event, listener) assign a listener to the first occurrence only of an event emitted by the frame. frame supports the following events: attach, detach, load, ready, and message. the listener is automatically removed after the first time the event is emitted. var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); frame.once("message", pong) function pong(e) { if (e.data == "ping") { // message only the sender, and not any frames attached to other browser windows e.source...
...nt is emitted. var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); frame.once("message", pong) function pong(e) { if (e.data == "ping") { // message only the sender, and not any frames attached to other browser windows e.source.postmessage("pong", "*"); } } parameters event : string the name of the event to listen to. frame supports the following events: attach, detach, load, ready, and message. listener : function the listener function. this is passed an event object which always contains a source property, which has a postmessage() function modeled after window.postmessage(). you can use this to communicate only with the specific frame instance that generated the event, and not to any frame instance attached to other browser windo...
...istener. for example, this code is equivalent to once(): var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); frame.on("message", pong) function pong(e) { if (e.data == "ping") { e.source.postmessage("pong", "*"); } frame.removelistener("message", pong) } parameters event : string the event the listener is listening for. frame supports the following events: attach, detach, load, ready, and message. listener : function the listener to remove. off(event, listener) this function is an alias for removelistener(). parameters event : string the event the listener is listening for. frame supports the following events: attach, detach, load, ready, and message. listener : function the listener to remove. destroy() destroy the frame. aft...
ui/sidebar - Archive of obsolete content
this will be used for the label for your sidebar in the "sidebar" submenu in firefox, and will be shown at the top of your sidebar when it is open. url the url of the content to load in the sidebar. this must be a local url (typically, loaded from the "data" folder using self.data.url()). ...
...use to send messages to, and receive messages from, scripts loaded into the sidebar. this is the event you should listen to if your main add-on code needs to communicate with the scripts loaded into the sidebar and the main add-on code starts the conversation. see using ready for an example. detach this event is emitted when a worker is detached from a sidebar, as a result of either of the following: calling the sidebar's hide() method, when the sidebar is being shown in the currently active window the user switching the sidebar off using the "sidebar" submenu in firefox, when the sidebar is being shown in the currently active window the detach listener receives a worker object as a parameter. this object is the same as the worker passed into the corresponding attach event. after de...
...worker) { var index = workerarray.indexof(worker); if(index != -1) { workerarray.splice(index, 1); } } var sidebar = require("sdk/ui/sidebar").sidebar({ id: 'my-sidebar', title: 'my sidebar', url: require("sdk/self").data.url("sidebar.html"), onattach: attachworker, ondetach: detachworker }); show this event is emitted when the sidebar is shown, as a result of any of the following: calling the sidebar's show() method, when the sidebar is not shown in the currently active window changing the sidebar's url property the user switching the sidebar on using the "sidebar" submenu in firefox, when the sidebar is not shown in the currently active window the user opening a new window from a window that has the sidebar showing hide this event is emitted when the sidebar ...
..., when the sidebar is not shown in the currently active window changing the sidebar's url property the user switching the sidebar on using the "sidebar" submenu in firefox, when the sidebar is not shown in the currently active window the user opening a new window from a window that has the sidebar showing hide this event is emitted when the sidebar is hidden, as a result of either of the following: calling the sidebar's hide() method, when the sidebar is being shown in the currently active window the user switching the sidebar off using the "sidebar" submenu in firefox, when the sidebar is being shown in the currently active window ...
Chrome Authority - Archive of obsolete content
the api used to gain chrome access is currently an experimental feature of the sdk, and may change in future releases. using chrome authority the most powerful low-level modules are run with "chrome privileges", which gives them access to the infamous components object, which grants unfettered access to the host system. from this, the module can do pretty much anything the browser is capable of. to obtain these privileges, the module must declare its intent with a statement like the following: var {cc, ci} = require("chrome"); the "chrome" built-in pseudo module is provided by the "toolkit/loader" module. the object returned by require("chrome"), when unpacked with the destructuring assignment feature available in the mozilla js environment, will provide the usual components.* aliases...
...e("chrome"), when unpacked with the destructuring assignment feature available in the mozilla js environment, will provide the usual components.* aliases: cc an alias for components.classes. ci an alias for components.interfaces. cu an alias for components.utils. cr an alias for components.results. cm an alias for components.manager. components an alias for components itself (note the lower-case). from this you can access less-frequently-used properties like components.stack and components.issuccesscode. note: the require("chrome") statement is the only way to access chrome functionality and the components api. the components object should not be accessed from modules. the sdk tools will emit a warning if it sees module code which references components directly. your modules sho...
...tions). the manifest is built with a simple regexp-based scanner, not a full javascript parser. developers should stick to simple require statements, with a single static string, one per line of code. if the scanner fails to see a require entry, the manifest will not include that entry, and (once the implementation is complete) the runtime code will get an exception. ...
...require("two"); the intention is that developers use require() statements for two purposes: to declare (to security reviewers) what sorts of powers the module wants to use, and to control how those powers are mapped into the module's local namespace. their statements must therefore be clear and easy to parse. a future manifest format may move the declaration portion out to a separate file, to allow for more fine-grained expression of authority. commands that build a manifest, like "jpm xpi" or "jpm run", will scan all included modules for use of cc/ci aliases (or the expanded components.classes forms). it will emit a warning if it sees the expanded forms, or if it sees a use of e.g. "cc" without a corresponding entry in the require("chrome") statement. these warnings will serve to guide de...
Creating Event Targets - Archive of obsolete content
these apis are still in active development, and we expect to make incompatible changes to them in future releases. the guide to event-driven programming with the sdk describes how to consume events: that is, how to listen to events generated by event targets. 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. this is especially useful if you want to build your own modules, either to organize your add-on better or to enable other developers to reuse your code. ...
...t events when the user adds and visits bookmarks, enabling users of the module to listen for these events using the sdk's standard event api. using the places api first, let's write some code using places api that logs the uris of bookmarks the user adds. create a new directory called "bookmarks", navigate to it, and run jpm init, accepting all the defaults. ...
... function() { bookmarkservice.removeobserver(bookmarkobserver); } try running this add-on, adding and visiting bookmarks, and observing the output in the console. modules as event targets we can adapt this code into a separate module that exposes the sdk's standard event interface. to do this we'll use the event/core module. ...
...rts delegate to the corresponding function from event/core, and use bind() to pass the exports object itself as the target argument to the underlying function. the removelistener() function is implemented by calling the underlying off() function. we can use this module in the same way we use any other module that emits module-level events, such as tabs. ...
Modifying Web Pages Based on URL - Archive of obsolete content
to follow this tutorial you'll need to have learned the basics of jpm. to modify any pages that match a particular pattern (for example, "http://example.org/") as they are loaded, use page-mod module. to create a page-mod, you need to specify two things: one or more content scripts to run whose job is to interact with web content. one or more patterns to match urls for the pages you want to modify. ...
...tp://example.org/") as they are loaded, use page-mod module. to create a page-mod, you need to specify two things: one or more content scripts to run whose job is to interact with web content. one or more patterns to match urls for the pages you want to modify. ...
... specifying the match pattern match pattern uses match-pattern syntax. you can pass a single match-pattern string, or an array. ...
... specifying the match pattern match pattern uses match-pattern syntax. you can pass a single match-pattern string, or an array. ...
Using XPCOM without chrome - Archive of obsolete content
we can then create an object from it and add it as an observer to the bookmarks service. ...
...we can then create an object from it and add it as an observer to the bookmarks service. ...
...we can then create an object from it and add it as an observer to the bookmarks service. ...
...we can then create an object from it and add it as an observer to the bookmarks service. ...
Finding window handles - Archive of obsolete content
erfaces.nsibasewindow); then in c++ part, a function take nsibasewindow as param hwnd getparentwindowhwnd(nsibasewindow *window) { nativewindow hwnd; nsresult rv = window->getparentnativewindow(&hwnd); if (ns_failed(rv)) return null; return (hwnd)hwnd; } that's it; use with caution! ...
...window *window) { nativewindow hwnd; nsresult rv = window->getparentnativewindow(&hwnd); if (ns_failed(rv)) return null; return (hwnd)hwnd; } that's it; use with caution! os specific examples using javascript (js-ctypes) nsibasewindow -> nativehandle in all of the examples below, the native handle to the most recent navigator:browser is obtained and then it is focused. run the snippets below from the scratchpad in environment > browser. ...
...v)) return null; return (hwnd)hwnd; } that's it; use with caution! ...
... components.utils.import('resource://gre/modules/services.jsm'); var browserwindow = services.wm.getmostrecentwindow('navigator:browser'); if (!browserwindow) { throw new error('no browser window found'); } var basewindow = browserwindow.queryinterface(ci.
JS XPCOM - Archive of obsolete content
getting an xpcom service var preferences = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice); you can then call any methods in the nsiprefservice interface on the preferences object. getting a different interface for a component some components implemen...
... methods in the nsiprefservice interface on the preferences object. getting a different interface for a component some components implement more than one interface. sometimes 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. ...
... a component some components implement more than one interface. sometimes 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. ...
...y 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. determining which interfaces an xpcom component supports to display a list of all interfaces that an xpcom component supports, do the following: // |c| is the xpcom component instance for each (i in components.interfaces) { if (c instanceof i) { alert(i); } } in this context, instanceof is the same as queryinterface except that it returns false instead of throwing an exception when |c| doesn't support interface |i|. another difference is that queryinterface returns an object, where as instanceof returns a boolean. xpcomutils - abo...
Progress Listeners - Archive of obsolete content
firefox 3.5 includes a way to set up a listener for all tabs, selected and not: listening to events on all tabs. ...
...firefox 3.5 includes a way to set up a listener for all tabs, selected and not: listening to events on all tabs. ...
...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...
...x 4 / thunderbird 3.3 / seamonkey 2.1), all events are optional. the tabbrowser only notifies you of the events for which you provide a callback. remember to change mylistener to a unique identifier. example: notification when the value in address bar changes a commonly asked question is how to get notified whenever the url in the address bar (also known as location bar) changes. using the following code, you will get notified when user navigates to another page (by clicking a link, using the back/forward button, by typing an address in the location bar, etc.) and also when user switches tabs. var myextension = { oldurl: null, init: function() { gbrowser.addprogresslistener(this); }, uninit: function() { gbrowser.removeprogresslistener(this); }, ...
Rosetta - Archive of obsolete content
e languages (like c), it is even not well defined the meaning of part of their semantics in respect to a scope that is more restricted than the full access to the resources they usually deal with – imagine, for example, the meaning of a c pointer within a html page! ...
...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 us to manually parse them. for a fast overview on the code proposed here you can git clone https://github.com/madmurphy/rosetta.js, or, at your choice, directly download this .zip file. rosetta.
...lla.org/user:fusionchess |*| |*| this framework is released under the gnu public license, version 3 or later. |*| http://www.gnu.org/licenses/gpl-3.0.html |*| |*| syntax: |*| |*| rosetta.appendcompiler([ "text/x-csrc", "text/x-c" ], yourcompiler); |*| \*/ var rosetta = new (function () { function createscript (oscript, oxhr200) { var smimetype = oscript.getattribute("type").tolowercase(), obaton = document.createcomment(" the previous code has been automatically translated from \"" + smimetype + "\" to \"text/ecmascript\". "); if (!odicts.hasownproperty(smimetype)) { alert("rosetta.translatescript() \u2013 unknown mime-type \"" + smimetype + "\": script ignored."); return; } var ocompiled = document.createelement("script"); oscript.pare...
...getsource(oscript) : createscript(oscript); } } function parsedocument () { for ( var ascripts = document.getelementsbytagname("script"), nidx = 0; nidx < ascripts.length; parsescript(ascripts[nidx++]) ); } var odicts = {}, rignoremimes = /^\s*(?:text\/javascript|text\/ecmascript)\s*$/;...
Extension Etiquette - Archive of obsolete content
making extensions, including how to be kind to your users. it assumes that you are already familiar with building an extension. user interface tools menu items using the tool menu option gives the author the maximum amount of choices. whether the extensions should go at the top, bottom, or somewhere in between on the tools menu, the author always has a choice. ideally, the location would be below the add-ons item, grouped with the other extension-related commands (menuitem:insertafter="javascriptconsole,devtoolsseparator"). sub-menus should be used for single extensions needing multiple menu items, and a tools menu item should not be created for options and preferences (for options and preferences, see the add-on manager). if possible, create a menu item in the menu where it is most appli...
... 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 allow for easy identification among other extensions in the extensions manager. coding practices namespace conflicts there are many namespaces which extensions often must share with other consumers, be they other add-ons, web code, or the browser itself. these often include areas such as: object prototypes, such as string.prototype, which are often extended to add methods to native objects. glob...
...paces can't be avoided, the simplest solution to prevent conflicts is to use a distinct prefix for all of your names. class names for html elements created by the cool beans extension, for instance, might all be prefixed with cool-beans-. global variables might all be defined as properties of the coolbeans object. some namespaces have specific conflict prevention conventions, which should be followed as appropriate. xpcom contract ids, for instance, should always begin with an @, followed by a domain name that the author controls, e.g., "@example.com/foo/bar;1" it is important that the prefix that you use be unlikely to conflict with other code, and that it be indicative of the name of your add-on. generic prefixes such as myextension-, or short prefixes such as ffx-, are likely to be use...
...n't have inner working knowledge of mozilla. make sure your extension's homepage states the "obvious," including the purpose of your extension. users also appreciate when your extension is shipped with a simple how-to document. ids firefox/thunderbird 1.5 or later are much more strict about the ids of extensions than their 1.0 counterparts. make sure they're valid. version numbering please follow the mozilla pattern: major version dot current incarnation dot security/bugfix release (like 1.0.7). internationalization locales always use locale dtds and property files, even if providing your extension in one language. it will make translation of your extension to another language easier. it occurs more often than you would think. options firefox users like options. lots of options. try ...
Inline options - Archive of obsolete content
firefox 7 supports a new syntax for defining extensions' preferences for both bootstrapped and traditional 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. options file the xul allowed for the inline options is limited to a few new tags. here is an example of an options.xul file: <?xml version="1.0"?> <!doctype mydialog system "chrome://myaddon/locale/mydialog.dtd"> <vbox xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <setting type="bool" pref="extensions.myaddon.bool" title="boolean" desc="stored as a boolean preference" /> </vbox> note that it's limited t...
...= ' + this.value); this.style.backgroundcolor='red';"> if labels on other toolbar buttons are visible (like by using add-on "classic theme restorer") then show label on throbber toolbar button </setting> note in order for the oninputchanged to execute, the setting must have a pref attribute, otherwise the oninputchanged will not trigger. some discussion on the subject at stackoverflow: how to use addeventlistener on inputchanged of inline options display notifications if you want to use the settings ui for anything more than storing preferences, then you will probably need to initialize them when they first appear. you can't do this until your options xul has been loaded into the add-on manager window, so you should listen for the addon-options-displayed notification to init...
... install.rdf. method 2 use install.rdf to identify the xul file used for displaying the options. this requires that you register a content path in the chrome.manifest. ...
...the chrome.manifest. ...
Jetpack Processes - Archive of obsolete content
rvice, provided by nsijetpackservice, is not included by default in firefox 4. prior to firefox 12, it could be included in custom builds by using enable_jetpack_service at compile time. however, the service has been removed entirely as of firefox 12. these processes are relatively lightweight, do not have access to xpcom, and can innately do little other than compute. messaging facilities that allow them to communicate with their parent chrome process are the only means by which they can be endowed with any real power. note: the above statement is not currently true, as js-ctypes is now provided to jetpack processes as of bug 588563. a mechanism to optionally disable this feature has been proposed in bug 614351. privileged apis when script is evaluated in a jetpack process via a call to nsij...
...ns by which they can be endowed with any real power. note: the above statement is not currently true, as js-ctypes is now provided to jetpack processes as of bug 588563. a mechanism to optionally disable this feature has been proposed in bug 614351. privileged apis when script is evaluated in a jetpack process via a call to nsijetpack.evalscript(), the script's global scope is endowed with the following privileged apis: sendmessage(amessagename [, v1 [, v2 [, ...]]]) similar to nsijetpack.sendmessage(), this function asynchronously sends a message to the chrome process. callmessage(amessagename [, v1 [, v2 [, ...]]]) this function is like sendmessage() but sends the message synchronously. it returns an array whose elements are the return values of each receiver in the chrome process that was...
...hing to indicate that it is no longer needed. if that other process does not do something explicit and simply removes all references to it, the handle remains rooted yet unreachable in both processes and a memory leak is created. to prevent such memory leaks, a process can either invalidate a handle, immediately preventing it from being passed as a message argument, or it can unroot the handle, allowing it to be passed as a message argument until all references to it are removed, at which point it is garbage collected. handles have the following native methods and properties: invalidate() invalidates the handle. either process may invalidate a handle when it is no longer useful. createhandle() creates a child handle which becomes invalid when its parent does. this is useful for associating h...
...l 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 code, check out the unit tests. see also nsijetpackservice nsijetpack ...
Listening to events in Firefox extensions - Archive of obsolete content
so provides some use cases that may be of specific interest. types of events there are multiple types of events that application and extension authors can use to receive notifications from <xul:browser> and <xul:tabbrowser> elements to hear about changes relating to loads of the content contained within them. simple dom events registering for a dom event is done using with code such as the following: function callback(evt) { // do your processing here. check evt.target for the target of the event. } b.addeventlistener("event", callback, false) where b is the browser or tabbrowser you wish to watch for events from. keep in mind that the events may come from any frame within the browser or, for a tabbrowser, any of the browsers within it. some of the more interesting dom events you m...
...hide event from each frame fires before the pagehide event in the main document. for navigation that occurs inside a single frame, events fire only in the affected frame. web progress listeners for more information about web loads a web progress listener can be used; these provide more details about the progress of loading data from the web. both browser and tabbrowser elements support the following: var progresslistener = { // add nsiwebprogressimplementation here } b.addprogresslistener(progresslistener); where b is the browser or tabbrowser you want to listen to events for. there are code snippets available that give more detail on using web progress listeners. for a tabbrowser, the above code will only get events from the browser that is currently displayed at the time the even...
...ner); where b is the browser or tabbrowser you want to listen to events for. there are code snippets available that give more detail on using web progress listeners. for a tabbrowser, the above code will only get events from the browser that is currently displayed at the time the event occurs. in order to listen to events from all browsers, including those not currently being displayed, the following example can be used: var tabsprogresslistener = { // add tabs progress listener implementation here } gbrowser.addtabsprogresslistener(tabsprogresslistener); this lets you receive events related to all tabs. more information about listening to events from all tabs is available. how events are used by firefox the firefox frontend already listens for a number of these progress events fro...
...de notification bars when appropriate as the user navigates apply the site zoom preferences to newly loading pages update the bookmarking star button ui update the identity display as the site's security changes tabsprogresslistener this object is a tabs progress listener and receives events for all browsers in the window. it is used to detect when a webpage attempts to refresh itself and allow the user to block the attempt. how events are used by the tabbrowser tabbrowser maintains a set of objects relating to progress listening for each browser. first it creates a browser-status-filter and adds it as a web progress listener for the browser. next it creates an internal object to receive all web progress events from the browser. this is created by the method mtabprogresslistener(). th...
Adding Events and Commands - Archive of obsolete content
vent propagation. in a nutshell, events propagate from the root of the dom tree all the way down to the target element and then all the way up back to the root, in the capture and bubble phases, respectively. you can capture and cancel events during any of these phases, provided that they aren't canceled before they reach the point where you intended to capture them. the addeventlistener method allows you to control the phase where you want to handle an event, with the last argument of the function. in general, you should avoid adding event handlers in the capturing phase, or canceling events. this can lead to unexpected behavior for the user since most events have a default behavior associated to them. custom events this is a very powerful tool that you should know, even if it isn't that ...
...dle an event, with the last argument of the function. in general, you should avoid adding event handlers in the capturing phase, or canceling events. this can lead to unexpected behavior for the user since most events have a default behavior associated to them. custom events this is a very powerful tool that you should know, even if it isn't that frequently used. the dom createevent function allows you to create custom events that you can dispatch and capture. custom events serve as a good communication mechanism, specially when dealing with a somewhat common problem: communication between window xul and web page content. it isn't hard for xul code to control the content on pages being loaded or displayed, as we will see later on, but it can be hard for your extension xul code to receive ...
...tribute values set or removed as well. you can override pre-existing values, such as the label attribute value in the example. let onlinebroadcaster = document.getelementbyid("xulschoolhello-online-broadcaster"); onlinebroadcaster.setattribute("label", "something"); you can also have finer-grained control to this behavior by adding the observes element as a child to your observer node. this allows you to choose which attributes you want it to observe. broadcasters allow you to easily maintain consistency among numerous elements without having to add much code. they also save you the trouble of having to know if a given element is present in the dom or not. for example, if you have a customizable toolbar, you can't be sure if a given button is present or not, so it's easier to use a broad...
...xulschoolhello-commandset"> <command id="xulschoolhello-hello-command" oncommand="xulschoolchrome.browseroverlay.sayhello(event);" /> <!-- more commands. --> </commandset> <!-- more code here... --> <menuitem id="xulschoolhello-hello-menu-item" label="&xulschoolhello.hello.label;" accesskey="&xulschoolhello.helloitem.accesskey;" command="xulschoolhello-hello-command" /> commands allow you to keep your javascript calls in a single place, avoiding code repetition and possible bugs. your ui can easily scale this way. you can create an extension that adds toolbar buttons, statusbar buttons and menu items, all with equivalent behavior, and without having to repeat lots of xul code in the process. commands and broadcasters also facilitate working with complex form windows and dialog...
Adding sidebars - Archive of obsolete content
sidebar with css or even disable resizing altogether, but none of those are good practices. forcing sidebars to have a fixed size can cause accessibility and usability problems. you can still have plenty of content available in your sidebar, you just need to organize it in a way that doesn't take too much space. for this purpose we'll also look at some handy xul elements in this section. they allow you to stack content on top of other content and switch between different sections easily. the tabbox element the « xul reference « element creates a tabbed view of one or more tabpanel elements. you can see an example of a tabbox element if you open the firefox preferences window and select the advanced section. the tabs are styled to match the operating system you're using, so you should av...
...ned control than the one provided by a tabbox. in these cases the « xul reference « and « xul reference « elements are probably what you're looking for. they are extremely useful, and you'll find yourself using them in many situations besides sidebars. a deck is like a tabbbox without the tabs. it only displays one of its child nodes at a time, depending on its selectedindex value. in the following example, the second child will be displayed, not the first which would be the default. <deck selectedindex="2"> <hbox> <!-- content for the first child. --> </hbox> <hbox> <!-- content for the second child. --> </hbox> </deck> note how this is one of the few cases where an attribute of an element is named using camel case instead of all small caps. the size of the d...
...es a lot of code for something so simple, specially if that's the only case where you need dynamic text. the alternative is to use a deck with the two labels, and change the selected index depending on the purpose of the window. this way you can still use dtd, and the code remains simple. a stack is like a deck, except that all of its children are always on display, one of top of the other. it allows you to decompose complex ui into individual layers, broadening the layout possibilities. one common use for a stack is to have an image background that stretches horizontally and vertically depending on the size of the foreground object: <stack> <hbox flex="1"> <image src="chrome://xulschoolhello/skin/stack-bg.png" flex="1" /> </hbox> <hbox> <!-- some content here. --> </hbox>...
...treechildren> </treeitem> </treechildren> </tree> in this case, the row for "john" has a child row for "john jr.". the « xul reference « element is placed as a child for john's « xul reference « element, and the container attribute must be set. it should be evident at this point that hand-coding a tree would take quite some time and yields a great deal of xml code that is hard to follow. this is why most of the uses of the tree element are for displaying data from an external datasource. even handling the construction of a tree using javascript and dom functions can become very convoluted, which is why trees are better used along with templates. this topic will be covered later when we look at different kinds of datasources and templates. adding style to a tree can also be chal...
Appendix A: Add-on Performance - Archive of obsolete content
ave 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 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-...
...h 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 provide the cleanest way to separate js into modules...
...ed multiple times during a single page load, and having inefficient code in the event handlers can cause a noticeable delay that users may have hard time figuring out. look at the source samples in the article and notice how they mostly consist of nested if statements. this is what you should do first to make sure that you filter out all cases that don't interest you so that your add-on doesn't slow down other requests. a very common filter is the url of the page, since most add-ons are limited to one or a few domains. use regular expressions if you need to. make sure your comparison code is as efficient as possible. finally, make sure all of your page load code is as efficient as possible. this can be tricky for some add-ons, like ad or script blockers that need to check a whitelist or bla...
...isteners, observers and other handlers normally have both an add and a remove function. don't forget to remove what you don't need anymore! even if you need something during the whole existence of the window, you should clean everything up in the unload event handler. even the unload event should be handled efficiently. even if it is not as important as other areas, firefox shutdown can also be slowed down because of add-ons. if there's anything you can unload before shutdown, or if there's anything you can do to unload things more efficiently, then it's important that you do. never use xmlhttprequest in synchronous mode. if your add-on needs to perform a heavy operation like sorting or a complex mathematical calculation, you should use dom workers to offload the work to other threads. ...
Appendix F: Monitoring DOM changes - Archive of obsolete content
unfortunately, adding listeners for any of these events to a document has a highly deleterious effect on performance, an effect which is not mitigated in the slightest by later removing those listeners. for this reason, it is best to avoid using mutation listeners at all costs, especially from extensions. this document lays out some alternatives which do not have such severe performance impacts. mutation observers mutation observers are the more efficient, w3c speced replacement for the highly inefficient mutation events. ...
... are fired very often while the mouse is moving. monkey patching in many instances, especially when dealing with chrome code, the best way to modify actions which result in dom mutations is by wrapping the functions that trigger those changes. ...
...variations on this method include modifying the arguments passed to the wrapped function, modifying its return value, and making changes both before and after the original method is called. ...
...the original method is called. this scheme is highly flexible and can be made to work under most circumstances. css animation events this technique, which works on firefox 5+, has some particular advantages. because it is based on css, it can be keyed to match new elements of any arbitrary css selector. and because it is css-based, and is triggered when css is being applied anyway, it does not slow dom mutations. the technique was adapted from the method used by the 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 fallba...
Local Storage - Archive of obsolete content
t you don't need to figure out its location. in general this is the only directory flag you'll need, but sometimes you'll need access to other system directories, and you don't want to have to worry about which operating system or system language your extension is running on. a full list of these flags can be found in the firefox source. having that function in place, we do something like the following: let myfile = xulschool.getlocaldirectory(); myfile.append("somefile.txt"); // do stuff with the file. files are handled with the nsifile interface. an nsifile doesn't necessarily represent an existing file, as in the previous examples. you first specify the file using nsifile and then use nsifile.create() to actually write it out to disk. you can also check if an nsifile exists using nsifi...
... come up with a javascript implementation of a logger similar to the log4j logger used in java projects. the logger is called log4moz and it is implemented as a javascript code module, so it only works on firefox 3 and above. to use this logger, you need to copy the log4moz.js file to your modules directory. in the initialization method of your one of your "common" or startup objects, add the following code: let formatter = new log4moz.basicformatter(); let root = log4moz.repository.rootlogger; let logfile = this.getlocaldirectory(); // remember this? let appender; logfile.append("log.txt"); // loggers are hierarchical, lowering this log level will affect all // output. root.level = log4moz.level["all"]; // this appender will log to the file system. appender = new log4moz.rotatingfileapp...
....addappender(appender); after that, you can create a logger object for any object in your project like this: this._logger = log4moz.repository.getlogger("xulschool.someobject"); this._logger.level = log4moz.level["all"]; note: we recommend that you create a logger instance in the constructor of every object and store it in a private variable. ...
...he rdf api may be removed at some point in the future because it requires a great deal of code even for the simplest tasks, and it currently sees little maintenance, so we don't recommend using 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 co...
Extensions support in SeaMonkey 2 - Archive of obsolete content
<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. ...
...ommunicator/content/bookmarks/bm-panel.xul chrome://browser/content/places/places.xul chrome://communicator/content/bookma...rksmanager.xul thunderbird uses mostly the same chrome urls for overlaying as seamonkey. there are exceptions, but these are few and far between. seamonkey also uses different ids for the menu items. ...
...bottombox", which encloses the find bar and status bar at the bottom of the browser window. although this doesn't affect the appearance of the display, it may affect your extension if it overlays chrome relative to these elements. ...
...d expansion cc components.classes ci components.interfaces cr components.results cu components.utils multi-browser compatibility to make an extension compatible with seamonkey as well as firefox/thunderbird, you may need to do different things depending on which application is running the extension. ...
Session store API - Archive of obsolete content
uence 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 the session store), and cookies and the list of recently closed tabs are restored. after that, the following steps are taken for each tab being restored: either an existing tab is reused or a new tab is created. in the latter case, a tabopen event is sent. the tab's persistent xul attributes (those saved due to calls to persisttabattribute()) and permissions are restored. the sstabrestoring event is sent. the tab is told to load the url it should be displaying. when the page is finished loadin...
...g 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 key/value pair to a tab, so that when the tab is restored, that pair is still associated with it. var ss = components.classes["@mozilla.org/browser/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); var currenttab = gbrowser.selectedtab; var datatoattach = "i want to attach this"; ss.settabvalue(currenttab, "key-name-here", datatoattach...
...tedtab; var datatoattach = "i want to attach this"; ss.settabvalue(currenttab, "key-name-here", datatoattach); this code sets the value of the key "key-name-here" to datatoattach. you may use any javascript object as the data. fetching a saved value you can fetch a value associated with a tab at any time (whether the tab is in the process of being restored or not), using code similar to the following: var ss = components.classes["@mozilla.org/browser/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); var currenttab = gbrowser.selectedtab; var retrieveddata = ss.gettabvalue(currenttab, "key-name-here"); after this code executes, the variable retrieveddata contains the value saved for the key "key-name-here". retrieveddata is undefined if there is no v...
...nstore); var currenttab = gbrowser.selectedtab; var retrieveddata = ss.gettabvalue(currenttab, "key-name-here"); after this code executes, the variable retrieveddata contains the value saved for the key "key-name-here". retrieveddata is undefined if there is no value saved for that key name. deleting a value associated with a tab to delete a value from a tab, you can use code similar to the following: var ss = components.classes["@mozilla.org/browser/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); var currenttab = gbrowser.selectedtab; ss.deletetabvalue(currenttab, "key-name-here"); remarks the window value save and restore functions work exactly like the tab-based functions by similar names. starting in firefox 3.5, notifications are sent after...
Setting up an extension development environment - Archive of obsolete content
settings, and further isolating personal data (such as bookmarks, extensions, and settings) from your testing environment. you could be running two instances of firefox simultaneously. note: for an extended guide on how to set up even more user profiles, take a look at multiple firefox profiles. this particularly comes in handy for the use of all currently available firefox versions. it even allows the running of simultaneous versions, at the same time. to quickly achieve our task of creating just a developer profile, we will start the application with the parameters: /path/to/firefox -no-remote -p profilename without these parameters, the default behavior of your mozilla applications is to only open the everyday user profile: named default. as we are specifically defining the user pro...
... start the application with the parameters: /path/to/firefox -no-remote -p profilename without these parameters, the default behavior of your mozilla applications is to only open the everyday user profile: named default. as we are specifically defining the user profile dev, if you don't have the dev profile already created, the profile selection window opens, where you can create it. in the following example, the described command starts a new instance of firefox, with a profile called dev; even if an instance of firefox is already running. on ubuntu (and many other linux distributions): /usr/bin/firefox -no-remote -p dev on other distributions of linux/unix: /usr/local/bin/firefox -no-remote -p dev on macos mavericks (10.9) and newer: /applications/firefox.app/contents/macos/firefo...
... of firefox you may choose any profile you like. development command flags as of gecko 2 (firefox 4), javascript files are cached ("fastload"). the -purgecaches command-line flag disables this behavior. alternatively, you can set the moz_purge_caches environment variable. see this bug for more information. development preferences there is a set of development preferences that, when enabled, allows you to view more information about application activity, thus making debugging easier. however, these preferences can degrade performance, so you may want to use a separate development profile when you enable these preferences. accessing firefox development preferences to change preference settings in firefox or seamonkey, type about:config in the location bar. you can also use the extension ...
...xtension\ on windows. remember to include the closing slash and remove any trailing whitespace. note: if you already installed the extension via xpi, you should uninstall it first before creating the pointer file. also note that the use of proxy files requires that the extension's chrome.manifest defines its chrome urls using traditional directories, rather than a jared structure. see below. place the file in the extensions folder of your profile and restart the application. using directories rather than jars regardless of whether you choose to eventually package your extension's chrome in a jar or in directories, developing in directories is simpler. if you choose a jared structure for releasing, you can still develop with a directory structure by editing your chrome.manif...
Search Extension Tutorial (Draft) - Archive of obsolete content
prompt for users. other settings violations designed to restrict user choice will result in stronger action, such as blacklisting of the add-ons in question. the most technically sound method of achieving this, and the only acceptable way of changing preferences such that they are automatically restored on add-on uninstall, is to make such changes in the default preference branch, as explained below. while the technical details below are important to understand, a library which encapsulates the appropriate logic is provided along with the example add-on 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 preferen...
...h encapsulates the appropriate logic is provided along with the example add-on 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,...
...nename=example engine"); in the case or restartless extensions, the preferences need to be changed manually, and reverted when the extension is disabled if they have not been changed in the meantime. while changes to default preference values will not persist across sessions, restartless extensions must nevertheless restore them for the balance of the session after they have been disabled. the following example bootstrap.js file illustrates the method: const { classes: cc, interfaces: ci, utils: cu, results: cr } = components; // import the services module. cu.import("resource://gre/modules/services.jsm"); // keep track of whether this is the first run. var firstrun = false; // get the root user preference branch. var userprefs = services.prefs.getbranch(""); // get the root default prefer...
...ctly via an xml description file. while the former is the simpler method, it does not support complex descriptions containing suggestion urls or separate keyword search urls. note: example uninstall code is only provided for restartless extensions. a separate tutorial exists for running code at uninstall in non-restartless extensions. an example bootstrap.js file illustrating the simple method follows: const { classes: cc, interfaces: ci, utils: cu, results: cr } = components; // import the services module. cu.import("resource://gre/modules/services.jsm"); // the details of the engine to add const engine_details = { name: "example engine", iconurl: "data:image/png;base64,...", alias: "example-engine", description: "an example search engine", method: "get", // the http re...
Bookmark Keywords - Archive of obsolete content
this might be used to reduce typing of a common url: http://www.cnn.com/ could be given the keyword cnn. once that's done, all it takes to go to the cnn home page would be to type <tt>cnn</tt> into the address bar. mozilla will automatically expand the keyword to the corresponding bookmarked url, and load up the site. that's pretty interesting on its own, but mozilla takes it a step further by allowing the user to define an "entry point" for added information. for example, a keyworded bookmark could be set up so that a user could type <tt>google spam and eggs</tt> and thereby trigger a google search for the words "spam and eggs." because these tools require bookmarks with specific keywords in order to work, they will be referred to hereafter as keymarks, as distinct from regular bookmarks. ...
... here." it doesn't have to go at the end of the location field-- it can be anywhere inside the field. you just need to fill in whatever piece of a url it is you want to be able to "fill in" when you use the keymark. all we need now is a keyword, and our keymark will be ready to go. fill in the value bz, as shown in figure 5. with that done, all you have to do in the future is type <tt>bz</tt> followed by a space and the bug's number into mozilla's address bar, and the browser will jump right to the bug with that number. this is illustrated in figure 6. that's all it takes! setting up a google keymark to set up a keymark that will search google directly form the address bar, go to google and run a search for any word. once you get a result page, bookmark that page. you'll need to replace ...
...is case, we'll give it a keyword and title of google and replace the term "geitost" with the %s, as shown (with extra highlighting) in figure 8. now we can run google searches straight from the address bar. these searches can be as complex as google will tolerate, since the entered data will be converted to url-encoded text before it's sent to the google servers. thus we could type any of the following into the address bar and get back useful results: <tt>google geitost</tt> <tt>google mozilla keyword bookmark</tt> <tt>google bookmark site:developer.netscape.com</tt> <tt>google netscape xml support -site:netscape.com</tt> a few examples in the course of writing this article, a number of potentially useful bookmarks were considered as possible examples. instead of just throwing them a...
... results: <tt>google geitost</tt> <tt>google mozilla keyword bookmark</tt> <tt>google bookmark site:developer.netscape.com</tt> <tt>google netscape xml support -site:netscape.com</tt> a few examples in the course of writing this article, a number of potentially useful bookmarks were considered as possible examples. instead of just throwing them away, we're providing them for you in the following table. even better, you can file them for future use by right-clicking (or holding down the control key and clicking on the link) and filing the bookmarks using the "file bookmark..." option in the contextual menu that pops up. once that's been done, making the keymark work is a simple matter of going into the bookmark manager and adding a keyword! bookmark suggested keywords find bugzill...
Structure of an installable bundle - Archive of obsolete content
xulrunner applications, extensions, and themes all share a common directory structure, and in some cases the same bundle can be used as a standalone xulrunner application as well as an installable application extension. basic structure of a bundle a bundle may include any of the following files: path from the root of the bundle description version information /install.rdf extension/theme install manifest /application.ini application launch manifest /bootstrap.js the bootstrap script for extensions not requiring a restart (those with <em:bootstrap>true</em:bootstrap> in their install.rdf). note that other files and directories (e.g. chrome.manifest, components, defaults) in bootstrapped extensions are not processed by ...
...ies firefox 2 and greater of course, an extension need not (and normally won't) have all of these directories. themes are limited for security reasons, and can normally only provide a chrome.manifest which registers the theme and a jar file. platform-specific files gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) removed support for platform-specific subdirectories, described below. instead, you need to use manifest flags, such as the os and abi flags, in your chrome manifest to specify components that should be loaded for specific platforms. for example: binary-component components/windows/mycomponent.dll abi=winnt_x86-msvc binary-component components/mac/mycomponent.dylib abi=darwin_x86-gcc3 binary-component components/mac/mycomponent64.dylib abi=darwin_x86_64-gcc3 bina...
...abi} all of the files which are loaded from the main extension directory are loaded from the subdirectory /platform/{platform string} if it exists. ...
...when default preferences are defined in several directories, the ones loaded later overwrite the earlier ones. official references for toolkit api structure of an installable bundle: describes the common structure of installable bundles, including extensions, themes, and xulrunner appl...
Dehydra Function Reference - Archive of obsolete content
see the dehydra object reference for details on the available object properties. process_type(type) dehydra calls this for each class, struct, enum, union, and typedef declaration. process_type is called after process_function is called for all the member functions. type is a type object representing the type that was declared. ...
...of variable types} representing an outline of the function stripped down to variables, function calls and assignments. process_decl(decl) process_decl is called for every global variable, function, or template declaration. decl is a variable type input_end() called once at the end of the c++ source file before the compiler quits. this is useful for finalizing analyses. builtin functions the following functions are provided by dehydra and may be called by the user: print(msg) print a string to stdout (or stderr if the compiler is piping output). if the current callback is associated with a particular location, the location will be printed first. msg is a string to output to customize the location info printed set this._loc before calling print() include(file [, namespace]) include a javas...
...r rooting bugs. gczeal is only enabled when spidermonkey and dehydra are compiled with debug macro defined. require() example require({strict:true, gczeal:2}) if (require().werror) print("werror is set") warning([code,] msg [, loc]) print a warning message using the gcc warning mechanism. if -werror is specified this will cause compilation to fail. optional: code is an integer parameter that allows warnings to be enabled(-wfoo) and disabled(-wno-) on the gcc commandline. this parameter is used when the first argument to warning() is an integer. it is not possible to define new warnings in dehydra, thus one has to figure out a warning code from an existing warning and hijack it for ulterior purposes. msg is a string to be presented as a gcc warning optional: loc is the location that should ...
...rom the last process_type or process_function. error(msg [, loc]) print an error message using the gcc error mechanism. this will cause compilation to fail. msg is a string to be presented as a gcc error optional: loc is the location that should be reported for the warning. if no location is provided, the location is inferred from the last process_type or process_function. _print(msg, ...) the low level function called by print(). it does not print the location. read_file(filename) read a file a return it as a string. write_file(filename, data) write a string to a file. builtin objects sys this.sys is a container for miscellaneous properties exposes by dehydra sys.gcc_version is a gcc version string sys.include_path exposes the search path used by include(). the default value is the follo...
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
ete since gecko 4.0this 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. warning: this technology is obsolete. no active maintainer has stepped forward, and the code broke in firefox 4. the code has been removed from the mozilla source tree. xulrunner ships with the javaxpcom component, which allows java code to interact with xpcom objects. as you will see in this article, working with xpcom objects in java is not that much different than doing so in c++. prerequisites java 1.4.2 or newer xulrunner 1.8.0.1 or newer embedding in order to embed mozilla in your java application, you will need to add the library mozillainterfaces.jar (located in xulrunner/sdk/lib folder) to your classpa...
...ed by the java application. it implements the iappfilelocprovider interface, and tells xpcom where to find certain files and directories. if your code cannot find the gre and keeps throwing filenotfoundexceptions during the getgrepathwithproperties(...) call, check whether you already registered the gre on your system: gre registration the initembedding method kicks off the embedding process, allowing the java application to work with xpcom and mozilla. once the java application is done using mozilla, it needs to terminate the embedding process: try { mozilla.termembedding(); } catch (xpcomexception e) { // this exception is thrown if termembedding failed } working with xpcom objects now that mozilla is embedded, the java application can work with xpcom objects. the mozilla cla...
...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 addition to retrieving and calling methods on xpcom objects, javaxpcom allows the java application to pass java class objects to xpcom methods. for example: mozilla mozilla = mozilla.getinstance(); windowcreator creator = new windowcreator(); // implements nsiwindowcreator nsiservicemanager servicemanager = mozilla.getservicemanager(); nsiwindowwatcher windowwatcher = (nsiwindowwatcher) servicemanager .getservicebycontractid(ns_windowwatcher_contractid, n...
...l; if (aprop.equals("apluginsdl")) { files = new file[1]; files[0] = new file(libxulpath, "plugins"); } return files; } } calling xpcom ui from another thread appstartup.run() enters the main event loop and will stay there until the application exits. in order to communicate with xpcom after this point, you should use an nsiproxyobjectmanager. following on from the above example, to create a new window, we would do the following: // first, get the event queue service. this handles all event queues in xpcom. nsieventqueueservice eventqueueservive = (nsieventqueueservice)servicemanager.getservicebycontractid("@mozilla.org/event-queue-service;1",nsieventqueueservice.ns_ieventqueueservice_iid); // next, we want to get the ui thread, since w...
Layout FAQ - Archive of obsolete content
mozilla.dev.tech.layout faq is there a way to do profiling of what is going on in mozilla? 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. ...
...n 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? ...
...ows 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? ...
...d 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? ...
GRE - Archive of obsolete content
this document describes how embedders should dynamically link to a gre. to understand how gres are registered, see gre registration. the xre project, which means "xul runtime environment", has been replaced by xulrunner. mozilla suite: the old gre there are two different forms for the gre: the "old" gre was part of the mozilla application suite. ...
...as part of the mozilla application suite. it was installed with the windows installer of mozilla 1.4 through 1.7.x. there was never an official gre shipped for linux, but various distributors such as red hat have registered mozilla installations as if they were a gre. the mozilla suite never supported a gre on mac. xulrunner: the new gre xulrunner is the new version of the gre, which not only allows embedding but is capable of bootstrapping entire xul applications such as firefox. xulrunner supports or is planned to support embedding on all three major platforms (windows, mac, and linux). finding and using a gre from application code avoid linking directly against xpcom.dll if an application wishes to use the gre, it must take careful steps to ensure that it links against the proper libr...
...m.so (xpcom.lib import lib), your application will not launch unless xpcom.dll is in your path. this prevents dynamically finding a compatible gre at runtime. find a compatible gre note: support for locating a standalone glue was removed in gecko 6.0. to find a compatible gre, you should use the function gre_getgrepathwithproperties() (declared in xpcom/glue/standalone/nsxpcomglue.h). this allows the embedder to specify what version(s) of gre are appropriate, and to specify any special features the gre must have (currently there are no special features defined). statically link to xpcomglue.lib (the "standalone glue") the solution is to statically link against xpcomglue.lib, also known as the "standalone glue" (see xpcom glue). this library provides a layer of indirection between embed...
...ropriate, and to specify any special features the gre must have (currently there are no special features defined). statically link to xpcomglue.lib (the "standalone glue") the solution is to statically link against xpcomglue.lib, also known as the "standalone glue" (see xpcom glue). this library provides a layer of indirection between embedding code and xpcom. to use the xpcom glue, you must follow these steps: compile your code with xpcom_glue defined. link with xpcomglue.lib (not xpcomglue_s.lib!). don't link against the nspr libs. find a compatible gre (see above). dynamically link to that gre using the xpcomgluestartup() function. see environment variables below. initialize xpcom and do your work; when finished, shut down xpcom. unlink xpcom with xpcomglueshutdown(). dependent...
Nanojit - Archive of obsolete content
nanojit as their back end. you can get nanojit by cloning the tamarin-redux mercurial repository at http://hg.mozilla.org/tamarin-redux. it's in the nanojit directory. the input for nanojit is a stream of nanojit lir instructions. the term lir is compiler jargon for a language used internally in a compiler that is usually cross-platform but very close to machine language. it is an acronym for "low-level intermediate representation". a compiler's lir is typically one of several partly-compiled representations of a program that a compiler produces on the way from raw source code to machine code. an application using nanojit creates a nanojit::lirbuffer object to hold lir instructions. it creates a nanojit::lirbufwriter object to write instructions to the buffer. then it wraps the lirbufwr...
... the instructions are in the lirbuffer, the application calls nanojit::compile() to produce machine code, which is stored in a nanojit::fragment. internally to nanojit, another set of filters operates on the lir as it passes from the lirbuffer toward the assembler. the result of compilation is a function that the application can call from c via a pointer to the first instruction. example the following code works with spidermonkey's hacked version of nanojit. figuring out how to compile it is left as an exercise for the reader; the following works when run in the object directory of an --enable-debug spidermonkey shell: g++ -ddebug -g3 -wno-invalid-offsetof -fno-rtti -include js-confdefs.h -i dist/include/ -i.. -i ../nanojit -o jittest ../jittest.cpp libjs_static.a note: remove the -ddeb...
... includes code where the raw lir is first converted into machine code.(where compile(fragmento->assm(), f); is called basically). then a pointer to a function is used, which takes an int as input and returns the sum of that parameter with two. (typedef js_fastcall int32_t (*addtwofn)(int32_t); ) then, printf is hardcoded to call it with a parameter 5, and on linking with nanojit library, the following program will display 2+5=7 now, what i need to do is generate output for this: start two = int 2 twoplustwo = add two, two ret twoplustwo this adds two and two in the most hardcoded way possible. the conversion from lir to a program like one shown above is the task of the parser. guards guards are special lir instructions, similar to conditional branches, with the difference that when...
...r to conditional branches, with the difference that when they are called, instead of going to a particular address, they leave the jit code entirely, and stop the trace. need guards are required in a cross platform dynamic language like javascript. certain assumptions are made when a particular jit code is generated. for example, in an instruction inr x, a guard would check that x doesn't overflow the range for a 32 bit integer. the jit code would have a guard checking this condition(an xt guard), and would return to the interpreter if the condition turns out to be true. the interpreter is then equipped to handle the overflow. hence, guards are needed to prevent certain erroneous behaviour that might result from the assumptions that are generally made while jit is generated. todo: explai...
Plug-n-Hack - Archive of obsolete content
their browser if any of these steps are carried out incorrectly then the browser will typically fail to connect to any website – debugging such problems can be frustrating and time-consuming. 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 functionality without having to switch to and from the tool. while some of the pnh capabilities do have a fixed meaning, particularly around proxy configuration, most of the capabilities are completely generic, ...
...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 functionality without having to switch to and from the tool. while some of the pnh capabilities do have a fixed meaning, particularly around proxy configuration, most of the capabilities are completely generic, allowing tools to expose whatever functionality they want. implementing the above features in firefox and the tools that we work on and support gives our team an advantage, however we believe that opening up such capabilities to all browsers and all security tools is much more useful for security researchers and application developers and testers. as a result we have designed and developed the pnh prot...
...hers and application developers and testers. as a result we have designed and developed the pnh protocol to be both browser and tool independent. the current protocol and firefox implementation are released under the mozilla public license 2.0 which means it can be incorporated in commercial tools without charge. ...
...he pnh protocol to be both browser and tool independent. the current protocol and firefox implementation are released under the mozilla public license 2.0 which means it can be incorporated in commercial tools without charge. ...
Scripting - Archive of obsolete content
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. ...
...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. ...
... 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 nsiplatformglue interface, whose methods are described in the following section. methods of the window.platform object can be called from webapp.js or from web content. the following code can be used by web content to determine whether it is running in prism: if ("platform" in window) { // prism-specific code goes here } see the nsiplatformglue idl definition file for details of the methods available to prism apps. currently, the webapp script also has access to...
... apps. 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. it means that the script has a higher level of privilege than scripts in the web content and has access to the file system, clipboard and other parts of the native os. note: in the future, the webapp script may have lower privileges. we are looking into the security aspects of the higher privilege level. ...
The life of an HTML HTTP request - Archive of obsolete content
the nscssframeconstructor, which creates frames for each content node according to the rules specified in the user agent stylesheet (ua.css) and the document specific style sheets. each content node corresponds to one or more nsiframe, except content with displaytype "none". ...
...or each content node according to the rules specified in the user agent stylesheet (ua.css) and the document specific style sheets. each content node corresponds to one or more nsiframe, except content with displaytype "none". if there are several frames created from a content node, then the first of these are called the "primary" node, and the following frames can be found by using the getnextinflow() method of nsiframe. ...
...es specified in the user agent stylesheet (ua.css) and the document specific style sheets. each content node corresponds to one or more nsiframe, except content with displaytype "none". if there are several frames created from a content node, then the first of these are called the "primary" node, and the following frames can be found by using the getnextinflow() method of nsiframe. the initial reflow is done by the nshtmlcontentsink::startlayout(), startlayout() calls presshell::initialreflow(). startlayout is called quite early in the parsing process, for html it's called in nshtmlcontentsink::openbody() (among other places). todo: how are nsiframes reflowed after a change when they already exist? (8) each nsiframe knows how how to draw itself on the screen. when the presshell [note: not t...
...these get passed references to the presentation context and a rendering context to do the drawing on. the rendering context implementation is a native class (nsgtkrenderingcontext on unix) that knows how to draw in a window. ...
execute - Archive of obsolete content
summary launches a file inside the install archive. method of install object syntax int execute ( string xpisourcepath [, boolean blocking]); int execute ( string xpisourcepath, string args [, boolean blocking]); parameters the execute method has the following parameters: xpisourcepath the pathname of the file to extract and execute. (note that this path points into the xpi itself.) args a parameter string that is passed to the executable. (ignored on mac os). see note below. blocking a boolean value that specifies whether the installation should wait for the execution of 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. r...
...at the installation should wait for this executable to finish before processing the next queued install command. if you do not set this flag and launch an executable that is not a part of the installation, you will raise an error when you restart the browser. passing arguments to the executable the args parameter, when present, passes a string to the executable as command-line parameters. the following line, for example, passes the "-c" command-line parameter to the executable: err = file.execute(myfile, "-c", true); when you want to pass more than one parameter to the executable itself, however, you must format the args string in a particular way so that the parameters can be broken up and passed separately as required. in general, you should use single quotes for the args string and doub...
... executable: err = file.execute(myfile, "-c", true); when you want to pass more than one parameter to the executable itself, however, you must format the args string in a particular way so that the parameters can be broken up and passed separately as required. in general, you should use single quotes for the args string and double quotes to delimit the command-line arguments within args. the following parsing rules apply: double quotes are treated as quotes; single quotes are ignored by the executable but legal in the execute() method. the outer quotes that frame the args string itself are stripped off when the string is passed to the executable. quotes that are escaped, or "backslashed," are passed through the executable intact. all other backslashed cases are ignored. this means...
...xecute() method. the outer quotes that frame the args string itself are stripped off when the string is passed to the executable. quotes that are escaped, or "backslashed," are passed through the executable intact. all other backslashed cases are ignored. this means that in order to pass three command-line arguments (-c, -d, and -s) to the executable, you should format the args string as follows: err = file.execute(myfile, '"-c""-d""-s"', true); //technically, given the rules above, you could also pass the same //arguments with the following line, but the result is much less //readable: err = file.execute(myfile, "\"-c\"\"-d\"\"-s\"", true); also see the note about binaries on the macintosh platform in addfile. ...
Accessing Files - Archive of obsolete content
e! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. accessing files this section describes how to create a file reference. retrieving a file when working with files, usage is always done via a file object and not via string paths. this allows files to used in a portable way. because string paths are not used, references to files in a file object are made relative to some starting directory. a number of starting directories may be used, for instance, the user's home directory, the desktop, the system's temporary folder, and so forth. once one of these starting directories is determined, a file reference may be created relative to this...
...f 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 to a file named sample.txt located in the profile directory. var file = io.getfile("profile", "sample.txt"); the nsiscriptableio object is a global object always available within an application or extension which provides a number of useful functions for dealing with files. one such method it provides is nsiscriptableio.getfile() which returns a new nsifile o...
... is the starting directory from which to locate a file. in the example above the word 'profile' is used, which means start from within the user's profile directory. the actual location of this directory will vary by user and system, so this is a convenient means to refer to a common directory without having to locate it yourself. for a full list of starting directories, see starting directories below. the second argument to nsiscriptableio.getfile() is the filename to locate, which, here, is 'sample.txt'. the result is that a reference is made to the 'sample.txt' file. it is important to note that this file does not have to exist for a file reference to be valid. that is, nsiscriptableio.getfile() will still return a valid file reference even if the file 'sample.txt' does not yet exist. you c...
...access a directory and iterate through subdirectories until you come to the file that you want. for more information about this, see working with directories. starting directories the examples above use the profile directory 'profile' as the starting directory for locating a file. there are several other values which may be used as the first argument to nsiscriptableio.getfile(), listed in the following table. application the directory of the executing application. for firefox, for instance, this will be the directory where firefox is installed. for a xulrunner application, this will be the directory where the application is installed. working the current working directory. if the application was launched from a command line, for instance, this will ...
loadOneTab - Archive of obsolete content
there's also no owner parameter as the owner tab is specified automatically. ...
...there's also no owner parameter as the owner tab is specified automatically. ...
...there's also no owner parameter as the owner tab is specified automatically. parameters inbackground if true the tab will be loaded in the background, if false the tab will be the newly selected tab. ...
... is specified automatically. parameters inbackground if true the tab will be loaded in the background, if false the tab will be the newly selected tab. and if null or not specified, this parameter will default to the browser.tabs.loadinbackground preference. firefox 3.6 note the second form of this method was added in firefox 3.6; it adds the relatedtocurrent parameter, and allows the parameters to be specified by name, in any order. ...
Panels - Archive of obsolete content
note that the panel is not placed in a separate file and is instead placed inside another window. ...
...fault, appear with its topleft corner just underneath the bottom edge of the button, much as a menu does. the position can, however, be changed. for more information about positioning the popup, see positioning popups. only buttons (and toolbarbuttons) have this automatic behaviour which opens the popup when pressed. for other types of elements, you need to use a different technique as in the following example. <label value="search" popup="search-panel"/> <panel id="search-panel"> <label control="search" value="terms:"/> <textbox id="search"/> </panel> to attach a panel to an non-button element, for instance to have a panel open when a label is clicked, use the popup attribute. the popup attribute should be set to the id of a panel within the same document. when the left mouse butt...
... attach a panel to an non-button element, for instance to have a panel open when a label is clicked, use the popup attribute. the popup attribute should be set to the id of a panel within the same document. when the left mouse button is pressed on the element with the popup attribute, the corresponding panel will be displayed. for instance, to attach the popup defined above to a label, use the following code: <label value="search" popup="search-panel"/> the result is a search button which opens a panel for entering the search term. when using the popup attribute, the panel will appear with the top left corner at the mouse position. in this case, you may wish to have the popup appear below the label instead. the position attribute may be used to control the placement of the popup. here is a...
... a panel like a context menu using the context attribute instead of the popup attribute. this works just like using context menus except that the panel element is used instead of the menupopup element. see context menus for more details on this. opening a panel with script the panel, like all popups, has an openpopup method which may be used to open the popup using a script. for example, the following would open a panel underneath a button: panel.openpopup(button, "after_start", 0, 0, false, false); likewise, the openpopupatscreen method will open a panel at a specific screen position. for more details about both methods, see opening and closing popups. closing a panel a panel is closed automatically when the user clicks outside of the panel. it is quite common however, to have an elem...
PopupEvents - Archive of obsolete content
this event will be fired even for elements that don't have a context menu associated with them. for more information about how to use this event, see context menu events. popupshowing this event is fired on a menupopup, panel or tooltip just before it is made visible. this event is most commonly used to add or adjust items on the popup based on the context. ...
..."show time" popup="time-panel"/> you can prevent a menu or popup from appearing by calling the preventdefault method of the event from within a popupshowing listener. the default operation of the popupshowing event is to continue showing the popup. the preventdefault method will stop this from happening and the popup will not be opened. <menu label="edit"> <menupopup onpopupshowing="if (gdisallowed) event.preventdefault();"> <menuitem label="undo"/> <menuitem label="redo"/> </menupopup> </menu> in this example, a global variable gdisallowed is checked and the preventdefault method is called. if you want to prevent a context menu from opening it is better to call preventdefault with a handler for the contextmenu event instead, to avoid the extra steps necessary to fire the popup...
.... the popupshown event the popupshown event is fired once a popup is already visible. when calling either the openpopup or openpopupatscreen methods, the popup will not actually be open before that method returns. the popupshown event will be fired when the ui is updated and the popup is visible. one possible use of the popupshown event is to open another menu. this technique, as shown in the following example, is needed if you wish to open a submenu programmatically. this is because you cannot open a submenu directly without first opening the parent menu. <script> function openfilemenu() { var filemenu = document.getelementbyid("file-menu"); filemenu.addeventlistener("popupshown", filemenuopened, false); filemenu.open = true; } function filemenuopened(event) { if (event.target != d...
... the menu is removed from the document. this is because there is no longer an element to send the events to. another situation is when the document is being unloaded. the popuphidden event the popuphidden event is fired after a popup has been closed. when a chain of menus is opened, that is, when a menu and at least one level of submenus is opened, first the popuphiding event will be fired on the lowest level of submenu. then that menu will be closed and the popuphidden event will be fired. this process will then repeat for the next highest level of menu until all the menus are closed. this means that when a long chain of submenus is opened, a number of popuphiding and popuphidden events will be fired in sequence. you can tell that the entire chain is closed when the topmost menu receives a p...
Actions - Archive of obsolete content
« previousnext » the content to generate in a template is specified using the <xul:action> element which should either be the next sibling of the <xul:query> element (if no rules need be specified) or be a direct child of a <xul:rule> element. the content to generate goes directly inside the action element. this content will be copied for each matching result (though see below for an exception) and inserted into the document. let's look at a simple example first. <vbox datasources="http://www.xulplanet.com/ds/sample.rdf" ref="http://www.xulplanet.com/rdf/a"> <template> <query> <content uri="?start"/> <triple subject="?start" predicate="http://www.xulplanet.com/rdf/relateditem" object="?relateditem"/> </query> <act...
... 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 would have generated the following content: <button id="http://www.xulplanet.com/rdf/b" label="http://www.xulplanet.com/rdf/b"/> naturally, you wouldn't use an id attribute inside a template action since the id would be replaced anyway. in fact, any ids you put inside a template 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 st...
...ou 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. ...
...rated elements should be given a particular id. although the uri attribute should only be on one element, it does not have to be the outermost element in the action body. you can place other elements outside this to serve as containers for all the results. one difference is that this content is only generated once, not for every result. only the content at the element with the uri attribute and below is copied for each result. for example, if the example were modified to the following: <action> <toolbar> <button uri="?relateditem" label="?relateditem"/> </toolbar> </action> here, only the button would be repeated for each result; the toolbar will only be generated once. the toolbar is created just before the content for the first result is generated. the effect will be a toolbar with...
Sorting Results - Archive of obsolete content
ate builder orders the results in the order the items appear in the seq. for instance, the photos are listed in the same order in this example as they appear in the seq in the datasource. this method of sorting a seq works best for the simple query syntax since it is obvious how the starting ref relates to the end member results (they are just the children), or for extended syntax queries that follow a similar pattern. for more complex queries, this natural sorting will not work, because the sort service assumes that the starting ref resource is the container and the end results are the children. in this case, the natural order of the results will just be the order that the template builder generates the results. for ascending or descending sorts, this doesn't matter, since it will ignore whe...
...ast value is the default if the attribute is not specified. the sortactive attribute may be set to true or false and specifies which column the tree is sorted by. only one column should have the sortactive attribute set to true at a time. the tree will change both attributes as necessary automatically when the column headers are clicked or the tree is sorted by other means. if you don't want to allow sorting by a certain column, you can leave out the sort attribute. only specify this attribute on columns that you wish to allow the user to sort by. here is a complete example of sorting a tree. the sort attribute should be set to the variable that holds the values to sort by. usually, this would be the same variable that is used to generate the label for the cells in that column, however this i...
...by specifing different types for different values, you can sort alphabetically, numerically or by date. if you are using the simple rdf query syntax, there are no variables, so you need to specify the full predicate including the rdf: prefix in the sort attribute. for instance: <treecol id="name" label="name" sort="rdf:http://purl.org/dc/elements/1.1/title" flex="1"/> note t...
...i="?" label="?name"/> </action> </template> </listbox> it will often be the case that multiple items have the same value, especially for larger amounts of data. you can specify multiple sort keys to further define how a sort should be handled in the case where the values for the first sort key are the same. to do this, just add another key after the first separated by a space, as in the following: sort="?name ?gender" in this example, results will be sorted by name, followed by gender for those with identical names. you may add as many sort keys as desired. sorting occurs when output is first generated as well as when a result is added as a result of a datasource change. when the rdf datasource changes, and a new result is available, the new content is inserted at the right location. ...
XML Templates - Archive of obsolete content
he datasources attribute may be a relative url or an absolute url. note: if you want to have the state of the disclosure triangles ("twisties") be persistent, be sure to give each node a unique "id" attribute. these are used to track the current state of the disclosure triangles. support for this was introduced in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4). ...
...rl or an absolute url. note: if you want to have the state of the disclosure triangles ("twisties") be persistent, be sure to give each node a unique "id" attribute. these are used to track the current state of the disclosure triangles. support for this was introduced in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4). for this and the following examples, we are going to use the following xml document containing a list of people: <people> <person name="napoleon bonaparte" gender="male"/> <person name="cleopatra" gender="female"/> <person name="julius caesar" gender="male"/> <person name="ferdinand magellan" gender="male"/> <person name="laura secord" gender="female"/> </people> xml query syntax the query syntax is fairly simple for xml datasources. just place an ex...
...s are used, and we'll see examples of why this is useful later. for an rdf query, the uri attribute specifies the member variable; for an xml query the member variable is always '?' so the value of the uri attribute for xml templates should always be the single question mark character as in this example. the label attribute has been set to a special value ?name. when a question mark character followed by a string appears in an attribute value, the label value is not directly, but instead the value of an attribute for the source xml is used. for each node generated by the xpath expression used in the query, the attribute on the generated xml node is taken and substituted for the question mark and following string. in the above example, the use of the ?name value, causes the name attribute on...
...y expr="person"/> <action> <hbox uri="?" align="center"> <button label="?name"/> <label value="?gender"/> </hbox> </action> </template> </vbox> note how two attributes are substituted here, the label on the button and the value on the label. the query does not have to be as simple as the one used here. any xpath expression may be used. for instance, the following query returns only those results for female people. <query expr="person[@gender='female']"/> as long as the expression returns one or more nodes, it can be used in an query expression. using inline xml it's also possible to embed the xml data directly within the xul document if desired. instead of using a url for the datasources attribute, you can use an anchor reference to refer to a node w...
Tree Widget Changes - Archive of obsolete content
ethod has been removed, instead use nsitreeboxobject.invalidatecell() like this invalidatecell(row, tree.columns.getprimarycolumn()). this may be used to redraw a cell after it or its data has been changed. the nsitreeview.cycleheader() method has been changed, cycleheader(colid, element) is now just cycleheader(column), since the code can get the element from the column object. ...
...normal -> nsitreeview.progress_normal (1) nsitreeview.progressundetermined -> nsitreeview.progress_undetermined (2) nsitreeview.progressnode -> nsitreeview.progress_none (3) as well, the drag and drop methods candropon and candropbeforeafter have been replaced with a single method candrop(idx,orientation) which handles both. 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 implemented. now it is. you can create a checkbox column by setting the type attribute of a column to checkbox. <treecol type="checkbox"> you can then set or clear the checkbox for a particular cell in that column by setting the value attribute to true, or leaving out the attri...
...lvalue method will be called with either the value true or false. note that the tree must also be marked as editable using the editable attribute in order for this to work. this is shown in the example above. sometimes, you might have a particular row or cell which you do not want to be editable. in this case, disable editing for that cell by setting editable to false for that cell, as in the following: <treecell value="true" editable="false"/> or, for custom views, return false from the iseditable method. currently, only checkbox columns support editing, although the content-based tree handles the nsitreeview.setcellvalue() and nsitreeview.setcelltext() functions to change the tree content with a script for other types of cells. for instance: var col = tree.columns.getprimarycolumn(); ...
...mns.getprimarycolumn(); treecell.setcelltext(5, col, "banana"); this will change the label of the cell in row 5 and the primary column to banana. however, this paves the way in the future for more general tree editing features. style improvements you can now specify the cursor to use for a cell using the css cursor property. treechildren::-moz-tree-cell-text { cursor: pointer; } this allows you to create separate cursors for cells. the :-moz-tree-separator pseudo has been improved to make it a proper box type and now has additional styling capabilities. example: treechildren::-moz-tree-separator { margin-top: 1px; border-top: 1px solid threedshadow; border-left: 1px solid threedshadow; border-right: 1px solid threedhighlight; border-bottom: 1px solid ...
Adding Labels and Images - Archive of obsolete content
nclude elements into groups. text elements you cannot embed text directly into a xul file without tags around it and expect it to be displayed. you can use two xul elements for this purpose. label element the most basic way to include text in a window is to use the label element. it should be used when you want to place a descriptive label beside a control, such as a button. ...
...later, we'll find out how to constrain the width of elements so that we can see the wrapping more easily. ...
...ingle line of text or place text or xhtml content inside opening and closing description tags for longer blocks of text. it is more common to use the attribute syntax for labels, and the text content syntax for descriptions. example 4 : source view <description> this longer section of text is displayed. </description> you can set the text via script using the textcontent property, as in the following example: <description id="text" width="200"/> document.getelementbyid('text').textcontent = "some lengthy word wrapped text goes here."; internally, both the label element and the description elements are the same. the label element is intended for labels of controls, such as text fields. the control attribute is only supported for labels. the description element is intended for other descri...
... only supported for labels. the description element is intended for other descriptive text such as informative text at the top of a dialog box. images xul has an element to display images within a window. this element is appropriately named image. note that the tag name is different than html (image instead of img). you can use the src attribute to specify the url of the image file. the example below shows this: <image src="images/banner.jpg"/> although you can use this syntax, it would be better in order to support different themes to use a style sheet to set the image url. a later section will describe how to use style sheets, but an example will be shown here for completeness. you can use the list-style-image css property to set the url for the image. here are some examples: xul: <image ...
Adding Style Sheets - Archive of obsolete content
have the progress bar 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 ski...
... 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 the interface skin, the files in a directory other than default will be applied. importing style sheets we've already seen how to import style sheets for use. an example is shown below: <?xml-stylesheet href="chrome://bookmarks/skin/" type="text/css"?> this might be the first lines of a bookmarks window. it imports the bookmarks style sheet, which is bookmarks.css. mozilla's skin system is smart enough to figure out which style sheet to use, because the specific filename was not indicated here. we have done a similar thing with the global style sheet file (chrome://global/skin...
...filename was not indicated here. we have done a similar thing with the global style sheet file (chrome://global/skin). a style sheet may import styles from another stylesheet using the import directive. normally, you will only import one style sheet from each xul file. the global style sheet can be imported from within the style sheet associated with the xul file. this can be done with the code below, allowing you to remove the import from the xul file: style import from xul: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> style import from css: @import url(chrome://global/skin/); the second syntax is preferred because it reduces the number of dependencies within the xul file itself. remove the global style sheet import from findfile.xul and add the import to findfile.cs...
...obal/skin/); the second syntax is preferred because it reduces the number of dependencies within the xul file itself. remove the global style sheet import from findfile.xul and add the import to findfile.css. all elements can be styled using css. you can use selectors to select the element that you wish to have styled. (the selector is the part before the curly brace in a style rule). the following list summarizes some of the selectors available: button matches all button tags. #special-button matches the element with an id of special-button. .bigbuttons matches all elements with a class of bigbuttons. button.bigbuttons matches all button elements with a class of bigbuttons. toolbar > button matches all buttons t...
Custom Tree Views - Archive of obsolete content
« previousnext » the tree view holds the data to be displayed in the tree. creating a custom view so far, we have only been using the built-in content tree view. in this section, we will look at creating a custom view. this is necessary when the page has a lot of data or that data is highly nested. for instance, 5000 rows of treeitems would load too slowly. you might also implement a custom view when you want to perform computations on the data to be displayed. since the view can store and retrieve the data in the most suitable manner for the kind of data used, the tree can be used even when there are hundreds of thousands of rows to be displayed. note: the tree-related interfaces changed in gecko 1.8. see tree widget changes for details. to implement a custom view, you ...
...e nsitreeview interface. you can create these objects in javascript, but you will need a separate object for each tree. naturally, since a custom tree view is being used, the content tree view will not be used, so the treeitem, treerow, and treecell elements will have no purpose since the custom view will get its data from elsewhere. thus, you can just leave the treechildren element empty. the following example shows this: <tree id="my-tree" flex="1"> <treecols> <treecol id="namecol" label="name" flex="1"/> <treecol id="datecol" label="date" flex="1"/> </treecols> <treechildren/> </tree> to assign data to be displayed in the tree, the view object needs to be created which is used to indicate the value of each cell, the total number of rows plus other optional information. the...
...d which is used to indicate the value of each cell, the total number of rows plus other optional information. the tree will call methods of the view to get the information that it needs to display. in general, although the tree view has thirty or so functions that may be implemented, you only need to implement the ones that the tree will call. three methods that you should implement are listed below. rowcount this property should be set to the total number of rows in the tree. getcelltext( row , column ) this method should return the text contents at the specified row and column. this will be called to display data for each cell. the rows are supplied as numeric values starting at 0. the columns are treecolumn objects. in the older versions of mozilla (before firefox 1.5 or mozilla ...
... very simple of course -- in reality you would have more complex data in each cell. the final step is to associate the view object with the tree. the tree has a property view, which can be assigned to the view object declared above. we can assign a value to this property at any time to set or change the view. function setview(){ document.getelementbyid('my-tree').view = treeview; } the following presents the example together. an inline script has been used here to simplify the example. normally, you would put the script in an external script file. example custom tree source <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window title="tree example" id="tree-window" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" ...
Manipulating Lists - Archive of obsolete content
', and a value 'thu'. the two arguments correspond to the label attribute and the value attribute on the listitem element. the value is used only as an extra optional value associated with an item which you might wish to use in a script. similarly, there is also an insertitemat() and a removeitemat() function which inserts a new item and removes an existing item respectively. the syntax is as follows: list.insertitemat(3, "thursday", "thu"); list.removeitemat(3); the insertitemat() function takes an additional argument, the position to insert the new item. the new item is inserted at this index, so, in the example, the new item will be added at position 3 while the item previously at that position will now be at position 4. remember that the first item is 0. the removeitemat() function wi...
...ex and selecteditem. the former returns the index of the selected item while the latter returns the selected element. for instance the selecteditem of a menulist will be the menuitem that is selected. if no item is selected, selectedindex will return -1, while selecteditem will return null. getting the selected item these two properties are commonly inspected during a select event, as in the following example: example 2 : source view <listbox id="thelist" onselect="alert(this.selecteditem.label);"> <listitem label="short"/> <listitem label="medium"/> <listitem label="tall"/> </listbox> the select event is fired for a listbox when an item in the list is selected. the select handler here displays an alert containing the label of the selected item in the list. since the select event ...
...ll use these properties to iterate over the list and perform some operation for each item. be careful when iterating over the selected items; if you modify the items in the list while iterating, the list will change and the selection properties may return different values. this is one reason why it is useful to manipulate the list by the item rather than by index. ...
...olelement interface also provides methods for modifying the selected items. for instance, the additemtoselection() function adds a new item to the set of selected items, without clearing the existing selection. the removeitemfromselection() function removes a single item from the selection. list scrolling if there are more rows in the listbox than can be displayed, a scroll bar will appear to allow the user to scroll the list. the scroll position may be adjusted using a couple of listbox methods. the scrolltoindex() method scrolls to a given row. this listbox will scroll such that the row will be the top row visible, unless the row is near the end of the list of items. the ensureindexisvisible() method is similar in that it also scrolls to show a row, but this method does not scroll if the...
Modifying a XUL Interface - Archive of obsolete content
usnext » the dom provides various functions to modify the document. creating new elements you can create new elements using the createelement() function of the document. it takes one argument, the tag name of the element to create. you can then set attributes of the element using the setattribute() function and append it to the xul document using the appendchild() function. ...
...ml element will be created, so it will have the features and functions of an html element instead. the createelementns() function may be used to create elements in a different namespace. the appendchild() function is used to add an element as a child of another element. three related functions are the insertbefore(), replacechild() and removechild functions. the syntax of these functions is as follows: parent.appendchild(child); parent.insertbefore(child, referencechild); parent.replacechild(newchild, oldchild); parent.removechild(child); it should be fairly straightforward from the function names what these functions do. the insertbefore() function inserts a new child node before an existing one. this is used to insert into the middle of a list of children of the parent element instead o...
...e adds a '1' to the textbox each time the button is pressed. the nextsibling property navigates from the button (this) to the next element, the textbox. the += operator is used to add to the current value so a 1 will be added onto 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 s...
...selectedindex property may be used to do this. the selectedindex property may be used to retrieve the index of the selected radio button in the group and well as change it. changing a element disabled or enabled it is common to disable particular fields that don't apply in a given situation. for example, in a preferences dialog, one might have the choice of several possibilities, but one choice allows additional customization. here is an example of how to create this type of interface. example 7 : source view <script> function updatestate(){ var name = document.getelementbyid("name"); var sindex = document.getelementbyid("group").selectedindex; name.disabled = sindex == 0; } </script> <radiogroup id="group" onselect="updatestate();"> <radio label="random name" selected="true"/> <hb...
More Tree Features - Archive of obsolete content
chical trees the tree element is also used to create hierarchical lists, like that found in a file manager or a browser'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 ke...
...es. essentially, a treeitem element can contain either single rows which are declared with the treerow element or a set of rows which are declared with the treechildren element. there are two other things you need to do to make sure the hierarchy works properly. first, you need to mark the treeitem element that has children as a container. you do this by adding the container attribute to it as follows: <treeitem container="true" /> this allows the user to click on the row that corresponds to the treeitem to expand and collapse the inner rows. you can have the child rows initially displayed by adding the open attribute. when the user expands and collapses the parent, the view's toggleopenstate function will be called to toggle the item between open and closed. for a content tree view, this wi...
...current state. the second change is that you must put the primary attribute on the first column. this causes a small triangle or plus sign to appear before the cells in that column to indicate the cells that can be expanded. in addition, child rows are indented. note also that the user cannot hide the primary column using the drop down to the right of the columns. ...
... 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-between sessions. (that feature will see in the later section). thus, once the user has decided on a column layout they like, it will automatically be saved for next time. ...
Tabboxes - Archive of obsolete content
tabboxes are typically used in an application in the preferences window. a series of tabs appears across the top of a window. the user can click each tab to see a different set of options. it is useful in cases when you have more options than will fit in one screen. xul provides a method to create such dialogs. it involves five new elements, which are described briefly here and in more detail below. tabbox the outer box that contains the tabs along the top and the tab pages themselves. tabs the inner box that contains the individual tabs. in other words, this is the row of tabs. tab a specific tab. clicking on the tab brings the tab page to the front. tabpanels the container for the pages. tabpanel the body of a single page. you would place the content for a page within this ele...
...for the pages. tabpanel the body of a single page. you would place the content for a page within this element. the first tabpanel corresponds to the first tab, the second tabpanel corresponds to the second tab and so on. the tabbox is the outer element. it consists of two children, a tabs element which contains the row of tabs and a tabpanels elements which contains the tabbed pages. shown below is the general syntax of a tabbox: <tabbox id="tablist"> <tabs> <!-- tab elements go here --> </tabs> <tabpanels> <!-- tabpanel elements go here --> </tabpanels> </tabbox> the tab elements are placed inside a tabs element, which is much like a regular box. the tabs element itself has been placed inside a tabbox. the tabbox also contains a tabpanels element which will appear bel...
...> <tabpanels> <tabpanel id="mailtab"> <checkbox label="automatically check for mail"/> </tabpanel> <tabpanel id="newstab"> <button label="clear news buffer"/> </tabpanel> </tabpanels> </tabbox> here, two tabs have been added, the first labeled 'mail' and the other 'news'. when the user clicks on the mail tab, the contents of the first tab page will be displayed below the tabs. in this case, the page with the check box labeled 'automatically check for mail' will appear. when the second tab is clicked, the page containing the button labeled 'clear news buffer' will appear instead. the currently selected tab element is given an additional selected attribute which is set to true. this alters the appearance of the currently selected tab to make it look selected. ...
...ia box will need to go on the first tab. we'll add some options on the second tab. the progress bar and the buttons can stay on the main dialog, outside of the tabs. <vbox flex="1"> <tabbox selectedindex="1"> <tabs> <tab label="search"/> <tab label="options"/> </tabs> <tabpanels> <tabpanel id="searchpanel" orient="vertical"> <description> enter your search criteria below and select the find button to begin the search. </description> <spacer style="height: 10px"/> <groupbox orient="horizontal"> <caption label="search criteria"/> <menulist id="searchtype"> <menupopup> <menuitem label="name"/> <menuitem label="size"/> <menuitem label="date modified"/> </menupopup> </menulist> <...
XBL Attribute Inheritance - Archive of obsolete content
however, with the features mentioned so far, the anonymous content is always created in the same way. it would be useful to add attributes to the bound elements that modify the inner elements. for example: xul: <searchbox/> xbl: <binding id="searchbinding"> <content> <xul:textbox/> <xul:button label="search"/> </content> </binding> in the example, the label attribute has been placed directly on the button element. ...
...t should inherit an attribute from the outer element, in this case the button. its value should be set to a comma-separated list of attribute names that are to be inherited. <xul:textbox xbl:inherits="flex"/> <xul:button xbl:inherits="label"/> when the content is generated, the textbox grabs the flex attribute from the searchbox and the button grabs the label attribute from the searchbox. this allows both the flexibility of the textbox and the label of the button to be different for each use of the binding. in addition, changing the value of the attributes on the searchbox with a script will update the textbox and button also. you can add the inherits attribute to as many elements as you wish, to inherit any number of attributes. note how the inherits attribute has been placed in the xbl nam...
...that has the same name. for example, to create a labeled textbox (a textbox with a text description beside it) out of a label and a textbox element, the label will need to inherit its text from the value attribute and the textbox will also need to inherit its default value from the value attribute as well. to solve this, we will need to use a different attribute and map it to the same one. ...
...g id="okcancel"> <content> <xul:button xbl:inherits="label=oktitle,image"/> <xul:button xbl:inherits="label=canceltitle"/> </content> </binding> the value of the oktitle attribute is mapped to the label attribute of the first button. the canceltitle attribute is mapped to the label attribute of the second button. the first button also inherits the image attribute. the result is as follows: <box class="okcancel" oktitle="ok" canceltitle="cancel" image="happy.png"> <button label="ok" image="happy.png"/> <button label="cancel"/> </box> note that the attributes are duplicated on the inner (anonymous) content. changing the attributes on the box with the okcancel class will automatically change the values on the buttons. you may also have noticed that we just made up our own attri...
XBL Example - Archive of obsolete content
you could put anything within the pages, however, this widget might be useful for a set of images. ...
...way. the label attributes on the two buttons inherit their values from the bound element. here, they inherit from two custom attributes, previoustext and nexttext. this makes it easy to change the labels on the buttons. the children of the element that the xbl is bound to will be placed inside the deck. the selectedindex is inherited by the deck, so we may set the initial page in the xul. the following xul file produces the result in the image. <box class="slideshow" previoustext="previous" nexttext="next" flex="1"> <button label="button 1"/> <checkbox label="checkbox 2"/> <textbox/> </box> the style sheet used here is: .slideshow { -moz-binding: url("slideshow.xml#slideshow"); } the first button, button 1 has been used as the first page of the deck. the label widget has not ...
...totalpages); </constructor> additional features we can add some additional features as well. some keyboard shortcuts could be used for the previous and next buttons, (say backspace and the enter key). first and last buttons could be added to go to the first and last pages. ...
...uttons, (say backspace and the enter key). first and last buttons could be added to go to the first and last pages. the label element could be changed to a field where the user could enter the page to go to, or a popup could be added to allow selection of the page from a menu. we could also add a border around the deck with css to make it look a bit nicer. ...
Using Remote XUL - Archive of obsolete content
introduction note: support for remote xul has long been a potential security concern; support for it was disabled in gecko 2.0. this also means you can't load xul using file:// urls unless you set the preference dom.allow_xul_xbl_for_file to true. however, there is a whitelist that lets you specify sites that can still use remote xul. ...
...ern; support for it was disabled in gecko 2.0. this also means you can't load xul using file:// urls unless you set the preference dom.allow_xul_xbl_for_file to true. however, there is a whitelist that lets you specify sites that can still use remote xul. the remote xul manager extension lets you manage this whitelist, which is maintained using nsipermissionmanager, by creating entries of type "allowxulxbl", like this: components.classes["@mozilla.org/permissionmanager;1"] .getservice(components.interfaces.nsipermissionmanager) .add(uri, 'allowxulxbl', components.interfaces.nsipermissionmanager.allow_action); xul (pronounced like "zool"), which is short for xml-based user interface language, is an xml-based language for describing application interfaces. it contains elements for all c...
...te). it is difficult to discern the site's basic structure and available resources, which makes it hard to locate a particular page or find the one with the information you want. part of the problem is that html has limited features for navigation. its primary mechanism--the hyperlink--was designed to be interspersed in content. html-based navigation bars take up too much space, dhtml menus are slow and buggy, and site maps make you go to an intermediate page to find the information you want. xul's navigation-oriented widgets, like toolbars, menus, and trees, are a better way to provide web site navigation because they can fit a lot of navigation into a small space, render quickly, and work well. note: the downside to using xul is that it only works with browsers that understand it. this i...
...e dom. knowledge of xml and its syntax is useful but not required. you also need a text editor and a web browser that can render xul, like mozilla, or firefox. if you build a xul file along with this tutorial and put it onto a web server, you need to configure your web server to specify the content type of xul files as application/vnd.mozilla.xul+xml. for apache, you can do this by adding the following line to your mime.types file: application/vnd.mozilla.xul+xml .xul alternately, add this line to your httpd.conf file or, if the apache server is configured to allow it, to the .htaccess file in the directory from which the xul file is served: addtype application/vnd.mozilla.xul+xml .xul then restart your web server. with php you can send the mime-type with the header() function. <?php ...
XUL accessibility tool - Archive of obsolete content
t an application is free of accessibility bugs or issues), many of the most common accessibility mistakes will be found and reported. availability the xul accessibility tool can currently be obtained from [http://www.xulplanet.com/aaron/files...bilitytool.xpi]. future versions of the extension will be available from addons.mozilla.org. the version currently on xulplanet is compatible with the following xul applications: firefox 1.5+ thunderbird 3.0a+ recent sunbird builds recent songbird builds. it probably also works on seamonkey, but i haven't verified this. use to launch the tool after installation, look for an entry in the tools menu of the host application, or hit ctrl+alt+shift+f12. once the tool window has loaded, select either a local file, web url, or currently open window fr...
...e tools menu of the host application, or hit ctrl+alt+shift+f12. once the tool window has loaded, select either a local file, web url, or currently open window from the file menu to generate a xul report for that document. be aware that the report might take a little while to be ready depending on the complexity of the application being analyzed and the speed of your machine. ...
... the application being analyzed and the speed of your machine. future work the following things have been suggested or are planned for a future version of the tool: new tests: (aaronlev) warning: hardcoded color and pixel sizings (aaronlev) error: duplicate accesskey in a dialog (already have this for menus) (aaronlev) error: form control without accesskey (aaronlev) warning: accesskey as lowercase letter with descender (underlined g,j,y,q,p are hard to read, not recommended) (aaronandy) list of things to check manually, such as a list oftrees in the document (make sure they have accessible column picker equivs) or a list of toolbarbuttons (make sure they have accessible alternatives). new features: (aaronlev) automatically test any new windows as they are opened. (aaronandy) hi...
...online tool to automatically generate a xul a11y tool compatible with a user-specified xul app. (aaronandy) link report sections to relevant part of xul a11y guidelines. (aaronandy) enable tabs, context menu, and other browser extras in report window. (aaronandy) xul runner version that can run from the command line, check a text file, and output the results somewhere. known bugs: test for lowercase i or l as accesskey (sometimes?) flags upppercase i and l too. possible false positives in some of the other tests processing is slower than we would like. ideas for further work on xul a11y some general ideas for using the tool and guidelines to further the accessibility cause within the mozilla project. add usability, i18n, security and other considerations to xul a11y guidelines ...
action - Archive of obsolete content
s | properties | methods | related ] used to specify the content that should be generated for each matching 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. ...
...iables 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. ...
...ce 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. ...
...ht, 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, 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 addeventliste...
arrowscrollbox - Archive of obsolete content
is available in the xul tutorial. ...
...lex="1"> <button label="red"/> <button label="blue"/> <button label="green"/> <button label="yellow"/> <button label="orange"/> <button label="silver"/> <button label="lavender"/> <button label="gold"/> <button label="turquoise"/> <button label="peach"/> <button label="maroon"/> <button label="black"/> </arrowscrollbox> 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, sortd...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. sm...
...ng for the corresponding arrowscrollbox, false disables it. currently, smooth scrolling supports horizontal arrowscrollboxes only. 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. ...
description - Archive of obsolete content
an ellipsis will be used in place of the cropped text. if the box direction is reversed, the cropping is reversed. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (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; } disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is disabled. disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, a...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. tabinde...
... which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. 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 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 merely associate data with an element, you could 1) use another attribute like "value2" or "data-myatt" (as in the html5 draft), as xul does not require ...
keyset - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a container element for key elements. the keyset and its descendants are not displayed. more information is available in the xul tutorial. ...
...ul reference home [ examples | attributes | properties | methods | related ] a container element for key elements. the keyset and its descendants are not displayed. more information is available in the xul tutorial. ...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. properties ...
...th an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. ...
label - Archive of obsolete content
Archive › Mozilla › XUL › label
er 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. control type: id this attribute specifies the id of the element with which the label is associated. when the user clicks on the label, the associated element is given focus. 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. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (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; } disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is disabled. disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, a...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. href t...
...these classes should be used instead of changing the style of the element directly since they will fit more naturally with the user's selected theme. header a class used for headings. typically, this will cause the text to appear bold. indent this class causes the text to be indented on its left side. monospace this class causes the text t...
listcell - Archive of obsolete content
eference home [ examples | attributes | properties | methods | related ] a single cell of a listbox. by default it only contains text but iconic and checkbox listcells are also available. attributes crop, disabled, image, label, type properties disabled style classes listcell-iconic, examples (example needed) 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. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (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; } disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is disabled. disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, a...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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 ...
...or 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. properties disabled type: boolean gets and sets the value of the disabled attribute. ...
listhead - Archive of obsolete content
disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. inherited...
...sing it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. ...
...an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. ...
...ortdirection, 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. disabled type: boolean gets and sets the value of the disabled attribute. ...
listheader - Archive of obsolete content
disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. label ...
... and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. 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. ...
...s, is normally preferred to use of the attribute, as it may need to update additional state. 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. ...
...inal, 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. ...
menupopup - Archive of obsolete content
he keyboard. more information is available in the xul tutorial and popup guide. ...
...when the label is right-clicked, the menu will be displayed. ...
... 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 the anchor and popup should be aligned. if specified as 2 words, the value indicates which corn...
...pens a popup element. there are two ways of specifying where the popup appears, either at a specific screen position, or relative to some element in the window. if either x or y are set to values, the popup will appear at the screen coordinate (x,y). if x and y are -1, the popup will be positioned relative to the element specified as the first argument. this is what you might do to show a popup below a button, for example. in this latter case, the anchor and align arguments may be 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 ...
preferences - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] overview <preferences> is a container for <preference> elements. it's supposed to be a child of <prefpane> element. <preferences> element should contain one or more <preference> elements. note: it's not clear which of the following methods and properties are public. examples <preferences> <preference id="pref_one" name="extensions.myextension.one" type="bool"/> <preference id="pref_two" name="extensions.myextension.two" type="string"/> ... etc ... </preferences> attributes these ought to be readonly; three of these could be merged into a single member attribute nsiprefservice service; the preferences service. attribute nsiprefbranch rootbranch; the root prefs branch. at...
... three of these could be merged into a single member attribute nsiprefservice service; the preferences service. attribute nsiprefbranch rootbranch; the root prefs branch. attribute nsiprefbranch defaultbranch; the root branch of the tree with default values. attribute nsiprefbranch2 rootbranchinternal; the root prefs branch (nsiprefbranch2). ...
...se could be merged into a single member attribute nsiprefservice service; the preferences service. attribute nsiprefbranch rootbranch; the root prefs branch. attribute nsiprefbranch defaultbranch; the root branch of the tree with default values. attribute nsiprefbranch2 rootbranchinternal; the root prefs branch (nsiprefbranch2). ...
...t, 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, 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 void firechangedevent(in domelem...
progressmeter - Archive of obsolete content
onmouseout="setloading(false)"/> function setloading(state){ document.getelementbyid('myprogress').mode = (state) ? 'undetermined' : 'determined'; } attributes max type: integer the maximum value that progressmeter may have. the default value if not specified is 100 such that the value may be used as a percentage. 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. value type: in...
...e bar that is filled in. undetermined the progressmeter is indeterminate. value type: integer an integer ranging from 0 to the maximum value that indicates the progress. for instance, if no maximum value has been set, setting the value to "0" shows an empty bar, "100" shows a bar at full length and "25" shows the first quarter of the bar. ...
... filled in. undetermined the progressmeter is indeterminate. value type: integer an integer ranging from 0 to the maximum value that indicates the progress. for instance, if no maximum value has been set, setting the value to "0" shows an empty bar, "100" shows a bar at full length and "25" shows the first quarter of the bar. ...
... gets and sets the value of the max attribute. mode type: string gets and sets the value of the mode attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. ...
richlistbox - Archive of obsolete content
disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. disable...
...s is done incrementally, so typing more letters with select more specific items. this feature may be disabled by setting this attribute to true. preference type: id connects the element to a corresponding preference. this attribute only has any effect when used inside a prefwindow. more information is available in the preferences system article. ...
...elect more specific items. this feature may be disabled by setting this attribute to true. preference type: id connects the element to a corresponding preference. this attribute only has any effect when used inside a prefwindow. more information is available in the preferences system article. seltype type: one of the values below used to indicate whether multiple selection is allowed. single only one row may be selected at a time. (default in listbox and richlistbox.) multiple multiple rows may be selected at once. (default in tree.) for trees, you can also use the following values: cell individual cells can be selected text rows are selected; however, the selection highlight appears only over the text of the primary column. for richlistbo...
...r an item is selected, either by the user or by calling one of the select methods. if set to true, the select event is never fired. 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 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 merely associate data with an element, you could 1) use another attribute like "value2" or "data-myatt" (as in the html5 draft), as xul does not require ...
rows - Archive of obsolete content
Archive › Mozilla › XUL › rows
les | attributes | properties | methods | related ] defines the rows of a grid. child row elements define the individual rows to appear in the grid. each child of a rows element should be a row element. the rows element may be nested inside another rows element. the children of these nested rows are counted as normal rows as if they were part of the parent. however, nesting rows elements allows groups of rows to have a separate appearance such as a different border, or separate scrolling may be defined for these rows. non-row related elements placed inside a rows element occupy the full width of the grid and are placed in their corresponding positions between the rows. more information is available in the xul tutorial. example see grid for an example. attributes inherited from...
...e a separate appearance such as a different border, or separate scrolling may be defined for these rows. non-row related elements placed inside a rows element occupy the full width of the grid and are placed in their corresponding positions between the rows. more information is available in the xul tutorial. example see grid for an example. ...
...appearance such as a different border, or separate scrolling may be defined for these rows. non-row related elements placed inside a rows element occupy the full width of the grid and are placed in their corresponding positions between the rows. more information is available in the xul tutorial. example see grid for an example. ...
...t, 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, 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 addeventlist...
tab - Archive of obsolete content
Archive › Mozilla › XUL › tab
e of the area around the selected tab. beforeselected type: boolean this is set to true if the tab is immediately before the currently selected tab. this is set automatically set when needed and you shouldn't adjust it manually. this is primarily useful for themes so that they can adjust the appearance of the area around the selected tab. 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. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (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; } disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is disabled. disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, a...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. fadein t...
...user presses the "tab" key. elements with a higher tabindex are later in the tab sequence. unread type: boolean this attribute is set to true if the tab is unread; that is, either it has not yet been selected during the current session, or has changed since the last time it was selected. this attribute is not present if the tab is not unread. validate type: one of the values below this attribute indicates whether to load the image from the cache or not. this would be useful if the images are stored remotely or you plan on swapping the image frequently. the following values are accepted, or leave out the attribute entirely for default handling: always the image is always checked to see whether it should be reloaded. never the image will be loaded from the cache...
tooltip - Archive of obsolete content
an ellipsis will be used in place of the cropped text. if the box direction is reversed, the cropping is reversed. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (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; } default type: boolean if true, the tooltip is used as the default popup for displaying tooltips in the window. 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 a...
...y 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 the anchor and popup should be aligned. if specified as 2 words, the value indicates which corn...
...pens a popup element. there are two ways of specifying where the popup appears, either at a specific screen position, or relative to some element in the window. if either x or y are set to values, the popup will appear at the screen coordinate (x,y). if x and y are -1, the popup will be positioned relative to the element specified as the first argument. this is what you might do to show a popup below a button, for example. in this latter case, the anchor and align arguments may be 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 ...
treecell - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a single cell in a tree. this element should be placed inside a treerow. you can set the text for the cell using the label attribute. more information is available in the xul tutorial. attributes editable, label, mode, properties, ref, src, value attributes editable type: boolean allows the contents of individual cells in the column to be changed, especially useful when <treecol type="checkbox">. also useful for disabling editing of individual treecells. when the user double-clicks an editable cell, a text field appears in which the user can edit the contents of the cell. the tree and treecol must also be marked as editable in order for this to work. the tree must be a cont...
...e marked as editable in order for this to work. the tree 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 th...
...e content generation begins. this will correspond to the value of an about attribute on an rdf container. this attribute should be placed alongside the datasources attribute. src type: uri set this to the uri of an image to appear in the tree cell. if this attribute is left out, no image appears. you can have both an image and a label. 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 merely associate data with an element, you could 1) use another attribute like "value2" or "data-myatt" (as in the html5 draft), as xul does not require ...
...oof); 3) use setuserdata() (future-proof and clean, but not easily serializable). for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax. for those elements, setattribute("value", myvalue) and getattribute("value") do not access or affect the contents displayed to the user. ...
where - Archive of obsolete content
Archive › Mozilla › XUL › where
boolean set to true to indicate that the value contains multiple values separated by commas. any of the values may match. otherwise, the entire value string is compared. negate type: boolean set to true to indicate that the comparison should be reversed. the where clause matches if the condition is false, and does not match if the condition is true. rel type: one of the values below the type of comparison to perform. equals the subject and value must match exactly. less the numeric value of the subject must be less than the value greater the numeric value of the subject must be greater than the value before the string value of subject must come before value alphabetically after the string value of subject must come after value alphabetically starts...
...f subject must come after value alphabetically startswith the value of subject must start with the value endswith the value of subject must end with the value contains the value of subject must contain the value as a substring subject type: string the variable or string to compare. value type: string the value to compare. ...
...t come after value alphabetically startswith the value of subject must start with the value endswith the value of subject must end with the value contains the value of subject must contain the value as a substring subject type: string the variable or string to compare. value type: string the value to compare. ...
...t, 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, 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 addeventlist...
Application Update - Archive of obsolete content
you will need to compile a unix/linux executable mar from mozilla/modules/libmar. ...
...ile a unix/linux executable mar from mozilla/modules/libmar. as far as i can tell enabling the options --enable-updater and --enable-update-packaging on your configure will build you mar. compiled versions of mar are available in the gecko sdk under the folder /host/bin for your os. in order to generate sha1 hashes i installed shash. ...
...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 p...
...howinstalledui", false); // 0 = suppress prompting for incompatibilities if there are updates available // to newer versions of installed addons that resolve them. // 1 = suppress prompting for incompatibilities only if there are versioninfo // updates available to installed addons that resolve them, not newer // versions. pref("app.update.incompatible.mode", 0); update server follow the instructions here to setup an update server for your xulrunner application to query. i opted for the simpler approach of not using the update php script. https is recommended but not required (yet). update.xml the format is outlined here process as best i can tell here's how the update process works. at the scheduled interval the application checks the update server for update.xml, se...
Creating a Windows Inno Setup installer for XULRunner applications - Archive of obsolete content
the stable release. if you want to edit scripts, you should get the quickstart pack (which includes istool, the script editor. however, if you don't get the quickstart pack, you can later get istool from inno setup third-party files. step 2: creating the application to make your application standalone, deploy your application according to the deploying xulrunner 1.8 article. my app's example follows. myapp/ application.ini chrome/ default/ myapp.exe (copy xulrunner-stub.exe and rename) xulrunner/ please test your application before deploying it. if your application does not run, neither will the installed version. step 3: creating the inno setup script create an inno setup script (.iss file). the inno setup script wizard can't set chrome directory's deployment...
...installed version. step 3: creating the inno setup script create an inno setup script (.iss file). the inno setup script wizard can't set chrome directory's deployment point, so you have to edit the iss file yourself. also you had better set the appname and apppublisher properties to the same values specified in your xulrunner application's application.ini file. my app's .iss file sample as follows: ; script generated by the inno setup script wizard. ; see the documentation for details on creating inno setup script files! [setup] appname=my app appvername=my app 1.0 apppublisher=mark finkle apppublisherurl=http://developer.mozilla.org/en/docs/getting_started_with_xulrunner appsupporturl=http://developer.mozilla.org/en/docs/getting_started_with_xulrunner appupdatesurl=http://developer.moz...
...ng inno setup script files! ...
...this will create the compiler, which you need to test by actually trying to install your xulrunner application. don't forget to then test the installed application to be sure the installation did indeed work correctly...
Deploying XULRunner - Archive of obsolete content
ook at the branding section of xulrunner tips. windows on windows, xulrunner does not yet have a complete built-in installation solution; app developers should use pre-existing solutions for a native windows installer. an example of one such solution may be found in the article: creating a windows inno setup installer for xulrunner applications. the installed files should be arranged in the following directory structure: installdir/ application.ini components/ ... components which are part of the application chrome/ ... chrome which is part of the application ... additional application files such as icons, etc myapplicationname.exe (this is the "stub executable"... you should copy and rename this file from xulrunner-stub.exe in yo...
... ... chrome which is part of the application ... additional application files such as icons, etc myapplicationname.exe (this is the "stub executable"... you should copy and rename this file from xulrunner-stub.exe in your xulrunner installation.) xulrunner/ ... copy xulrunner/ to this directory when deploying with xulrunner 2.0 and above do the following: move chrome.manifest to the root directory, and adjust resource paths inside chrome.manifest accordingly with xulrunner 9.0 or 10.0 you may need to copy "mozutils.dll" and/or "mozcrt19.dll" from the xulrunner directory to the root directory. this should be fixed with xulrunner 11.0 with xulrunner 11.0 you may need to copy "gkmedias.dll" from the xulrunner directory to the ro...
...updated to know about the change, so it will report an error: "unable to load xpcom." xulrunner was fixed in gecko 39. see this blog post for additional background about this change. xulrunner 38 and earlier in xulrunner 38 and earlier, xulrunner is provided in a mac os x framework bundle, which is placed in your application bundle's frameworks directory. the complete bundle structure is as follows: myapp.app/ contents/ info.plist pkginfo frameworks/ xul.framework/ files copied from /library/frameworks/xul.framework/versions/1.8/... make sure you copy all symlinks correctly (use rsync -rl /library/frameworks/xul.framework ...). resources/ application.ini app_icon.icns ...
...ou can use any paint or graphics utility to create your application's icon, which should be provided as a 512 by 512 pixel png file. to make it all work, change the permissions of your bundle by running chmod -r 755 yourapp.app. linux most linux applications are distributed as simple .tar.bz2 archives which can be unpacked by the user wherever they wish. the archive should be structured as follows: appname/ application.ini components/ ... components which are part of the application chrome/ ... chrome which is part of the application ... additional application files such as icons, etc myapplicationname (this is the "stub executable"... you should copy and rename this file from xulrunner-stub in your xulrunner installation.) xu...
What XULRunner Provides - Archive of obsolete content
the goal of xulrunner is to provide a solution for deploying xul applications (primarily firefox and thunderbird), as well as providing an embedding mechanism. ...
...see the wikimo:xul:installation story. extension manager file picker (uses native os filepicker as appropriate) find toolbar helper app dialog/ui security ui (maintenance of ssl keychains, etc...
...plied by xulrunner, and may be overridden by embedders under certain circumstances: apis and user interface for installing, uninstalling, and upgrading xul applications. see the wikimo:xul:installation story. ...
... helper app dialog/ui security ui (maintenance of ssl keychains, etc) embedding apis the following embedding apis are provided by xulrunner: cross-platform embedding (xre_initembedding) javaxpcom embedding gtkmozembed (linux only) activex control (windows only) (not yet complete) obsolete since gecko 7.0 nsview-based-widget (mac os x only) (not yet complete) the "maybe" list the following features have been discussed and may be included if developer time permits and code size is controlled: ldap support spellchecking support (with or without dictionaries provided) see bug 285977 core support for profile roaming (with application-specific extensibility) pyxpcom embedding (not yet complete) - but it does work, if you compile a custom build that includes the pyxpcom bindi...
nsIContentPolicy - Archive of obsolete content
troduced gecko 1.0 inherits from: nsicontentpolicybase last changed in gecko 42 (firefox 42 / thunderbird 42 / seamonkey 2.39) you can observe content that is being loaded into your browser by implementing nsicontentpolicy. this interface can be very useful if you are developing a content-aware plugin (blocking ads or altering the look of content, for example), or if you want to stop or allow user-browsed urls. warning: do not block the caller in your implementations of shouldload() or shouldprocess() (for example, by launching a dialog to prompt the user for something).") note: in reality, much of this interface is defined in the nsicontentpolicybase interface, but for now is documented here until someone has time to split things up. method overview short shouldload(...
... 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 dom properties that depend on style (e.g., computed style). query any dom properties that depend on the current state of the dom outside the "context" node (e.g., lengths of node lists). [javascript implementations only] access properties...
...is 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 on shouldload() to see what this means for implementors of this method. short shouldprocess( in unsigned long acontenttype, in nsiuri acontentlocation, in nsiuri arequ...
...r header file #include "_path_to_sdk/include/content/nsicontentpolicy.h" class myclass: public nsisupports, public nsicontentpolicy { ... ns_decl_nsicontentpolicy ... } // and this into your implementation file ns_impl_isupportsn(myclass, nsisupports, nsicontentpolicy, ...) note: before you can recieve notifications, you must register your plugin with nsicategorymanager. see example below. char* previous = nsnull; nscomptr<nsicategorymanager> catman; servman->getservicebycontractid(ns_categorymanager_contractid, ns_get_iid(nsicategorymanager), getter_addrefs(catman)); rv = catman->addcategoryentry("content-policy", component_classname, component_contractid, pr_true, pr_true, &previous); javascript developers can also implement an xpcom component that extends nsicontentpolicy...
2006-10-20 - Archive of obsolete content
s so far failed to compile firefox with his own extensions of choice so that his custom build would have those extensions enabled in the end product. christopher finke is asking the community members for tutorials or any tips on how to get started. on october 20th christopher finke responded to his original post. he stated that he was able to pre-package the extensions that he wanted by following this walkthrough and a little bit of help from this post. christopher would not like to learn how to create a build of firefox with custom extensions and not have those extensions appear in the addons window. on october 20th jeff walden responded christopher finke's question. jeff provided this link as an answer to christopher finkes' question. nsis and my extension jan vávra is w...
...chine 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. you can do this by replying ...
... 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. you can do this by replying to the following post. discussions sparky and comet going away on friday on october 19th j. paul reed posted the following discussion: j. paul reed stated that he is also going to decommission comet, the machine that performed seamonkey trunk gtk1 builds, this friday. j. paul reed's long-term goal is to remove old incompatible hardware. on the same day robert kaiser responded to j. paul reed's post...
...comet and btek are currently the fastest-cycling tinderboxes available therefore they are quite fast to detect general fires on the mozilla tree. ...
Monitoring plugins - Archive of obsolete content
sumed by the plugin. usage to make use of the new component you must register to receive its runtime notifications using the observer service. the notification's topic is experimental-notify-plugin-call. if you are new to the mozilla observer service, you may want to familiarize yourself with it before proceeding further. you can find more information on the observer service here and here. ...
... find more information on the observer service here and here. ...
...hecks to see that the arriving notification's topic is the correct one. this is useful in cases where your class is registered to receive notifications for more than one topic with the observer service. ...
...no longer want to be listening to runtime notifications - your class must include an unregister method that contains the following code: var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.removeobserver(this, "experimental-notify-plugin-call"); skeleton observer class below is a skeleton class that you may use to listen to runtime notifications: function pluginobserver() { this.registered = false; this.register(); //takes care of registering this class with observer services as an observer for plugin runtime notifications } pluginwatcherobserver.prototype = { observe: function(subject, topic, data) { if (topic == "experimental-notify-plugin-ca...
Why RSS Content Module is Popular - Including HTML Contents - Archive of obsolete content
html data in it. (even through you are not suppose to.) for example, if your blog post was: this is <b>bold</b>. then the <description> would be: <description>this is &lt;b&gt;bold&lt;/b&gt;.</description> note that the "<" has been turned into "&lt;". and the ">" has been turned into "&gt;". this greatly bloats the size of contents but is necessary since certain characters are no allowed in xml. xml does however have the cdata convention. you can put (almost) whatever you want in a cdata section. including "<" and ">" without having to escape them. using the example above we'd have: <description><![cdata[this is <b>bold</b>.]]></description> this helps reduce the bloat. however, the <description> is not suppose to be used for any of this. it is only suppose to be used to...
...uppose to be used for any of this. it is only suppose to be used to includeplain text. but rss still leaves us without a way to include html contents. the rss content module fills this gap. note: do not put anything butplain text into the rss <description> element. although it has become common practice to use the rss <description> element and put non-plain text data in it. ...
...text. but rss still leaves us without a way to include html contents. the rss content module fills this gap. note: do not put anything butplain text into the rss <description> element. although it has become common practice to use the rss <description> element and put non-plain text data in it. it is not actually allowed. ...
...the rss <description> element and put non-plain text data in it. it is not actually allowed. the rss 2.0 specification clearly states that “entity-encoded html is allowed“ and even provides examples showing exactly the syntax above (using cdata and unencoded html). the wording of this note should be reconsidered. ...
SAX - Archive of obsolete content
ml, 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. quick start the sax parser functionality is available through the xml reader component. to create one, use the following code: var xmlreader = components.classes["@mozilla.org/saxparser/xmlreader;1"] .createinstance(components.interfaces.nsisaxxmlreader); after you created the sax parser, you need to set the handlers for the events you're interested in and fire off the parsing process. all functionality is available through the nsisaxxmlreader interface. set the handlers handlers a...
...nterested in and fire off the parsing process. all functionality is available through the nsisaxxmlreader interface. set the handlers handlers are user-defined objects implementing sax handler interfaces, depending on what kind of information they need to get from the parser. after the parsing process is started, handlers receive a series of callbacks for the content of xml being parsed. the following handlers are available: interface purpose nsisaxcontenthandler receive notification of the logical content of a document (e.g. elements, attributes, whitespace, and processing instructions). nsisaxdtdhandler receive notification of basic dtd-related events. nsisaxerrorhandler receive notification of errors in the input stream. nsisaxlex...
..., // nsisupports queryinterface: function(iid) { if(!iid.equals(components.interfaces.nsisupports) && !iid.equals(components.interfaces.nsisaxcontenthandler)) 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. ...
...sisaxcontenthandler)) 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. ...
Tamarin Tracing Build Documentation - Archive of obsolete content
tamarin source versions the following instructions are for obtaining and building the tamarin tracing source code. for instructions on tamarin central, please see tamarin build documentation supported platforms operating system processor status windows xp x86 supported, acceptance and performance tests automated in buildbot mac os x 10.4 x86 supported, acceptance and performance tests automated in buildbot linux - ubuntu 8.0.4 x86 supported, acceptance and performance tests automated in buildbot windows mobile (pocket pc 5.0) armv4t supported, acceptance and performance tests automated in buildbot raw image (no os) armv5 supported, acceptance and performance tests not done linux (nokia n810) armv5 supported, acceptance and performance tests not done current build sta...
...ts automated in buildbot raw image (no os) armv5 supported, acceptance and performance tests not done linux (nokia n810) armv5 supported, acceptance and performance tests not done current build status the current tamarin tracing build status can be found at tamarin tracing build status getting the tamarin source the tamarin tracing source resides in mercurial at tamarin tracing. use the following command to create a copy of the tamarin repository: $ hg clone http://hg.mozilla.org/tamarin-tracing tamarin-tracing building tamarin building tamarin will create all the libraries for the avmplus and garbage collector (mmgc), and create a standalone executable, avmshell, for executing files in the abc file format. running avmshell without any arguments will list the available options. no...
...: $ python ../configure.py --target=arm-windows --enable-shell; make to build for thumb: $ python ../configure.py --target=thumb-windows --enable-shell; make platform-specific builds project files for specific platforms/ides (microsoft visual studio, xcode, etc) are included in the source tree under tamarin-tracing/platform, but are not formally supported. running tamarin compliance tests follow the same steps as the tamarin central instructions. http://developer.mozilla.org/en/docs...mpliance_tests running tamarin performance tests follow the same steps as the tamarin central instructions. http://developer.mozilla.org/en/docs...formance_tests tamarin buildbot adobe maintains a continuous build and test system for tamarin tracing and continuous build and test system for tamarin central, ...
...g/en/docs...formance_tests tamarin buildbot adobe maintains a continuous build and test system for tamarin tracing and continuous build and test system for tamarin central, similar to tinderbox. performance tests are also run on every build. see the latest build performance report for the latest results or a weekly performance report. tamarin buildbot tryserver the tryserver/sandbox is setup to allow users to push any code changes that they would like to have tested in the automated build/test process prior to actually pushing the changes. the sandbox is setup so that it is able to build and test branches that are based on either tamarin-central or tamarin-tracing. any comments, questions or problems can be directed to brent baker how to setup a user repository with the source and patches t...
Using SSH to connect to CVS - Archive of obsolete content
accessing read-only cvs, and our getting write access page for directions on obtaining write access. generating an ssh key first, install ssh. most linux, bsd, and osx distributions come with it installed already. cygwin makes ssh available on windows if you install the openssh package from the net category. if all else fails, openssh is a widely used and highly portable implementation. the following command should generate a suitable key pair: ssh-keygen -t dsa this will take a moment, followed by a prompt for a passphrase. once you have entered a passphrase, ssh-keygen will create two files, ~/.ssh/id_dsa and ~/.ssh/id_dsa.pub do not sendid_dsa. do file a server operations bug in bugzilla and attach yourid_dsa.pub to the bug. setting up cvs to use ssh in your system's environ...
...org from the open internet. if you are behind a firewall with an http tunneling proxy, you can use a program called corkscrew, in combination with the proxycommand ssh config directive to continue to access the mozilla cvs server. this technique was taken from eric engstrom's site, but the instructions have been re-written specifically for mozilla. ...
...taken from eric engstrom's site, but the instructions have been re-written specifically for mozilla. download, build, and install corkscrew by following the instructions in the install file in the corkscrew source distribution. corkscrew uses the standard "./configure; make install" technique common to many open source projects. make sure you have a ~/.ssh/config file that has at least the following directives preferredauthentications hostbased,publickey,password host cvs.mozilla.org proxycommand corkscrew <i>proxyserver.foo.com</i> <i>port</i> %h %p replaceproxyserver.foo.com with the hostname of your proxy server, andport with the numeric tcp port on which the http tunnel is running. the usual cvs commands should now work. avoiding passphrase requests you can avoid repeated pas...
...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 session, and be passed on to all child shells. ms-dos command prompt cygwin for /f "t...
-ms-block-progression - Archive of obsolete content
layout is vertical. ...
...layout is vertical. ...
...layout is vertical. ...
...layout is vertical. formal syntax tb | rl | bt | lr specifications not part of any specification. ...
-ms-scroll-snap-points-x - Archive of obsolete content
ong the x-axis. initial valuesnapinterval(0px, 100%)applies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete syntax values note: a <length-percentage> is a value that can be either a <length> or a <percentaqe>. snapinterval( <length-percentage>, <length-percentage> ) specifies a starting snap-point followed by the interval between all snap-points. the first value specifies 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...
...onstrates both types of values for the -ms-scroll-snap-points-x property. in the first selector, the first snap-point is at 0%, and the interval is set to 100%. in the second selector, each snap-point is listed separately — 100%, 200%, 300%, and so on. ...
... of values for the -ms-scroll-snap-points-x property. in the first selector, the first snap-point is at 0%, and the interval is set to 100%. in the second selector, each snap-point is listed separately — 100%, 200%, 300%, and so on. ...
...ly — 100%, 200%, 300%, and so on. (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 w...
-ms-scroll-snap-points-y - Archive of obsolete content
ong the y-axis. initial valuesnapinterval(0px, 100%)applies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete syntax values note: a <length-percentage> is a value that can be either a <length> or a <percentaqe>. snapinterval( <length-percentage>, <length-percentage> ) specifies a starting snap-point followed by the interval between all snap-points. the 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 facto...
...onstrates both types of values for the -ms-scroll-snap-points-y property. in the first selector, the first snap-point is at 0%, and the interval is set to 100%. in the second selector, each snap-point is listed separately — 100%, 200%, 300%, and so on. ...
... of values for the -ms-scroll-snap-points-y property. in the first selector, the first snap-point is at 0%, and the interval is set to 100%. in the second selector, each snap-point is listed separately — 100%, 200%, 300%, and so on. ...
...ly — 100%, 200%, 300%, and so on. (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 w...
VBArray.lbound - Archive of obsolete content
non-standard. do not use! this object is a microsoft extension and is only supported in internet explorer. the vbarray.lbound method returns the lowest index value used in the specified dimension of a vbarray. syntax safearray.lbound(dimension) remarks if the vbarray is empty, the lbound method returns undefined. if dimension is greater than the number of dimensions in the vbarray, or is negative, the method generates a "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...
...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. ...
...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. ...
...t"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(j, i) = k k = k + 1 next next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vba){ var i; var a = new vbarray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the lower bound of dimension "; s += i + " is "; s += a.lbound(i); s += ".<br />"; } return (s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standa...
XForms Select Element - Archive of obsolete content
introduction allows the user to choose one or more selections from a list of pre-defined items (see the spec). the list of pre-defined items can be specified by either item (see the spec) or itemset (see the spec) elements. you can visually group these pre-defined items by using the choices (see the spec) element to contain them. note, some representations of the select element do not support visual grouping. attributes ui common appearance - the value of this attribute gives a hint to the xforms processor as to which type of widget(s) to use to represent this control. accesskey - used to specify the keyboard shortcut for focusing this control. single-node binding special selection - isn't currently supported. ...
...lect element do not support visual grouping. attributes ui common appearance - the value of this attribute gives a hint to the xforms processor as to which type of widget(s) to use to represent this control. accesskey - used to specify the keyboard shortcut for focusing this control. single-node binding special selection - isn't currently supported. this attribute, when set to 'open', allows the user to provide free entry to the list. possible values are open and closed, default is closed. incremental - supported, default value is true properties selection - see corresponding attribute incremental - see corresponding attribute type restrictions the select element can be bound to a node containing simple content capable of holding a sequence. the data binding restriction to...
...nd closed, default is closed. incremental - supported, default value is true properties selection - see corresponding attribute incremental - see corresponding attribute type restrictions the select element can be bound to a node containing simple content capable of holding a sequence. ...
...t element is used, which allows the available choices to be obtained from an xforms model. the relaxation happens when the itemset element specifies the item value using a copy (see spec) element. this is because a copy element can be used to add a subtree of nodes underneath the element that the select control is bound to. representations the xforms select element can be represented by the following widgets for the specified appearance attribute values: list - default representation (xhtml/xul) check group- used when appearance = 'full' (xhtml/xul) list displaying a listbox is the default representation (xhtml/xul). characteristics analogous widgets are <html:select size="5" multiple="true"/> and <xul:listbox seltype="multiple"/> visual grouping by choices element isn't implement...
Popup Window Controls - Archive of obsolete content
mozilla and firefox allow users to control most unsolicited attempts to open new windows such as popup and popunder windows. learn how to detect popup controls, how to ask your readers to enable popups for your site and how to get the benefits of popup windows without using popup windows. ...
...la and firefox allow users to control most unsolicited attempts to open new windows such as popup and popunder windows. learn how to detect popup controls, how to ask your readers to enable popups for your site and how to get the benefits of popup windows without using popup windows. ...
...o get the benefits of popup windows without using popup windows. ...
...you can also provide a hyperlink which can be used to open a popup window even in the event that the user has suppressed unsolicited popups on your site. replacements for popup windows if your popup was created during the time the web page was loading, you may consider using document.write() to emit appropriate html which will contain the same information as ...
The Business Benefits of Web Standards - Archive of obsolete content
ent behavior by platform, mozilla-based browsers are designed to behave identically on all supported platforms (mac, linux, unix, windows...) web content is increasingly being accessed by a growing number of user agents other than browsers, or by browsers on different platforms - for example mobile telephones. feed content such as rss and atom simply will not work without being implemented by following the requisite standard. assumptions about the user and their platform based on erroneous thinking about the anticipated user community are inevitably always wrong. it does not follow for example that successful business users have wide monitors. the opposite may be true. power users and business travellers are downsizing their notebooks. increasingly one person may need to acccess the same si...
...chnologies 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 turn can act as fuel for social media dialogue with the user community. from this it follows that there needs to be a framework and a process for content contributors to post articles, to upload videos, sound or any other media. a web site is only a vehicle for carrying, navigating and displaying that content. content management systems attempt with some success to supply that level of functionality. they act as a very good example of real separation not only of style and content but th...
...reasingly difficult commercial future. the development process: working in teams a common challenge for web developers when assuming management of existing sites is the code written by other developers. in many cases, they are faced with poor html code quality that may also rely on undocumented features or hacks and specific coding practices. lack of documentation is also often problematic. following standards-compliance in requirements documents is a very effective way to ensure measurable quality of the final product, the w3c being an impartial judge. because standards are very well documented, another person taking over some standard-compliant code can hit the ground running - and will not need to become familiar with the previous developer's coding practices. this also significantly r...
...l these great experiences can be enjoyed by the user regardless of platform, software, operating system, or any one of a dozen other variables including screen size, text resolution, javascript activation, or any disabilty the user may have. conclusion using web standards and separating structure from presentation brings a host of benefits for today and tomorrow. today, it means more audience, lower cost to produce new content, and becoming compliant with accessibility requirements. for tomorrow, it means reducing vendor lock-in, reducing cost of maintenance, and having a more flexible web site in terms of presentation. last but not least, use of standards opens the door to xml technologies. all these factors also contribute to easier site management, a larger audience and a better retur...
3D collision detection - Game development
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. ...
... 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 trigonometric operations, which are slower to calculate. if you have entities that will be rotating, you can either modify the dimensions of the bounding box so it still wraps the object, or opt to use another bounding geometry type, such as spheres (which are invariant to rotation.) the animated gif below shows a graphic example of an aabb that adapts its size to fit the rotating entity. the box constantly changes dimensions to snugly ...
...ecking 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. ...
...avascript: function ispointinsideaabb(point, box) { return (point.x >= box.minx && point.x <= box.maxx) && (point.y >= box.miny && point.y <= box.maxy) && (point.z >= box.minz && point.z <= box.maxz); } aabb vs. aabb checking whether an aabb intersects another aabb is similar to the point test. we just need to do one test per axis, using the boxes' boundaries. ...
Explaining basic 3D theory - Game development
etry 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 own shaders that manipulate the output. vert...
...nd lighting — it calculates final colors based on the given parameters. textures textures are 2d images used in the 3d space to make the objects look better and more realistic. textures are combined from single texture elements called texels the same way picture elements 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 ...
... on the screen display. during output merging some processing is also applied to ignore information that is not needed — for example the parameters of objects that are outside of the screen or behind other objects, and thus not visible, are not calculated. ...
...uring output merging some processing is also applied to ignore information that is not needed — for example the parameters of objects that are outside of the screen or behind other objects, and thus not visible, are not calculated. ...
Implementing game control mechanisms - Game development
captain rogers was created using the phaser framework, the most popular tool for simple 2d game development in javascript right now, but it should be fairly easy to reuse the knowledge contained within these articles when building games in pure javascript or any other framework. if you're looking for a good introduction to phaser, then check the 2d breakout game using phaser tutorial. in the following articles we will show how to implement various different control mechanisms for captain rogers to support different platforms — from touch on mobile, through keyboard/mouse/gamepad on desktop, to more unconventional ones like tv remote, shouting to or waving your hand in front of the laptop, or squeezing bananas. setting up the environment let's start with a quick overview of the game's fo...
...menu.js and game.js files, and we'll explain the code inside the create() and update() methods in much more detail in later articles. pure javascript demo 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. ...
...e 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 essential to provide an acceptable level of accessibility for the...
...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 essential to provide an acceptable level of accessibility for the game. desktop gamepad controls — the gamepad api rather usefully allows gamepads to be used for controlling web apps on desktop/laptop, for that console feel. unconventional controls — the final article showcases some unconventional control mechanisms, from the experimental to the slightly crazy, which you might not believe could be used to play the game. ...
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...
...", so they submitted a game where you have to feed the hungry fridge by tapping the healthy food (apples, carrots, lettuces) and avoid the "bad" food (beer, burgers, pizza.) a countdown changes the type of food the fridge wants to eat every few seconds, so you have to be careful and act quickly. the second, hidden "change" implementation is the ability to transform the static fridge into a full-blown moving, shooting and eating machine. when you connect the controller, the game significantly changes (hungry fridge turns into the super turbo hungry fridge) and you're able to control the armored fridge using the gamepad api. you have to shoot down the food, but once again you also have to find the type of food the fridge wants to eat at each point, or else you'll lose energy. the game encapsu...
...ypes of "change" — good food vs. bad food, and mobile vs. desktop. demo the full version of the hungry fridge game was built first, and then to showcase the gamepad api in action and show the javascript source code, a simple demo was created. it's part of the gamepad api content kit available on github where you can dive deep into the code and study exactly how it works. the code explained below is from the full version of the hungry fridge game, but it's almost identical to the one from the demo — the only difference is that the full version uses the turbo variable to decide whether or not the game will be launched using super turbo mode. it works independently, so it could be turned on even if the gamepad is not connected. note: easter egg time: there's a hidden option to launch su...
...is.player.angle += 3; this.turret.angle += 3; } even if we move it a little by mistake or the stick doesn't make it back to its original position, the tank won't turn unexpectedly. specification update after more than a year of stability, in april 2015 the w3c gamepad api spec was updated (see the latest.) it hasn't changed much, but it's good to know whats going on — the updates are as follows. getting the gamepads the navigator.getgamepads() method has been updated with a longer explanation and an example piece of code. now the length of the array of gamepads has to be n+1 where n is the number of connected devices — when there's one device connected and it has the index of 1, the array's length is 2 and it will look like this: [null, [object gamepad]]. if the device is disconnec...
Build the brick field - Game development
e bricks to destroy with the ball, and this is what we'll create now! setting up the brick variables the overall aim of this lesson is to render a few lines of code for the bricks, using a nested loop that works through a two-dimensional array. first however we need to set up some variables to define information about the bricks such as their width and height, rows and columns, etc. add the following lines to your code below the variables which you have previously declared in your program. var brickrowcount = 3; var brickcolumncount = 5; var brickwidth = 75; var brickheight = 20; var brickpadding = 10; var brickoffsettop = 30; var brickoffsetleft = 30; here we've defined the number of rows and columns of bricks , their width and height, the padding between the bricks so they won't touch ...
...n the bricks so they won't touch each other and a top and left offset so they won't start being drawn right from the edge of the canvas. we will hold all our bricks in a two-dimensional array. it will contain the brick columns (c), which in turn will contain the brick rows (r), which in turn will each contain an object containing the x and y position to paint each brick on the screen. add the following just below your variables: var bricks = []; for(var c=0; c<brickcolumncount; c++) { bricks[c] = []; for(var r=0; r<brickrowcount; r++) { bricks[c][r] = { x: 0, y: 0 }; } } the code above will loop through the rows and columns and create the new bricks. note that the brick objects will also be used for collision detection purposes later. brick drawing logic now let's cre...
...ow number, r, brickheight, and brickoffsettop. now every single brick can be placed in its correct place row and column, with padding between each brick, drawn at an offset from the left and top canvas edges. ...
... ctx.rect(brickx, bricky, brickwidth, brickheight); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); } } } actually drawing the bricks the last thing to do in this lesson is to add a call to drawbricks() somewhere in the draw() function, preferably at the beginning, between the clearing of the canvas and drawing the ball. add the following just above the drawball() call: drawbricks(); compare your code at this point, the game has got a little more interesting again : exercise: try changing the number of bricks in a row or a column, or their positions. next steps so now we have bricks! but the ball isn't interacting with them at all — we'll change that as we continue to the seventh chapter: collision detection. ...
Track the score and win - Game development
uld look after completing this lesson at gamedev-canvas-workshop/lesson8.html. destroying the bricks is really cool, but to be even more awesome the game could award points for every brick a user hits, and keep count of the total score. counting the score if you can see your score throughout the game, eventually you can impress your friends. you need a variable to record the score. add the following into your javascript, after the rest of your variables: var score = 0; you also need a drawscore() function, to create and update the score display. add the following after the collisiondetection() function: function drawscore() { ctx.font = "16px arial"; ctx.fillstyle = "#0095dd"; ctx.filltext("score: "+score, 8, 20); } drawing text on a canvas is similar to drawing a shape. t...
...d where it will be placed. the first parameter is the text itself — the code above shows the current number of points — and the last two parameters are the coordinates where the text will be placed on the canvas. to award a score each time a brick is hit, add a line to the collisiondetection() function to increment the value of the score variable each time a collision is detected. ...
...add ...
... if(b.status == 1) { if(x > b.x && x < b.x+brickwidth && y > b.y && y < b.y+brickheight) { dy = -dy; b.status = 0; score++; } } } } } calling drawscore() from the draw() function keeps the score up to date with every new frame — add the following line inside draw(), just below the drawpaddle() call: drawscore(); displaying a winning message when all bricks have been destroyed collecting the points works well, but you won't be adding them forever — what about when all the bricks have been destroyed? it's the main purpose of the game after all, so you should display a winning message if all available points have been collected. add the following highlighted section ...
Buttons - Game development
on at gamedev-phaser-content-kit/demos/lesson15.html. instead of starting the game right away we can leave that decision to the player by adding a start button they can press. let's investigate how to do that. new variables we will need a variable to store a boolean value representing whether the game is currently being played or not, and another one to represent our button. add these lines below your other variable definitions: var playing = false; var startbutton; loading the button spritesheet we can load the button spritesheet the same way we loaded the ball's wobble animation. add the following to the bottom of the preload() function: game.load.spritesheet('button', 'img/button.png', 120, 40); a single button frame is 120 pixels wide and 40 pixels high. you also need to grab ...
...ion. add the following to the bottom of the preload() function: game.load.spritesheet('button', 'img/button.png', 120, 40); a single button frame is 120 pixels wide and 40 pixels high. you also need to grab the button spritesheet from github, and save it in your /img directory. adding the button to the game adding the new button to the game is done by using the add.button method. ...
...thub, and save it in your /img directory. adding the button to the game adding the new button to the game is done by using the add.button method. add the following lines to the bottom of your create() function: startbutton = game.add.button(game.world.width*0.5, game.world.height*0.5, 'button', startgame, this, 1, 0, 2); startbutton.anchor.set(0.5); the button() method's parameters are as follows: the button's x and y coordinates the name of the graphic asset to be displayed for the button a callback function that will be executed when the button is pressed a reference to this to specify the execution context the frames that will be used for the over, out and down events. note: the over event is the same as hover, out is when the pointer moves out of the button and down is when...
... « previousnext » ...
Physics - Game development
ble as a commercial plugin. for simple games like ours, we can use the arcade physics engine. we don't need any heavy geometry calculations — after all it's just a ball bouncing off walls and bricks. first, let's initialize the arcade physics engine in our game. ...
...ng off walls and bricks. first, let's initialize the arcade physics engine in our game. add the physics.startsystem() method at the beginning of the create function (make it the first line inside the function), as shown below: game.physics.startsystem(phaser.physics.arcade); next, we need to enable our ball for the physics system — phaser object physics is not enabled by default. ...
...he function), as shown below: game.physics.startsystem(phaser.physics.arcade); next, we need to enable our ball for the physics system — phaser object physics is not enabled by default. add the following line at the bottom of the create() function: game.physics.enable(ball, phaser.physics.arcade); next, if we want to move our ball on the screen, we can set velocity on its body. add the following line, again at the bottom of create(): ball.body.velocity.set(150, 150); removing our previous update instructions remember to remove our old method of adding values to x and y from the update() function: function update() { ball.x += 1; ball.y += 1; } we are now handling this properly, with a physics engine. final code check the latest code should look like this: var ball; ...
...cts of gravity pulling it down. this kind of functionality is just the tip of the iceberg — there are various functions and variables that can help you manipulate the physics objects. check out the official physics documentation and see the huge collection of examples using the arcade and p2 physics systems. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps now we can move to the next lesson and see how to make the ball bounce off the walls. « previousnext » ...
Visual JS GE - Game development
the client made in four variant on a javascript frameworks for 2d canvas js , three.js , webgl2 vs glmatrix and 2d canvas with matter.js in typescript to complete the stack. installation and setup first of all download visual-js from bitbucket. extract the package into your root folder. installing modules navigate to server_instance/, then in the node.js command prompt or console enter the following installation commands: npm install mysql npm install delivery npm install express npm install mkdirp npm install socket.io npm install nodemailer@0.7.0 setting up config.js you will find config.js in the server_instance folder: all node.js applications use the same folder — server_instance. some apps might need to have local storage, for instance, editor.js. you need to edit the config fi...
...s npm install mkdirp npm install socket.io npm install nodemailer@0.7.0 setting up config.js you will find config.js in the server_instance folder: all node.js applications use the same folder — server_instance. some apps might need to have local storage, for instance, editor.js. ...
... in page editor found at server_instance/editor.js. build_from_editor_to_visual_js found at server_instance/build_from_editor_to_visual_js_file.js. this is a node.js app for local use. if you use editor.js to visually create game objects, you must start the build_from_editor_to_visual_js_file.js when you have ...
...system folder lib/visual_scripts/ and generates your code. resource js objects used for adding images for animation purposes. this is done using server_instance/res.js. you need to put your images in a folder, for example test_res/ , inside project_instance/res/. next, run the command server_instance/node res.js. after this has finished processing, restart the web page by entering the following in the console: resource.test_res. resource objects contain the path data for all your images. the actual image objects will be created after you add animation to the game objects. this is good because it is memory safe. visual js.exe windows gui freeware only for windows users. contains the following tools. visual_js.exe version 1.0 — comes with source editor. ml_sys.exe — multi...
Grid Lines - MDN Web Docs Glossary: Definitions of Web-related terms
this gives us 4 column lines and 3 row lines. ...
...emplate-columns: repeat(3, 1fr); grid-template-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. ...
...elow 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 column line 1 to column line 3, and from row line 1 to row line 3. * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 100px); } .wrapper > div { border: 2px solid #ffa94d; bo...
...peat(3, 1fr); grid-template-rows: 100px 100px; } .item { grid-column-start: 1; grid-column-end: 3; grid-row-start: 1; grid-row-end: 3; } naming lines the lines created in the explicit grid can be named, by adding the name in square brackets before or after the track sizing information. 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; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 100px); } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } <div class="w...
SQL Injection - MDN Web Docs Glossary: Definitions of Web-related terms
web apps that fail to validate user input. hackers can maliciously pass sql commands through the web app for execution by a backend database. sql injection can gain unauthorized access to a database or to retrieve information directly from the database. many data breaches are due to sql injection. ...
...se. 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 called a magical string, for example: username: admin password: anything 'or'1'='1 after clicki...
... ' 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 statement and hence returns a true value. finally, due to the or operator, the value ( false or true ) is t...
...nce password=anything results in false, but '1'='1' is a true statement and hence returns a true value. finally, due to the or operator, the value ( false or true ) is true, so authentication bypasses successfully. just due to a simple string (magical string) the entire database is compromised. how to prevent before executing the queries for the user credentials, make some changes like the following: $id = $_get['id'] (1) $id = stripslashes($id) (2) $id = mysql_real_escape_string($id) so due to (1) each single quote (') in the input string is replaced with double quotes ("), and due to (2) before every (') it adds (/). the revised magical string fails to bypass the authentication, and your database stays secure. learn more general knowledge sql injection on wikipedia explanatio...
Accessibility - Learn web development
bilities. sites should also not cause harm: web features like motion can cause migraines or epileptic seizures. by default, html is accessible, if used correctly. web accessibility involves ensuring that content remains accessible, regardless of who and how the web is accessed. the firefox accessibility inspector is a very useful tool for checking out accessibility issues on web pages. the following video provides a nice introduction to it: 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 get the most out of this module, it would be a good idea to either work through at least the first two modules of the html, css, and javascript topics, or perhap...
...u can try out most of the code examples in an online coding program such as jsbin or glitch. guides what is accessibility? this article starts off the module with a good look at what accessibility is — this includes what groups of people we need to consider and why, what tools different people use to interact with the web, and how we can make accessibility part of our web development workflow. ...
...opment workflow. html: a good basis for accessibility a great deal of web content can be made accessible just by making sure the correct html elements are always used for the correct purpose . this article looks in detail at how html can be used to ensure maximum accessibility. css and javascript accessibility best practices css and javascript, when used properly, also have the potential to allow for accessible web experiences, but if misused they can significantly harm accessibility. this article outlines some css and javascript best practices that should be considered to ensure that even complex content is as accessible as possible. ...
...cessibility. css and javascript accessibility best practices css and javascript, when used properly, also have the potential to allow for accessible web experiences, but if misused they can significantly harm accessibility. this article outlines some css and javascript best practices that should be considered to ensure that even complex content is as accessible as possible. wai-aria basics following on from the previous article, sometimes making complex ui controls that involve unsemantic html and dynamic javascript-updated content can be difficult. wai-aria is a technology that can help with such problems by adding in further semantics that browsers and assistive technologies can recognize and use to let users know what is going on. here we'll show how to use it at a basic level to impro...
Attribute selectors - Learn web development
value is exactly value — the string inside the quotes. [attr~=value] p[class~="special"] matches elements with an attr attribute whose value is exactly value, or contains value in its (space separated) list of values. [attr|=value] div[lang|="zh"] matches elements with an attr attribute whose value is exactly value or begins with value immediately followed by a hyphen. in the example below you can see these selectors being used. by using li[class] we can match any selector with a class attribute. this matches all of the list items except the first one. li[class="a"] matches a selector with a class of a, but not a selector with a class of a with another space-separated class as part of the value. it selects the second list item. li[cla...
...i[class="a"] matches a selector with a class of a, but not a selector with a class of a with another space-separated class as part of the value. it selects the second list item. li[class~="a"] will match a class of a but also a value that contains the class of a as part of a whitespace-separated list. it selects the second and third list items. substring matching selectors these selectors allow for more advanced matching of substrings inside the value of your attribute. for example, if you had classes of box-warning and box-error and wanted to match everything that started with the string "box-", you could use [class^="box-"] to select them both (or [class|="box"] as described in section above). selector example description [attr^=value] li[class^="box-"]...
...ches all of our list items. case-sensitivity if you want to match attribute values case-insensitively you can use the value i before the closing bracket. this flag tells the browser to match ascii characters case-insensitively. without the flag the values will be matched according to the case-sensitivity of the document language — in html's case it will be case sensitive. in the example below, the first selector will match a value that begins with a — it only matches the first list item because the other two list items start with an uppercase a. the second selector uses the case-insensitive flag and so matches all of the list items. note: there is also a newer value s, which will force case-sensitive matching in contexts where matching is normally case-insensitive, however this ...
...can continue on to the next article and read about pseudo-class and pseudo-element selectors. ...
Test your skills: The Box Model - Learn web development
the aim of this task is to help you check your understanding of the css box model. note: you can try out solutions in the interactive 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. the box model one with the two boxes below, one is using the standard box model, the other the alternate box model. change the width of the second box by adding rules to the .alternate class, so that it matches the visual width of the first box. ...
...et stuck, then ask us for help — see the assessment or further help section at the bottom of this page. the box model one with the two boxes below, one is using the standard box model, the other the alternate box model. change the width of the second box by adding rules to the .alternate class, so that it matches the visual width of the first box. your final result will look like the image below. 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. the box model two in this task, add to the box: a 5px, black, dotted border. a top margin of 20px. a right margin of 1em. a bottom margin of 40px. a left margin of 2em. padding on...
...e 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. the box model two in this task, add to the box: a 5px, black, dotted border. a top margin of 20px. a right margin of 1em. a bottom margin of 40px. a left margin of 2em. padding on all sides of 1em. try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. the box model three in this example the inline element has a margin, padding and border however the lines above and below are overlapping it. what can you add to your css to cause the size of the margin, pad...
...for this task to work in your own editor or in an online editor. the box model three in this example the inline element has a margin, padding and border however the lines above and below are overlapping it. what can you add to your css to cause the size of the margin, padding, and border to be respected by the other lines, while still keeping the element inline? 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. 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 want to ask for help: put your work into an online shareable e...
Test your skills: sizing - Learn web development
the aim of this task is to help you check your understanding of some of the values and units that we looked at in the lesson on sizing items in css. note: you can try out solutions in the interactive 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. task one in this task, you have two boxes. the first should be sized so that the height will be at least 100 pixels tall, even if there is less content than would cause it to grow to that height, however, the content should not overflow if there is more content than fits in 100 pixels. test this box by removing the content from the...
... will be at least 100 pixels tall, even if there is less content than would cause it to grow to that height, however, the content should not overflow if there is more content than fits in 100 pixels. test this box by removing the content from the html to make sure you still get a 100 pixel tall box even with no content. the second box should be fixed at 100 pixels tall, so that content will overflow if there is too much. 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. task two this task has a box, which contains another box. your task is to make the inner box 60% of the width of the outer box. the value of the box-sizing property i...
... a box, which contains another box. your task is to make the inner box 60% of the width of the outer box. the value of the box-sizing property is set to border-box, which means that the total width includes any padding and border. you should also give the inner box padding of 10% using the width (or inline size) as the size from which that percentage is calculated. try updating the live code below to recreate the example as displayed in the image: 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 three this task has two images in boxes. one image is smaller than the box, the other is larger and breaking out of the box. if you imagine that the box is responsive and therefore could grow and shrink...
...or in an online editor. task three this task has two images in boxes. one image is smaller than the box, the other is larger and breaking out of the box. if you imagine that the box is responsive and therefore could grow and shrink, which property would you apply to the image so that the large image shrinks down into the box but the small image does not stretch. try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors mentioned above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an o...
Test your skills: values and units - Learn web development
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, the first list item has been given a background color using hex color codes. ...
...same color in different formats, plus a final list item where you should make the background semi-opaque. the second list item should use rgb color. the third should use hsl color. the fourth should use rgb color but with the alpha channel set to .2. you can find conversions for the hex color at this link. you need to figure out how to use the values in css. 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. task two in this task you need to set the size of various items of text. the <h1> should be 50 pixels. the <h2> should be 2em. all <p> elements should be 16 pixels. a <p> element that is directly after an <h1> should b...
...r 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 need to set the size of various items of text. the <h1> should be 50 pixels. the <h2> should be 2em. all <p> elements should be 16 pixels. a <p> element that is directly after an <h1> should be 120%. ...
... assessment or further help you can practice these examples in the interactive editors mentioned above. ...
Test your skills: Writing Modes and Logical Properties - Learn web development
the aim of this task is to help you check your understanding of writing modes and logical properties. the things you need to know to complete these tasks are covered in the lesson on handling different text directions. note: you can try out solutions in the interactive 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. ...
...ol 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 the box in the example is displayed with a horizontal writing mode. can you add a line of css to change it so it uses a vertical writing mode with right to left text? your example should look like the image below. 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. task two in the example below use logical properties to replace width and height in order to maintain the aspect ratio of the box as it is turned vertically. your end result should look l...
...g 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. task two in the example below use logical properties to replace width and height in order to maintain the aspect ratio of the box as it is turned vertically. your end result should look like the image below. try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. ...
...uld look like the image below. try updating the live code below to recreate the example as displayed in the image: 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 three use logical versions of the margin, border, and padding properties so that the edges of the box relate to the text rather than following top, left, bottom and right. you can see how this should look in the image below. 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. assessment or further help you can practice these examples in the interactive editors mentioned above. ...
Test Your Skills: Fundamental layout comprehension - Learn web development
if you have worked through this module then you will have already covered the basics of what you need to know to do css layout today, and to work with older css as well. this task will test some of your knowledge by way of developing a simple webpage layout using a variety of techniques. note: you can try out solutions in the interactive 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. project brief you have been provided with some raw html, basic css, and images — now you need to create a layout for the design, which should look just like the image below. basic setup you ...
... if you don't want to work locally then using a tool such as codepen or jsfiddle will work as well. you will need to upload the images using their assets functionality and replace the value in the src attribute to point to the new image location. ...
... if you don't want to work locally then using a tool such as codepen or jsfiddle will work as well. ...
... link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). ...
Test your skills: Multicol - Learn web development
the aim of this task is to get you working with the css column-count, column-width, column-gap, column-span and column-rule properties and values covered in our lesson on multiple-column layout. you will be working through three small tasks which use different elements of the material you have just covered. ...
... 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. ...
...reate 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. ...
... assessment or further help you can practice these examples in the interactive editors mentioned above. ...
Supporting older browsers - Learn web development
g your content read out to them by a screen reader, or have zoomed in on the page to be able to read it. supporting everyone means serving a version of your content that is designed defensively, so that it will look great on modern browsers, but will still be usable at a basic level for users of older browsers. a basic level of support comes from structuring your content well so that the normal flow of your page makes sense. a user with a very limited feature 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 l...
... is a definition for what happens if a floated item, for example, is also a grid item using css grid layout. couple this information with the knowledge that browsers ignore css that they don’t understand, and you have a way to create simple layouts using the legacy techniques we have already covered, which are then overwritten by your grid layout in modern browsers that understand it. in the below example, we have floated three <div>s so they display in a row. any browser that does not support css grid layout will see the row of boxes as a floated layout. a floated item that becomes a grid item loses the float behaviour, which means that by turning the wrapper into a grid container, the floated items become grid items. if the browser supports grid layout it will display the grid view, if n...
...round-color: rgb(207,232,220); padding: 1em; width: 33.333%; } <div class="wrapper"> <div class="item">item one</div> <div class="item">item two</div> <div class="item">item three</div> </div> to deal with this issue we need to have a way to detect if grid is supported and therefore if it will override the width. css has a solution for us here. feature queries feature queries allow you to test whether a browser supports any particular css feature. this means that you can write some css for browsers that don’t support a certain feature, then check to see if the browser has support and if so throw in your fancy layout. if we add a feature query to the above example, we can use it to set the widths of our items back to auto if we know that we have grid support. * {box-si...
...ity of flexbox css grid layout and progressive enhancement using css grid: supporting browsers without grid a tutorial which uses the ie10 and 11 version of grid should i try to use the ie10 implementation of grid layout? ...
CSS layout - Learn web development
ilable in css. at the end of the lessons is an assessment to help you check your understanding of layout methods, by laying out a webpage. introduction to css layout this article will recap some of the css layout features we've already touched upon in previous modules — such as different display values — and introduce some of the concepts we'll be covering throughout this module. normal flow elements on webpages lay themselves out according to normal flow - until we do something to change that. this article explains the basics of normal flow as a grounding for learning how to change it. flexbox flexbox is a one-dimensional layout method for laying out items in rows or columns. items flex to fill additional space and shrink to fit into smaller spaces. this article explains all the ...
...eed to know to get started with page layout, then test your grid skills before moving on. floats originally for floating images inside blocks of text, the float property became one of the most commonly used tools for creating multiple column layouts on webpages. with the advent of flexbox and grid it has now returned to its original purpose, as this article explains. positioning positioning allows you to take elements out of the normal document layout flow, and make them behave differently, for example sitting on top of one another, or always remaining in the same place inside the browser viewport. this article explains the different position values, and how to use them. multiple-column layout the multiple-column layout specification gives you a method of laying content out in columns, ...
...n values, and how to use them. multiple-column layout the multiple-column layout specification gives you a method of laying content out in columns, as you might see in a newspaper. this article explains how to use this feature. responsive design as more diverse screen sizes have appeared on web-enabled devices, the concept of responsive web design (rwd) has appeared: a set of practices that allows web pages to alter their layout and appearance to suit different screen widths, resolutions, etc. it is an idea that changed the way we design for a multi-device web, and in this article we'll help you understand the main techniques you need to know to master it. beginner's guide to media queries the css media query gives you a way to apply css only when the browser and device environment matc...
...n for a multi-device web, and in this article we'll help you understand the main techniques you need to know to master it. beginner's guide to media queries the css media query gives you a way to apply css only when the browser and device environment matches a rule that you specify, for example "viewport is wider than 480 pixels". media queries are a key part of responsive web design, as they allow you to create different layouts depending on the size of the viewport, but they can also be used to detect other things about the environment your site is running on, for example whether the user is using a touchscreen rather than a mouse. in this lesson you will first learn about the syntax used in media queries, and then move on to use them in a worked example showing how a simple design might ...
How do you set up a local testing server? - Learn web development
sting server. local files vs. remote files throughout most of the learning area, we tell you to just open your examples directly in a browser — this can be done by double clicking the html file, dragging and dropping it into the browser window, or choosing file > open... and navigating to the html file. there are many ways to achieve this. if the web address path starts with file:// followed by the path to the file on your local hard drive, a local file is being used. in contrast, if you view one of our examples hosted on github (or an example on some other remote server), the web address will start with http:// or https://, to show that the file has been received via http. the problem with testing local files some examples won't run if you open them as local files. this can be d...
...ples by running them through a local web server. one of the easiest ways to do this for our purposes is to use python's simplehttpserver (or http.server, depending on the version of python installed.) to do this: install python. if you are using linux or macos, it should be available on your system already. if you are a windows user, you can get an installer from the python homepage and follow the instructions to install it: go to python.org under 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 h...
...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 directory level if you need to cd .. enter the command to star...
... by default, this will run the contents of the directory on a local web server, on port 8000. you can go to this server by going to the url localhost:8000 in your web browser. here you'll see the contents of the directory listed — click the html file you want to run. note: if you already have something running on port 8000, you can choose another port by running the server command followed by an alternative port number, e.g. python3 -m http.server 7800 (python 3.x) or python -m simplehttpserver 7800 (python 2.x). you can then access your content at localhost:7800. running server-side languages locally python's simplehttpserver (python 2.0) http.server (python 3.0) module is useful, but it doesn't know how to run code written in languages such as python, php or javascript. to h...
HTML forms in legacy browsers - Learn web development
e "nicer" or "with advanced functionality", but building efficient html forms is not a question of design or technology. rather, it's about simplicity, intuitivess, and ease of user interaction. the tutorial, forms usability 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 th...
...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 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 validation api test : modernizr.formvalidation, // if the browser does not support it, the following polyfill is loaded nope : form-validation-api-polyfill.js, // in any case, your core app file that depends on that api is loaded both : app.js, // once both files are loaded, this function is called in order to initialize the app. complete : function () { app.init(); } }); the modernizr team conveniently maintains a list of great polyfills. just pick what you need. note: m...
...esome features to help you in dealing with unobstructive javascript and graceful degradation techniques. please read the modernizr documentation. pay attention to performance even though scripts like modernizr are very aware of performance, loading a 200 kilobyte polyfill can affect the performance of your application. this is especially critical with legacy browsers; many of them have a very slow javascript engine that can make the execution of all your polyfills painful for the user. performance is a subject on its own, but legacy browsers 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...
Example 2 - Learn web development
<span class="value">cherry</span> <ul class="optlist hidden"> <li class="option">cherry</li> <li class="option">lemon</li> <li class="option">banana</li> <li class="option">strawberry</li> <li class="option">apple</li> </ul> </div> <form> css content .widget select, .no-widget .select { position : absolute; left : -5000em; height : 0; overflow : hidden; } /* --------------- */ /* required styles */ /* --------------- */ .select { position: relative; display : inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline: none; } .select .optlist { position: absolute; top : 100%; left : 0; } .select .optlist.hidden { max-height: 0; visibility: hidden; } /* ------------ */ /* fanc...
... 100px */ border : 0.2em solid #000; /* 2px */ border-radius : 0.4em; /* 4px */ box-shadow : 0 0.1em 0.2em rgba(0,0,0,.45); /* 0 1px 2px */ background : #f0f0f0; background : -webkit-linear-gradient(90deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); background : linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display : inline-block; width : 100%; overflow : hidden; white-space : nowrap; text-overflow : ellipsis; vertical-align: top; } .select:after { content : "▼"; position: absolute; z-index : 1; height : 100%; width : 2em; /* 20px */ top : 0; right : 0; padding-top : .1em; -moz-box-sizing : border-box; box-sizing : border-box; text-align : center; border-left : .2em solid #000; border-radius: 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 js html content <form class="no-widget"> <select name="m...
... <span class="value">cherry</span> <ul class="optlist hidden"> <li class="option">cherry</li> <li class="option">lemon</li> <li class="option">banana</li> <li class="option">strawberry</li> <li class="option">apple</li> </ul> </div> <form> css content .widget select, .no-widget .select { position : absolute; left : -5000em; height : 0; overflow : hidden; } result for no js ...
Test your skills: Basic controls - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. basic controls 1 this task starts you off nice and gently by asking you to create two <input> elements, for a user's id and password, along with a submit button. ...
...c controls 1 this task starts you off nice and gently by asking you to create two <input> elements, for a user's id and password, along with a submit button. create appropriate inputs for user id and password. you should also associate them with their text labels semantically. create a submit button inside the remaining list item, with button text of "log in". 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. basic controls 2 the next task requires you to create working sets of checkboxes and radio buttons, from the provided text labels. turn the first <fieldset>'s contents into a set of radio buttons — you should only be able to select one pony character at once. ...
...boxes and radio buttons, from the provided text labels. turn the first <fieldset>'s contents into a set of radio buttons — you should only be able to select one pony character at once. make it so that the first radio button is selected upon page load. turn the second <fieldset>'s content into a set of checkboxes. add a couple more hotdog choices of your own. ...
...ad. turn the second <fieldset>'s content into a set of checkboxes. add a couple more hotdog choices of your own. 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. basic controls 3 the final task in this set requires you to create a file picker. create a basic file picker. allow the user to pick multiple files at once. allow the file picker to accept jpg and png images only. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed,...
Test your skills: Other controls - Learn web development
this aim of this skill test is to assess whether you've understood our other form controls article. note: you can try out solutions in the interactive 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. other controls 1 in our first "other controls" assessment, we'll get you to create a multi-line text input. create a basic multi-line text input. associate it semantically with the provided "comment" label. ...
...the bottom of this page. other controls 1 in our first "other controls" assessment, we'll get you to create a multi-line text input. create a basic multi-line text input. associate it semantically with the provided "comment" label. give the input 35 columns, and 10 rows of space in which to add comments. give the comments a maximum length of 100 characters. 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. other controls 2 now it's time to have a go at implementing a drop-down select menu, to allow a user to pick their favourite food from the choices provided. create your basic select box structure. associate it semantically with the provided "comment" label. in...
... other controls 3 in our final task of this set, we start with much the same list of food choices. ...
...s differently: create a basic text input that is semantically associated with the provided label. put the food choices into a list that can be associated with a form input. associate the list with your text input, so that when you type characters, any of the list options that match the character sequence are given in a dropdown list as autocomplete suggestions. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can...
Web forms — Working with user data - Learn web development
this module provides a series of articles that will help you master the essentials of web forms. web forms are a very powerful tool for interacting with users — most commonly they are used for collecting data from users, or allowing them to control a user interface. however, for historical and technical reasons it's not always obvious how to use them to their full potential. in the articles listed below, we'll cover all the essential aspects of web forms including marking up their html structure, styling form controls, validating form data, and submitting data to the server. 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, ...
...es easy to understand, and also be able to make use of our basic native form controls guide. mastering forms however requires more than just html knowledge — you also need to learn some specific techniques to style form controls, and some scripting knowledge is required to handle things like validation and creating custom form controls. therefore, before you look at the other sections listed below we'd recommend that you go away and learn some css and javascript first. the above text is a good indicator as to why we've put web forms into its own standalone module, rather than trying to mix bits of it into the html, css, and javascript topic areas — form elements are more complex than most other html elements, and they also require a close marriage of related css and javascript technique...
...trated when trying to use our apps. form validation helps us achieve these goals — this article tells you what you need to know. sending form data 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. advanced articles the following articles aren't essential to the learning pathway, but they'll prove interesting and useful when you've mastered the above techniques and want to know more. how to build custom form controls you'll come across some cases where the native form widgets just don't provide what you need, e.g. because of styling or functionality. in such cases, you may need to build your own form widget out of ...
...se study. sending forms through javascript this article looks at ways to use a form to assemble an http request and send it via custom javascript, rather than standard form submission. it also looks at why you'd want to do this, and the implications of doing so. (see also using formdata objects.) css property compatibility table for form controls this last article provides a handy reference allowing you to look up what css properties are compatible with what form elements. ...
Add a hitmap on top of an image - Learn web development
links (perhaps styled with css) are preferable to image maps for several reasons: text links are lightweight, maintainable, often more seo-friendly, and support accessibility needs (e.g., screen readers, text-only browsers, translation services). how to insert an image map, 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) ill...
...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 least six values). coordinates are given in css pixels. in case of overlap, source order carries the day. href the url of the resource you’re linking to. you may leave this attribute blank if yo...
...of the upper-left and bottom-right corners. for a polygon, to provide the x/y coordinates of each corner (so, at least six values). coordinates are given in css pixels. in case of overlap, source order carries the day. href the url of the resource you’re linking to. you may leave this attribute blank if you don’t want the current area to link anywhere (say, if you’re making a hollow circle.) alt a mandatory attribute, telling people where the link goes or what it does. alt text only displays when the image is unavailable. please refer to our guidelines for writing accessible link text. you may write alt="" if the href attribute is blank and the entire image already has an alt attribute. <map name="example-map-1"> <area shape="circle" coords="200,250,25" href=...
...ire image already has an alt attribute. <map name="example-map-1"> <area shape="circle" coords="200,250,25" href="page-2.html" alt="circle example" /> <area shape="rect" coords="10, 5, 20, 15" href="page-3.html" alt="rectangle example" /> </map> step 3: make sure it works for everybody you aren’t done until you test image maps rigorously on many browsers and devices. try following links with your keyboard alone. try turning images off. if your image map is wider than about 240px, you’ll need to make further adjustments to make your website responsive. it's not enough to resize the image for small screens, because the coordinates stay the same and no longer match the image. if you must use image maps, you may want to look into matt stow's jquery plugin. alternatively...
Debugging HTML - Learn web development
amentals, and creating hyperlinks. objective: learn the basics of using debugging tools to find problems in html. debugging isn't scary when writing code of some kind, everything is usually fine, until that dreaded moment when an error occurs — you've done something wrong, so your code doesn't work — either not at all, or not quite how you wanted it to. for example, the following shows an error reported when trying to compile a simple program written in the rust language. here, the error message is relatively easy to understand — "unterminated double quote string". if you look at the listing, you can probably see how println!(hello, world!"); might logically be missing a double quote. however, error messages can quickly get more complicated and less easy to interpre...
...cause browsers parse it permissively, meaning that the page still displays even if there are syntax errors. browsers have built-in rules to state how to interpret incorrectly written markup, so you'll get something running, even if it is not what you expected. this, of course, can still be a problem! note: html is parsed permissively because when the web was first created, it was decided that allowing people to get their content published was more important than making sure the syntax was absolutely correct. the web would probably not be as popular as it is today, if it had been more strict from the very beginning. active learning: studying permissive code it's time to study the permissive nature of html code. first, download our debug-example demo and save it locally. this demo is de...
...k out what every error message means, don't worry about it — a good idea is to try fixing a few errors at a time. then try revalidating your html to show what errors are left. sometimes fixing an earlier error will also get rid of other error messages — several errors can often be caused by a single problem, in a domino effect. you will know when all your errors are fixed when you see the following banner in your output: summary so there we have it, an introduction to debugging html, which should give you some useful skills to count on when you start to debug css, javascript, and other types of code later on in your career. this also marks the end of the introduction to html module learning articles — now you can go on to testing yourself with our assessments: the first one is lin...
...nner in your output: summary so there we have it, an introduction to debugging html, which should give you some useful skills to count on when you start to debug css, javascript, and other types of code later on in your career. this also marks the end of the introduction to html module learning articles — now you can go on to testing yourself with our assessments: the first one is linked below. previous overview: introduction to html next in this module getting started with html what’s in the head? metadata in html html text fundamentals creating hyperlinks advanced text formatting document and website structure debugging html marking up a letter structuring a page of content ...
Document and website structure - Learn web development
dedicated tags that you can use to represent such sections, for example: header: <header>. navigation bar: <nav>. main content: <main>, with various content subsections represented by <article>, <section>, and <div> elements. sidebar: <aside>; often placed inside <main>. footer: <footer>. active learning: exploring the code for our example our example seen above is represented by the following code (you can also find the example in our github repository). we'd like you to look at the example above, and then look over the listing below to see what parts make up what section of the visual. <!doctype html> <html> <head> <meta charset="utf-8"> <title>my page title</title> <link href="https://fonts.googleapis.com/css?family=open+sans+condensed:300|sonsie+one" rel="stylesh...
... look at the example above, and then look over the listing below to see what parts make up what section of the visual. ...
...e non-semantic element, which you should only use if you can't think of a better semantic text element to wrap your content, or don't want to add any specific meaning. for example: <p>the king walked drunkenly back to his room at 01:00, the beer doing nothing to aid him as he staggered through the door <span class="editor-note">[editor's note: at this point in the play, the lights should be down low]</span>.</p> in this case, the editor's note is supposed to merely provide extra direction for the director of the play; it is not supposed to have extra semantic meaning. for sighted users, css would perhaps be used to distance the note slightly from the main text. <div> is a block level non-semantic element, which you should only use if you can't think of a better semantic block element to us...
...t common to every page) content you want to have on your website — write a big list down. next, try to sort all these content items into groups, to give you an idea of what parts might live together on different pages. this is very similar to a technique called card sorting. now try to sketch a rough sitemap — have a bubble for each page on your site, and draw lines to show the typical workflow between pages. the homepage will probably be in the center, and link to most if not all of the others; most of the pages in a small site should be available from the main navigation, although there are exceptions. you might also want to include notes about how things might be presented. active learning: create your own sitemap try carrying out the above exercise for a website of your own creat...
Test your skills: Links - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. links 1 in this task we want you to help fill in the links on our whales information page: the first link should be linked to a page called whales.html, which is in the same directory as the current page. ...
...ail is automatically filled in as "question about whales". note: the first link in the example has the target="_blank" attribute set on it, so that when you click on it, it opens the page in a new tab. this is not strictly best practice, but we've done it here so that the page doesn't open in the embedded <iframe>, getting rid of your example code in the process! try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. links 2 in this task we want you to fill in the four links so that they link to the appropriate places: the first link should link to an image called blue-whale.jpg, which is located in a directory called blue inside the current directory. the second link shoul...
...e current page. it has an id of bottom. note: the first three links in the example have the target="_blank" attribute set on them, so that when you click on them, they open the linked page in a new tab. this is not strictly best practice, but we've done it here so that the pages don't open in the embedded <iframe>, getting rid of your example code in the process! try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. links 3 the following links link to an info page about narwhals, a support email address, and a pdf factfile that is 4mb in size. in this task we want you to: take the existing paragraphs with poorly-written link text, and rewrite them so that they have good lin...
...ny links that need a warning added. note: the first and third links in the example have the target="_blank" attribute set on them, so that when you click on them, they open the linked page in a new tab. this is not strictly best practice, but we've done it here so that the pages don't open in the embedded <iframe>, getting rid of your example code in the process! try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can...
Test your skills: HTML images - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. html images 1 in this task we want you to embed a simple image of some blueberries into the page. you need to: add the path to the image to an appropriate attribute to embed it on the page. ...
...s in a folder inside the current folder called images. add some alternative text to an appropriate attribute to describe the image, for people that cannot see it. give the <img> element an appropriate width and height so that it displays at the correct aspect ratio, and enough space is left on the page to display it. the image's intrinsic size is 615 x 419 pixels. ...
...pdating 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. html images 2 in this task you already have a full-featured image, but we'd like you to add a tooltip that appears when the image is moused over. you should put some appropriate information into the tooltip. 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. html images 3 in this final task you are provided with both a full-featured image and some caption text. what you need to do here is add elements that will associate the image with the caption. ...
... assessment or further help you can practice these examples in the interactive editors above. ...
Mozilla splash page - Learn web development
look correct. project brief in this assessment we are presenting you with a mostly-finished mozilla splash page, which aims to say something nice and interesting about what mozilla stands for, and provide some links to further resources. unfortunately, no images or video have been added yet — this is your job! you need to add some media to make the page look nice and make more sense. the following subsections detail what you need to do: preparing images using your favourite image editor, create 400px wide and 120px wide versions of: firefox_logo-only_rgb.png firefox-addons.jpg mozilla-dinosaur-head.png call them something sensible, e.g. firefoxlogo400.png and firefoxlogo120.png. along with mdn.svg, these images will be your icons to link to further resources, inside the furthe...
...ote: you should optimise your jpg and png images to make them as small as possible, while still looking ok. tinypng.com is a great service for doing this easily. adding a logo to the header inside the <header> element, add an <img> element that will embed the small version of the firefox logo in the header. adding a video to the main article content just inside the <article> element (right below the opening tag), embed the youtube video found at https://www.youtube.com/watch?v=ojcncvb1olg, using the appropriate youtube tools to generate the code. the video should be 400px wide. adding responsive images to the further info links inside the <div> with the class of further-info you will find four <a> elements — each one linking to an interesting mozilla-related page. to complete this se...
... free solution), then from there you can test whether they are working properly using browser developer tools such as the firefox network monitor. an art directed red panda inside the <div> with the class of red-panda, we want to insert a <picture> element that serves the small portrait panda image if the viewport is 600px wide or less, and the large landscape image otherwise. ...
... write a post asking for assessment and/or help at the mdn discourse forum. add the "learning" tag to your post so we are able to more easily find it. your post should include: a descriptive title such as "assessment wanted for mozilla splash page". ...
Test your skills: Multimedia and embedding - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...simple audio file onto the page. you need to: add the path to the audio file to an appropriate attribute to embed it on the page. the audio is called audio.mp3, and it is in a folder inside the current folder called media. add an attribute to make browsers display some default controls. add some appropriate fallback text for browsers that don't support <audio>. 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. multimedia and embedding 2 in this task we want you to mark up a slightly more complex video player, with multiple sources, subtitles, and other features besides. you need to: add an attribute to make browsers display some default controls. add some appropriate...
...hoice of which one to download ahead of time. give the <video> a width and height equal to its intrinsic size (320 by 240 pixels). make the video muted by default. display the text tracks contained in the media folder, in a file called subtitles_en.vtt, when the video is playing. you must explicitly set the type as subtitles, and the subtitle language to english. 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. multimedia and embedding 3 for this final task you have two tasks to do: embed a pdf into the page. the pdf is called mypdf.pdf, and is contained in the media folder. go to a sharing site like youtube or google maps, and embed a video or other media item into t...
...ownload the starting point for this task to work in your own editor or in an online editor. multimedia and embedding 3 for this final task you have two tasks to do: embed a pdf into the page. the pdf is called mypdf.pdf, and is contained in the media folder. go to a sharing site like youtube or google maps, and embed a video or other media item into the page. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can...
Client-side web APIs - Learn web development
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. provide apis allowing 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...
...t 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 explains the very basics of how these work. ...
...r embedding rich media in documents — <video> and <audio> — which in turn come with their own apis for controlling playback, seeking, etc. this article shows you how to do common tasks such as creating custom playback controls. client-side storage modern web browsers feature a number of different technologies that allow you to store data related to web sites and retrieve it when necessary allowing you to persist data long term, save sites offline, and more. this article explains the very basics of how these work. ...
Silly story generator - Learn web development
l free to put it inline in a <script> element inside the html page. 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 you have been provided with some raw html/css and a few text strings and javascript functions; you need to write the necessary javascript to turn this into a working program, which does the following: generates a silly story when the "generate random story" button is pressed. replaces the default name "bob" in the story with a custom name, only if a custom name is entered into the "enter custom name" text field before the generate button is pressed. converts the default us weight and temperature quantities and units in the story into uk equivalents if the uk radio button is checked be...
...h a custom name, only if a custom name is entered into the "enter custom name" text field before the generate button is pressed. converts the default us weight and temperature quantities and units in the story into uk equivalents if the uk radio button is checked before the generate button is pressed. will generate another random silly story if you press the button again (and again...) the following screenshot shows an example of what the finished program should output: to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do. basic setup: create a new file called main.js, in the same directory as your index.html file. apply the external javascript file to your html by ...
... variable. in this block we are saying "if a value has been entered into the customname text input, replace bob in the story with that custom name." inside the second if block, we are checking to see if the uk radio button has been selected. if so, we want to convert the weight and temperature values in the story from pounds and fahrenheit into stones and centigrade. what you need to do is as follows: look up the formulae for converting pounds to stone, and fahrenheit to centigrade. inside the line that defines the weight variable, replace 300 with a calculation that converts 300 pounds into stones. concatenate ' stone' onto the end of the result of the overall math.round() call. inside the line that defines the temperature variable, replace 94 with a calculation that converts 94...
... paragraph) equal to newstory. hints and tips you don't need to edit the html in any way, except to apply the javascript to your html. if you are unsure whether the javascript is applied to your html properly, try removing everything else from the javascript file temporarily, adding in a simple bit of javascript that you know will create an obvious effect, then saving and refreshing. the following for example turns the background of the <html> element red — so the entire browser window should go red if the javascript is applied properly: document.queryselector('html').style.backgroundcolor = 'red'; math.round() is a built-in javascript method that simply rounds the result of a calculation to the nearest whole number. there are three instances of strings that need to be replaced.
Test your skills: Arrays - Learn web development
this aim of this skill test is to assess whether you've understood our arrays article. note: you can try out solutions in the interactive 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. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). arrays 1 let's start off with some basic array practice. in this task we'd like you to create an array of three items, stored inside a variable calle...
... start off with some basic array practice. in this task we'd like you to create an array of three items, stored inside a variable called myarray. the items can be anything you want — how about your favourite foods or bands? next, modify the first two items in the array using simple bracket notation and assignment. then add a new item to the beginning of the array. 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. arrays 2 now let's move on to another task. here you are provided with a string to work with. we'd like you to: convert the string into an array, removing the + characters in the process. save the result in a variable called myarray. store the length of the arr...
... arrays 2 now let's move on to another task. here you are provided with a string to work with. we'd like you to: convert the string into an array, removing the + characters in the process. save the result in a variable called myarray. store the length of the array in a variable called arraylength. store the last item in the array in a variable called lastitem. 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. arrays 3 for this final array task, we provide you with a starting array, and you will work in somewhat the opposite direction. you need to: remove the last item in the array. add two new names to the end of the array. go over each item in the array and add it...
...he array. add two new names to the end of the array. go over each item in the array and add its index number after the name inside parentheses, for example ryu (0). note that we don't teach how to do this in the arrays article, so you'll have to do some research. finally, join the array items together in a single string called mystring, with a separator of " - ". try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can...
Test your skills: variables - Learn web development
this aim of this skill test is to assess whether you've understood our storing the information you need — variables article. note: you can try out solutions in the interactive 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. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). variables 1 in this task we want you to: declare a variable called myname. initialize myname with a suitabl...
... answer (or into the browser's javascript console, in the case of the downloadable version). variables 1 in this task we want you to: declare a variable called myname. initialize myname with a suitable value, on a separate line (you can use your actual name, or something else). declare a variable called myage and initialize it with a value, on the same line. ...
... variables 3 the final task for now — in this case you are provided with some existing code, which has two errors present in it. ...
...t for this task to work in your own editor or in an online editor. variables 3 the final task for now — in this case you are provided with some existing code, which has two errors present in it. the results panel should be outputting the name chris, and a statement about how old chris will be in 20 years' time. how can you fix the problem and correct the output? try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can...
Test your skills: Object-oriented JavaScript - Learn web development
the aim of this skill test is to assess whether you've understood our object-oriented javascript for beginners, object prototypes, and inheritance in javascript articles. note: you can try out solutions in the interactive 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. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). oojs 1 in this task we provide you with a constructor. we want yo...
...pe class called square. give it a name of square and a sidelength of 5. call your calcperimeter() method on the instance, to see whether it logs the calculation result to the browser devtools' console as expected. create a new instance of shape called triangle, with a name of triangle and a sidelength of 3. call triangle.calcperimeter() to check that it works ok. 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. oojs 2 next up we want you to take the shape class you saw in task #1 (including the calcperimeter() method) and recreate it using es class syntax instead. test that it works by creating the square and triangle object instances as before (using new shape() for bot...
...o work in your own editor or in an online editor. oojs 2 next up we want you to take the shape class you saw in task #1 (including the calcperimeter() method) and recreate it using es class syntax instead. test that it works by creating the square and triangle object instances as before (using new shape() for both), and then calling their calcperimeter() methods. 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. oojs 3 finally, we'd like you to start with the es shape class you created in the last task. we'd like you to create a square class that inherits from shape, and adds a calcarea() method that calculates the square's area. also set up the constructor so that the na...
...square object instances is automatically set to square, and the sides property is automatically set to 4. when invoking the constructor, you should therefore just need to provide the sidelength property. create an instance of the square class called square with appropriate property values, and call its calcperimeter() and calcarea() methods to show that it works ok. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can...
CSS performance optimization - Learn web development
previous overview: performance next painting an unstyled page, and then repainting it once styles are parsed would be bad user experience. for this reason, css is render blocking, 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 med...
...y needs to apply it for a specific scenario, it still downloads the stylesheet, but doesn't render block. by separating out the css into multiple files, the main render-blocking file, in this case styles.css, is much smaller, reducing the time that rendering is blocked. animating on the gpu browsers are optimized to handle css animations, and handle animating properties that do not trigger a reflow (and therefore also a repaint) very well. to improve performance, the node being animated can be moved off the main thread and onto the gpu. properties that will lead to compositing include 3d transforms (transform: translatez(), rotate3d(), etc.), animating transform and opacity, position: fixed, will-change, and filter. some elements, including <video>, <canvas> and <iframe>, are also on their ...
...ch properties of an element are expected to change enabling browsers to set up optimizations before the element is actually changed, improving performance by doing potentially expensive work before it is required. will-change: opacity, transform; the font-display property applied to the @font-face rule, the font-display property defines how font files are loaded and displayed by the browser, allowing text to appear with a fallback font while a font loads, or fails to load. this improves performance by making the text visible instead of having a blank screen, with a trade-off being a flash of unstyled text. @font-face { font-family: somefont; src: url(/path/to/fonts/somefont.woff) format('woff'); font-weight: 400; font-style: normal; font-display: fallback; } the contain propert...
...back font while a font loads, or fails to load. this improves performance by making the text visible instead of having a blank screen, with a trade-off being a flash of unstyled text. @font-face { font-family: somefont; src: url(/path/to/fonts/somefont.woff) format('woff'); font-weight: 400; font-style: normal; font-display: fallback; } the contain property the contain css property allows an author to indicate that an element and its contents are, as much as possible, independent of the rest of the document tree. this allows the browser to recalculate layout, style, paint, size, or any combination of them for a limited area of the dom and not the entire page. conclusion previous overview: performance next in this module the "why" of web performance what is web perf...
The "why" of web performance - Learn web development
overview: performance next web performance is all about making websites fast, including making slow processes seem fast. this article provides an introduction into why web performance is important to site visitors and for your business 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 b...
...at the time of this writing had over 400 http requests with a file size of over 22.6mb. imagine loading this on a desktop computer connected to a fibre optic network. this would seem relatively fast, and the file size would be largely irrelevant. imagine loading that same site using tethered mobile data on a 9 year-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 ...
...purchase, reading an article, or subscribing to a newsletter. the action being measured as the conversion rate depends on the website's business goals. performance impacts conversion; improving web performance improves conversion. site visitors expect a site to load in two seconds or less; sometimes even less on mobile (where it generally takes longer). these same site visitors begin abandoning slow sites at 3 seconds. the speed at which a site loads is one factor. if the site is slow to react to user interaction, or appears janky, this causes site visitors to lose interest and trust. here's some real-world examples of performance improvements: tokopedia reduced render time from 14s to 2s for 3g connections and saw a 19% increase in visitors, 35% increase in total sessions, 7% increa...
...s and video. the decisions you make and the tools you choose as you build your site can greatly affect the performance of the finished work. good performance is an asset. bad performance is a liability. site speed directly affects bounce rates, conversion, revenue, user satisfaction, and search engine ranking. performant sites have been shown to increase visitor retention and user satisfaction. slow content has been shown to lead to site abandonment, with some visitors leaving to never return. reducing the amount of data that passes between the client and the server lowers the costs to all parties. reducing html/css/javascript and media file sizes reduces both the time to load and a site's power consumption (see performance budgets). tracking performance is important. multiple factors, incl...
Web performance - Learn web development
h as: introduction to html css first steps javascript first steps once you've worked through this module, you'll probably be excited to go deeper into web performance — you can find a lot of further teachings in our main mdn web performance section, including overviews of performance apis, testing and analysis tools, and performance bottleneck gotchas. guides this topic contains the following guides. the following is a suggested order for working through them; you should definitely start with the first one. the "why" of web performance this article discusses why web performance is important for accessibility, user experience and your business goals. what is web performance? you know web performance is important, but what is constitutes web performance? this article introduces...
...her 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. ...
...e, 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 density is possible. in this article we discuss the impact images have on performance, and the methods to reduce the number of bytes sent per image. multimedia: video the lowest hanging fruit of web performance is often media optimization. in th...
...this article outlines some javascript best practices that should be considered to ensure even complex content is as performant as possible. ...
Ember resources and troubleshooting - Learn web development
chat server where you can meet the ember community, ask for help, and help others! general troubleshooting, gotchas, and misconceptions this is nowhere near an extensive list, but it is a list of things that came up around the time of writing (latest update, may 2020). how do i debug what's going on in the framework? for framework-specific things, there is the ember-inspector add-on, which allows inspection of: routes & controllers components services promises data (i.e: from a remote api — from ember-data, by default) deprecation information render performance for general javascript debugging, check out our guides on javascript debugging as well as interacting with the browser's other debugging tools. in any default ember project, there will be two main javascript ...
... 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 more common and easier-to-reason-about one-wa...
...nsistent 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 more common and easier-to-reason-about one-way bound data flow. ...
... 2017: secrets of the glimmer vm what is the state of the mut helper? ...
Using Vue computed properties - Learn web development
ion is to use vue’s computed properties. computed properties work similarly to methods, but only re-run when one of their dependencies changes. in our case, this would only re-run when the todoitems array changes. to create a computed property, we need to add a computed property to our component object, much like the methods property we've used previously. adding a summary counter add the following code to your app component object, below the methods property. the list summary method will get the number of finished todoitems, and return a string reporting this. computed: { listsummary() { const numberfinisheditems = this.todoitems.filter(item =>item.done).length return `${numberfinisheditems} out of ${this.todoitems.length} items completed` } } now we can add {{listsummary}...
... return `${numberfinisheditems} out of ${this.todoitems.length} items completed` } } now we can add {{listsummary}} directly to our template; we'll add this inside an <h2> element, just above our <ul>. we'll also add an id and an aria-labelledby attribute to assign the <h2> contents to be a label for the <ul> element. ...
...@change event handler to each checkbox instead of using v-model. update the <input> element in todoitem.vue to look like this. <input type="checkbox" class="checkbox" :id="id" :checked="isdone" @change="$emit('checkbox-changed')" /> since all we need to do is emit that the checkbox was checked, we can include the $emit() inline. in app.vue, add a new method called updatedonestatus(), below your addtodo() method. this method should take one parameter: the todo item id. we want to find the item with the matching id and update its done status to be the opposite of its current status: updatedonestatus(todoid) { const todotoupdate = this.todoitems.find(item => item.id === todoid) todotoupdate.done = !todotoupdate.done } we want to run this method whenever a todoitem emits a checkb...
...h the matching id and update its done status to be the opposite of its current status: updatedonestatus(todoid) { const todotoupdate = this.todoitems.find(item => item.id === todoid) todotoupdate.done = !todotoupdate.done } we want to run this method whenever a todoitem emits a checkbox-changed event, and pass in its item.id as the parameter. update your <to-do-item></to-do-item> call as follows: <to-do-item :label="item.label" :done="item.done" :id="item.id" @checkbox-changed="updatedonestatus(item.id)"> </to-do-item> now if you check a todoitem, you should see the summary update appropriately! summary in this article we've used a computed property to add a nice little feature to our app. we do however have bigger fish to fry — in the next article we will look at co...
Focus management with Vue refs - Learn web development
previous overview: client-side javascript frameworks next we are nearly done with vue. the last bit of functionality to look at is focus management, or put another way, how we can improve our app's keyboard accessibility. we'll look at using vue refs to handle this — an advanced feature that allows you to have direct access to the underlying dom nodes below the virtual dom, or direct access from one component to the internal dom structure of a child component. 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 installatio...
...ns from all the way before elements are created and added to the vdom (mounted), until they are removed from the vdom (destroyed). vue lets you run methods at various stages of this lifecycle using lifecycle methods. this can be useful for things like data fetching, where you may need to get your data before your component renders, or after a property changes. the list of lifecycle methods are below, in the order that they fire. beforecreate() — runs before the instance of your component is created. data and events are not yet available. created() — runs after your component is initialized but before the component is added to the vdom. this is often where data fetching occurs. beforemount() — runs after your template is compiled, but before your component is rendered to the actual...
...he <h2> in app.vue — and it's associated with our list of to-do items. this makes it a reasonable place to move focus to when we delete a node. first, we need to add a ref to our list heading. we also need to add a tabindex="-1" to it — this makes the element programmatically focusable (i.e. it can be focused via javascript), when by default it is not. inside app.vue, update your <h2> as follows: <h2 id="list-summary" ref="listsummary" tabindex="-1">{{listsummary}}</h2> note: tabindex is a really powerful tool for handling certian accessibility problems. however, it should be used with caution. over-using tabindex="-1" can cause problems for all sorts of users, so only use it exactly where you need to. you should also almost never use tabindex > = 0, as it can cause problems for use...
...="listsummary" tabindex="-1">{{listsummary}}</h2> note: tabindex is a really powerful tool for handling certian accessibility problems. however, it should be used with caution. over-using tabindex="-1" can cause problems for all sorts of users, so only use it exactly where you need to. you should also almost never use tabindex > = 0, as it can cause problems for users since it can make the dom flow and the tab-order mismatch, and/or add non-interactive elements to the tab order. this can be confusing to users, especially those using screen readers and other 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 <h...
Chrome Worker Modules
ding 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. this defines a global value require(), that you may now use as follows: // import the module // (here, we import the core of os.file) let core = require("resource://gre/modules/osfile/osfile_shared_allthreads.jsm"); // we may now use module core. core.declareffi(...) note that, for the moment, require() only accepts absolute uris. if the your module uri ends with “.js”, you can omit the extension. creating modules creating a module is just as simple. a module ...
...the your module uri ends with “.js”, you can omit the extension. creating modules creating a module is just as simple. a module is a file, whose filename generally ends with either “.js” or “.jsm”, and designed to be opened through require(). any value you define in that file is private by default. ...
...s") 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 of an add-on). stack traces unfortunately, the module loader doesn’t play nicely with error stack traces. ...
...r on chrome manifests (if your code is part of an add-on). stack traces unfortunately, the module loader doesn’t play nicely with error stack traces. that is, the following will not show human-readable stacks: try { mymodule.foo(); } catch (ex) { log("exception raised at " + ex.filename) log("stack: " + ex.stack); } rather, you should use properties modulename and modulestack, as follows: try { mymodule.foo(); } catch (ex) { log("exception raised at " + ex.modulename) log("stack: " + ex.modulestack); } subtleties you shouldn’t mix both styles exports.foo = bar and module.exports = {foo: bar}. if you do, know that any call to module.exports will overwrite all calls to `exports.foo = bar. you should not modify exports or module.exports once your module initializa...
Mozilla accessibility architecture
a chance to review its data. also, msaa clients need to access the event accessibles using the unique child id we give it. when we get the child id back, we can recreate the hash key needed to retrieve the accessible. finally, because the msaa client gets the same accessible for the event and for tree traversal each time, it can do comparisons with its own internal data model. for example, this allows the msaa client to invalidate parts of its own cache or data model based on dom mutation events. three levels of the accessibility cache there are three levels in the accessibility cache: global cache of doc accessibles (gglobaldocaccessiblecache), used to get the accessible for any document. per-document cache of accessibles a cache in each nsdocaccessible (maccessnodecache), containing a...
...h document. member variables in nsaccessible that keep track of the number of children (maccchildcount), the parent (mparent), the first child (mfirstchild) and the next sibling (mnextsibling). if mnextsibling equals the magic value dead_end_accessible (void*)1, then there are known to be no more siblings. if mnextsiblings == nsnull, then there could still be more siblings. this architecture allows us to quickly wipe away an entire document's worth of cached nodes when a document goes away, simply by destroying the document accessible's cache. however, it takes two steps to get a dom node's cached accessible. we must first get the document accessible from the global cache for the node's document, and then use that document accessible's specific cache to check for an entry for the dom node.
...ent, and then use that document accessible's specific cache to check for an entry for the dom node. this is not much of a problem because it is still much faster than creating a new accessible every time. this two step process is implemented in nsaccessibilityservice::getcachedaccessible(domnode). the member variables keeping track of the number of children, parent, first child and next sibling allow us to have instant traversal around accessible nodes that have already been visited. role of nsaccessnode if you work mostly in the atk sections of our accessibility module, you may wonder what the purpose of nsaccessnode is -- there are no atk interfaces that use it. in fact, it exists because of our isimpledomnode extension to msaa, which we implement on nsaccessnodewrap. isimpledomnode is us...
... exists because of 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 ...
Multiprocess on Windows
wn 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 code lives in the mscom library, located in the tree at /ipc/mscom. its headers are exported ...
... same language features which were supported by vb at that time. given those two options, it may seem that oicf is the preferred format. however, for various reasons, our com interceptor currently only supports typelib metadata. in order for the interceptor to be able to work with our interfaces, we must do some additional work to compensate for typelib's weaknesses. the required steps are as follows: ensure that you generate typelibs for all of your com interfaces; ensure that those interfaces are registered; register any outparams that consist of arrays of interfaces. we will now further detail each of these items: generating typelibs for all com interfaces you first need to include a library statement in your idl. when midl processes your idl, it generates c code for building a p...
... 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 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 ...
...reference to be released on an mta thread. interceptortargetptr<t> no-op deleter: used to annotate pointers whose reference counts must never be touched. these pointers all use mozilla::uniqueptr under the hood. use the mozilla::mscom::to*uniqueptr functions in ipc/mscom/ptr.h to create new instances of these. there is also a mozilla::mscom::getter_addrefs() function that allows these pointers to receive outparams. simple example now you know about mainthreadhandoff::wrapinterface and about the smart pointers, you're ready to wrap an interface: accessible* myaccessible = ....; mozilla::mscom::stauniqueptr<iaccessible> acctowrap; myaccessible->getnativeinterface(mozilla::mscom::getter_addrefs(acctowrap)); mozilla::mscom::proxyuniqueptr<iaccessible> wrapped; hresult ...
Adding a new event
code. what type of event do you want? roughly, there are 3 types of event. first, you need to choose which type you need. a simple dom event which can be implemented with webidl and widgetevent or something. this type of event is useful if the event isn't handled by c++ code. a dom event which represents a native event like a user action such as keyboard or mouse input. this type of event allows c++ code to handle it easier. it's not a dom event. however, c++ code may need to dispatch an event to dom tree and handle it with c++ event handler. this is useful for widget notifying dom tree of something or retrieving something from dom tree. how to implement an internal event class if you're in case 1 (a simple dom event), you can skip this section. add event messages you need to ad...
...vents.h this header file should be used for defining input events from keyboard or ime and also other text edit related events like querying focused content information. touchevents.h this header file should be used for defining input events from touch devices. miscevents.h if the new event class isn't proper any header files above, you should use this. each event class should implement following methods manually. virtual internalfooevent* asfooevent() moz_override this method should just return this. this method is used for retrieving sub class pointer avoiding to use static_cast. virtual widgetevent* duplicate() const moz_override this method should create a new instance with copying its members except widget. for copying the members, this should use assignfooeventdata() with t...
...ed to be dispatch to content, the class should be able to cross process boundary. in such cases, you may need to add new paramtraits for the new event class in nsguieventipc.h. modify utility methods of widgetevent widgetevent class has some utility mehtods and all of them are implemented in widgeteventimple.cpp. e.g., if your event shouldn't cause dom event, you need to modify widgetevent::isallowedtodispatchdomevent(). if your event should be fired on focused node, you need to modify widgetevent::istargetedatfocusedcontent(). how to implement a dom event class if you're in the case 3 (non-dom events), you can skip this section. create webidl of the event write a dom event definition with webidl. it should be created under dom/webidl/. see webidl bindings for the detail. if your new...
...: true, detail: 5 }); you shouldn't define construnctor in it. create xpcom interface for the dom event if your event class should be accessible via xpcom interface, you should create a new nsidomfooevent interface in dom/interfaces/events/. however, in these days, this is not necessary. ...
What to do and what not to do in Bugzilla
it lists the requirements and the email to contact. if you need faster access to get canconfirm or editbugs, especially in order to triage bugs or to participate in a bug day, then you can ask in #bmo on irc, or you may create a bug requesting permissions. ...
...ity page in the bug description. before you have canconfirm, you can still do good triaging by leaving comments with useful information on the bug that will help to confirm it. the same is true for editbugs: 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 ne...
... triager. the decision to mark a bug wontfix is reserved for module owners or module peers. verifying bugs only resolved bugs can be verified. to verify a bug, you will need to be the bug reporter, assignee, qa_contact, or in the 'editbugs' permission group. you should verify a bug if it has been proven that the resolution of the bug was correct. when verifying a bug, you should remember the following: verifying duplicates is the easiest task, so start with that. note that in general it's impossible to verify a duplicate until the original has been resolved. verifying wontfix or invalid bugs is relatively easy if a developer or a trusted qa person has wontfixed or invalidated them. bugs that were invalidated or wontfixed by someone else must be verified by a module owner or module peer ...
...e critical severity. priority/target milestone as stated in the bugzilla etiquette, you must not change the target milestone and priority fields. these fields are reserved for the developers. this also applies to bugs with target milestones in the past. reassigning bugs if a bug belongs to a different product or component it should be reassigned. when performing bug reassignments, keep the following things in mind: always remember to check the reassign to default owner and qa contact radio button under the comment textbox. mozilla applications like the application suite, thunderbird, or firefox share most of their program code and all of the backend code including things like network connectivity (ftp, http, imap) and html rendering. make sure that you also test thunderbird or firefox...
Makefile - variables
es to remove. garbage_dirs a "clean target" macro containing a list of directories to remove. global_deps a list of common dependencies (makefile.in, autoconf.mk) that will force rebuilding. libobjs have_dtrace sun microsystem's dynamic tracing environment is available. local_includes allow use of moz_objdir in .mozconfig with older gnu gcc on beos. module module_name no_dist_install inhibit generating and copying exports/install targets into $(moz_objdir)/dist/install. .ns_printing objs obj_suffix filename suffix to use when writing object file...
... python_unit_tests list of python scripts to check exit status for make check xpc_shell_tests no_xpcshell_manifest_check inhibit validating manifest files when running xpcshell tests. compiler variable description gnu_cc define...
... exports a list of exported headers and source files for external use. has_extra_exports pref_js_exports javascript preferences file to export[1]. sdk_headers makefile generation description no_makefile_rule [pending] inhibit makefile.in deps that would allow $obj/makefile to be generated. no_submakefile_rule [pending/redundant?] inhibit makefile generation within subdirectories. no_ variable description no_profile_guided_optimize inhibit pgo builds no_dist_install note: values will be appended to the export variable when present. ...
... l10n.mk and localization variable description en_us_binary_url server url from which wget will ftp binaries. l10nbasedir moz_chrome_multilocale a list of locale names to process moz_chrome_file_format both, file, jar, omni, symlink packager_no_libs hack to allow one makefile to include another without pulling in libs:: target definitions. stagedist local staging directory for localization and packaging. todo: xpcom/xpinstall variables: https://developer.mozilla.org/en/adding_xpcom_components_to_mozilla_build_system ...
Old Thunderbird build
this page covers the basic steps needed to build a thunderbird up to version 59. for thunderbird 60 and later, see the new build instructions. for additional information, see the build documentation. hardware requirements at least 4 gb of ram. 8 gb or more is recommended. while you can build thunderbird on older hardware it can take quite a bit of time to compile on slower machines with less ram. good internet connection for the initial source download. build prerequisites depending on your operating system you will need to carry out a different process to prepare your machine. so firstly complete the instructions for your os and then continue following these build instructions. to build on windows, please read the prerequisites so you don't skip preparing the mapi headers n...
...e the unbundled folder's name is now "mozilla" and not "mozilla-central"). then run "python client.py checkout" to ensure you are up-to-date. the source code requires 3.6gb of free space or more and additionally 5gb or more for default build. build configuration to build thunderbird, you need to add a file named mozconfig to the root directory of the comm-central checkout that contains the following line: ac_add_options --enable-application=mail you can create a file with this line by doing this: cd comm-central echo 'ac_add_options --enable-application=mail' > mozconfig if you omit this line, the build system will build firefox instead. other build configuration options can be added to this file, although it's strongly recommended that you only use options that you fully understand.
.../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 --enable-calendar line to your mozconfi...
...there is not supported. check for @topsrcdir@ or relative paths in your mozconfig. those have caused several problems historically and tend to be poorly tested when the build system changes. if on windows you get link errors like "lnk1102: out of memory" or "lnk1318: unexpected pdb error; ok (0)", try deleting the largest .pdb files before rushing out the door to buy more ram. clobbering (see below) will also remove those files. try with a clean obj-dir. you can clean out previous build artefacts using ./mozilla/mach clobber references general build documentation comm-central using the mozilla symbol server ...
Gecko Logging
ing 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. note: log module names can only contain specific characters. the first character must be a lowercase or uppercase ascii char, underscore, dash, or dot. subsequent characters may be any of those, or an ascii digit. #include "mozilla/logging.h" static mozilla::lazylogmodule sfoolog("foo"); logging interface a basic interface is provided in the form of 2 macros and an enum class. mozilla lo...
...uld consider asserting in a debug build. warning 2 a warning often indicates an unexpected state. info 3 an informational message, often indicates the current program state. debug 4 a debug message, useful for debugging but too verbose to be turned on normally. verbose 5 a message that will be printed a lot, useful for debugging program flow and will probably impact performance. example usage code sample #include "mozilla/logging.h" using mozilla::loglevel; static mozilla::lazylogmodule slogger("example_logger"); static void dostuff() { moz_log(slogger, loglevel::info, ("doing stuff.")); int i = 0; int start = time::nowms(); moz_log(slogger, loglevel::debug, ("starting loop.")); while (i++ < 10) { moz_log(s...
...); } } enabling logging the log level for a module is controlled by setting an environment variable before launching the application. it can also be adjusted by setting prefs. by default all logging output is disabled. set moz_log="example_logger:3" in the windows command prompt (cmd.exe), don't use quotes: set moz_log=example_logger:3 if you want this on geckoview example, use the following adb command to launch process: adb shell am start -n org.mozilla.geckoview_example/.geckoviewactivity --es env0 "moz_log=example_logger:3" there are special module names to change logging behavior. you can specify one or more special module names without logging level. special module name append append new logs to existing log file. sync print each log s...
...rt rather than set. if you're only interested in the content process you can use rust_log_child rather than rust_log. the log crate lists the available log levels: log level purpose rust logging levels error designates very serious errors. warn designates hazardous situations. info designates useful information. debug designates lower priority information. trace designates very low priority, often extremely verbose, information. it is common for debug and trace to be disabled at compile time in release builds, so you may need a debug build if you want logs from those levels. check the env_logger docs for more details on logging options. child processes / e10s sometimes it can be useful to only log child...
Contributing to the Mozilla code base
please come and ask your questions in our chatroom, where we can help you get started. we know even before you start contributing 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. ...
...ocess: 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++ firefox developers documentation firefox (front-end) javascript and/or html/css firefox developers documentation devtools javascript and/o...
... document, https://developer.mozilla.org/docs/mozilla our reviewer checklist is very useful, if you have a patch near completion, and seek a favorable review utilize our build tool mach, its linting, static analysis, and other code checking features step 3: get your code reviewed once you fix the bug, you can advance to having your code reviewed. when you commit your code, please use the following format for your commit message: `bug number - what your patch does; r?reviewer` for example, a commit message may look like `bug 1234567 - remove reflow by caching element size. r?jsample` mozilla in most of the projects uses phabricator for code review. who is the right person to ask for a review? if you have a mentored bug: ask your mentor. they will help, or can easily find out. it mig...
...to ask for a review are there related bugs on similar topics? the reviewer in those bugs might be another good choice we have a list of modules, which lists peers and owners for the module. some of these will be good reviewers. in a worst case scenario, set the module owner as the reviewer, asking them in the comments to pick someone more suitable please select only one reviewer. step 4b: follow it up once you've asked for a review, a reviewer will often respond within a day or two, reviewing the patch, or saying when they will be able to review it, perhaps due to a backlog. if you don't hear back within this time, naturally reach out to them: add a comment to the bug saying 'review ping?', check the "need more information from" box, and add the reviewer's name. if they don't respond wi...
mach
m 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 directory is used. the default mozconfig search logic i...
...nt working directory, so you can run commands like mach build . to rebuild just the files in the current directory. for example: $ cd devtools/client $ mach build webconsole # rebuild only the files in the devtools/client/webconsole directory $ mach mochitest webconsole/test # run mochitests in devtools/client/webconsole/test enable tab completion to enable tab completion in bash, run the following command. you can add the command to your .profile so it will run automatically when you start the shell: source /path/to/mozilla-central/python/mach/bash-completion.sh this will enable tab completion of mach command names, and in the future it may complete flags and other arguments too. note: mach tab completion will not work when running mach in a source directory older than firefox 24. ...
...o be cryptic and not utterly helpful. that above bootstrap.py will download and setup everything so you can build a mozilla app such as firefox etcetera, so it is a nice starting point. why should i use mach? you should use mach because it provides a better and more unified developer experience for working on mozilla projects. ...
...mach fit into the modules system? mozilla operates with a modules governance system where there are different components with different owners. there is not currently a mach module. there may or may never be one. mach is just a generic tool. the mach core is the only thing that could fall under perview of a module and an owner. even if a mach module were established, mach command modules (see below) would likely never belong to it. instead, mach command modules are owned by the team/module that owns the system they interact with. in other words, mach is not a power play to consolidate authority for tooling. instead, it aims to expose that tooling through a common, shared interface. who do i contact for help or to report issues? you can ask questions in #build. can i use mach outside of m...
Performance
them. key points to keep in mind scripts registered during addon startup get executed during session restore. 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. the following examples omit some boilerplate code for the sake of brevity the "better" examples also omit some best practices and only demonstrate how to fix the problem described in their respective subtopics. performance best practices declaring stateless functions once per process bad: // addon.js services.mm.loadframescript("framescript.js", true) // framescript.js const precomputedconstants = ...
... as long as it the action does not happen frequently the memory and startup savings should outstrip the added cost of script evaluation. delaying the script registration until the session is restored my provide some middle ground for some addons. it does not provide the same memory footprint reductions but it improves application startup. ...
... better: instead of only keeping the state in the parent an addon can employ a master-slave architecture where the parent has the authoritative state and replicates it to the child processes in advan...
...=> r == true)) return ci.nsicontentpolicy.accept; return ci.nsicontentpolicy.reject_request; } }); // more boilerplate code here this example is a (somewhat condensed) content policy which gets triggered for every network request in a child process to either allow or deny the request. since the code calls to the parent process to check whether a specific request can be allowed it would slow down all page loads, as web pages generally issue dozens of requests. better: instead of only keeping the state in the parent an addon can employ a master-slave architecture where the parent has the authoritative state and replicates it to the child processes in advance so they can act based on their local copy. see the previous chapter on how to efficiently replicate addon sta...
mozbrowsercontextmenu
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: clientx the x value of the coordinate that was clicked inside the browser <iframe>'s viewport. clienty the y value of the coordinate that was clicked inside the browser <iframe>'s viewport. systemtargets an array containing one or more menusystem objects (see the menusystem object, below), containing details of the standard menu(s) that will be shown. for example, if the us...
... <iframe>'s viewport. systemtargets an array containing one or more menusystem objects (see the menusystem object, below), containing details of the standard menu(s) that will be shown. for example, if the user clicked on an image nested in an <a> tag, two menus are available — one with information related to the image, and one for the link. contextmenu a menu object (see the menu object, below) representing a custom menu defined via <menu> / <menuitem> elements and pointed to via a contextmenu attribute on the dom element clicked on, which contains the menu's id. contextmenuitemselected an anonymous function that fires when a menu item is selected. ...
... uri a domstring. in the case of an image or video context menu, this is the src of the image or video clicked on to get the context menu. in the case of an link context menu, it is the link's href. ...
...d a domstring representing the method of a form, in the case of a form context menu. name a domstring representing the name of a form, in the case of a form context menu. the menu object an object representing a custom menu defined via <menu> / <menuitem> elements and pointed to via a contextmenu attribute on the dom element clicked on, which contains the menu's id. its properties are as follows: type a domstring representing the type of context menu displayed. it can be menu (a full menu) or menuitem (a single menu item.) label a domstring equal to the label attribute of the dom node the context menu is accessed on. icon the menu item's icon, if the context menu being accessed is a menu item. id the menu item's id, if the context menu being accessed is a menu item. this is pa...
Embedding Tips
interface also has methods for reloading, stopping a load and going back and forward in the history. how do i block a load? implement the nsiwebprogresslistener interface and register it with the appropriate web browser object via the nsiwebbrowser::addwebbrowserlistener() method. use the callbacks for after-the-fact cancellation. alternatively, implement a nsiuricontentlistener as described below. how do i watch/intercept a load before it happens? implement the nsiuricontentlistener interface, and register it with the appropriate web browser object via the nsiwebbrowser::parenturicontentlistener attribute. watch for changes in nsiuricontentlistener::onstarturiopen(). you can abort the uri load at this point if you don't want it to proceed. if necessary you may also implement the nsiuri...
...sslistener object to listen for progress and state notifications. how do i save / upload a document / data to a web or ftp site? again, use the webbrowser persist object, but specify a remote location as the target uri. your web progress listener must also implement nsiauthprompt if you want to be able to upload to a password protected location (e.g. an ftp site). the nsiauthprompt interface allows the networking layer to pose a user / password prompt to obtain the values needed for authentication. your own implementation should pose this dialog, or fill in the values that are needed for the upload to succeed. how do i know when saving is done, monitor progress etc.? register your ownnsiwebprogresslistener object to listen for progress and state notifications. here is a simple example w...
...ogresslistener object to listen for progress and state notifications. here is a simple example which demonstrates the principle. the simplepersist() function takes a string url and a string file path. in response it creates a persist object, creates a listener and starts the operation. as the operation progresses, methods on the listener such as onstatechange, onprogresschange etc. are called, allowing the embedder to know what is happening. when the operation is completed, the onstatechange will be notified 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 | sta...
...s defined here. for an example, see browserimpl.cpp in mfcembed and its simple cbrowsertooltip class implemented in mfc. how do i disable drag/drop support? when setting up your browser add a hook to the command manager which points to your nsiwebbrowserchrome implementation. this implementation should also implement nsiclipboarddragdrophooks. deny the drop by setting the return value of the allowdrop() function. nscomptr<nsicommandmanager> commandmanager = do_getinterface(iwebbrowser); if (commandmanager) { nscomptr<nsidomwindow> thedomwindow = do_getinterface(iwebbrowser); nscomptr<nsicommandparams> cmdparamsobj = do_createinstance(ns_command_params_contractid,&rv); cmdparamsobj->setisupportsvalue("addhook", reinterpret_cast<nsisupports*>(ichromeimplementation)); commandmanager-...
How to Report a Hung Firefox
firefox is running but is not responding..." dialog? this usually means that something in firefox is hung. this may be because of a code error within firefox 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. what information to include in a bug report as usual, following bug writing guidelines will make your report much more likely to lead to a fix in firefox. check the cpu usage of the firefox process(es): is it idle, using 100% of a core (which may show up as 50%, 25% in your monitoring tool if you have a multi-core processor) or neither? (if you're experiencing high cpu usage and firefox eventually recovers from a hang, you should try the instruction...
... 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 repor...
...cing high cpu usage and firefox 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 ...
...ash me now! (simple) use the menu button to find the crash me icon and click the icon. 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 link. another way to trigger a crash in a hung tab is to run the following script in the browser console (opened after selecting the hung tab): let wm = cc["@mozilla.org/appshell/window-mediator;1"]. getservice(ci.nsiwindowmediator); let win = wm.getmostrecentwindow("navigator:browser"); let browser = win.gbrowser.selectedbrowser; if (browser.isremotebrowser) { browser.messagemanager.loadframescript('data:,let appinfo = components.classes["@mozilla.org/xr...
PBackground
a language used to define "protocols" — essentially formalized versions of how two things can communicate. it is similar in some respects to idl and webidl. at build time the ipdl compiler automatically generates a large amount of c++ glue code from the ipdl files. ipdl protocols are used to specify how the chrome and content processes talk to each other and verify that a content process is "following the rules". note: if you want more detailed information on ipdl, start out by reading the ipdl tutorial. when used at run time, every protocol has two actors — a parent and a child. these actors can live in different processes due to ipdl, which automatically serializes calls on one side and transmits them to the other. this is the foundation of how chrome and content processes talk to e...
... processes. for example, when we are uploading textures from the content process we don't need to go through the main thread of the parent process. instead we can go directly to the compositor thread in the parent process by creating a new top-level protocol that connects the compositor thread in the parent process to the main thread of a child process. this protocol is called pcompositor, and allows us to bypass the main thread of the parent process, which trims the latency of texture uploads since they will not get bogged down if that thread is busy. writing code that works in both chrome and content processes a lot of code "just works" in the content process. but some things, such as apis that need to manipulate files or device settings (e.g. geolocation) cannot run in the content proce...
...ult in dxr): if (xre_getprocesstype() == geckoprocesstype_default) { dothething(arguments); } else { mipdlprotocol->senddothething(arguments); } this can get unwieldy very quickly, so a better solution was needed. pbackground pbackground exists to solve such problems. it connects a designated "background" thread in the chrome process to any other thread in any other process. pbackground allows us to bypass the chrome process's main thread if used from the content process' main thread. bypass both main threads if used from a non-main thread in a content process write process-agnostic code because it can be used even from another thread in the parent process the parent side of a pbackground actor pair is always on the designated background thread, while the child side is on the t...
...ss both main threads if used from a non-main thread in a content process write process-agnostic code because it can be used even from another thread in the parent process the parent side of a pbackground actor pair is always on the designated background thread, while the child side is on the thread that chooses to use pbackground. the background thread is designed to be responsive (nobody is allowed to do long running computation or file i/o on it) to guarantee better latency than going through the main threads (which can run arbitrary js, gc, etc.) can provide. examples indexeddb was rebuilt on top of pbackground last year. this allows the dom code to generally not worry about what thread (main vs. worker) or process (single vs. multiple) it is running in. instead, it simply turns all o...
Downloads.jsm
edownload( object aproperties ); parameters aproperties provides the initial properties for the newly created download. this matches the serializable representation of a download object. some of the most common properties in this object include: source: string containing the uri for the download source. alternatively, may be an nsiuri, a downloadsource object, or an object with the following properties: url: string containing the uri for the download source. isprivate: optional indicates whether the download originated from a private window. if omitted, the download is public. referrer: optional string containing the referrer uri of the download source. can be omitted or null if no referrer should be sent or the download source is not http. target: string ...
...e download originated from a private window. if omitted, the download is public. referrer: optional string containing the referrer uri of the download source. can be omitted or null if no referrer should be sent or the download source is not http. target: string containing the path of the target file. alternatively, may be an nsifile, a downloadtarget object, or an object with the following properties: path: string containing the path of the target file. saver: optional string representing the class of the download operation. if omitted, defaults to "copy". alternatively, may be the serializable representation of a downloadsaver object. promise resolves to the newly created download object. fetch() downloads data from a remote network location to a local...
... aoptions ); parameters asource string containing the uri for the download source. alternatively, may be an nsiuri or a downloadsource object. atarget string containing the path of the target file. alternatively, may be an nsifile or a downloadtarget object. aoptions optional an optional object used to control the behavior of this function. you may pass an object with a subset of the following fields: isprivate: optional indicates whether the download originated from a private window. if omitted, the download is public. promise resolves to undefined when the download has finished successfully and you can access the target file. promise can be rejected with downloaderror if the download failed. getlist() retrieves the specified type of downloadlist object. there is one...
... yield download.finalize(true); } } finally { yield list.removeview(view); } }).then(null, components.utils.reporterror); conversion from nsidownloadmanager starting in firefox for desktop version 26, the nsidownloadmanager and nsidownload interfaces are not available anymore. the new module works differently from the old component. in general, you should be aware of the following highlights: there is no difference between active downloads and finished downloads. the download object can be used without requiring direct database access. observer notifications (for example, "dl-done") and download listeners are replaced by views on the downloadlist object returned by the getlist() method. object identity replaces the use of numeric identifiers. you can use download o...
JavaScript OS.Constants
getservice(components.interfaces.nsiosfileconstantsservice). init(); from a chrome worker no initialization is required. module os.constants is always available for chrome workers. ...
...cal 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 for interacting with libc. useful mostly for using js-ctypes to interact with the following platforms: macos x; android; linux; other variants of unix. os.constants.libc is available on all platforms, although some constants are not defined everywhere. before using a constant, you should check that it is defined. error values eacces permission denied eagain resource temporarily unavailable ebadf bad file descriptor eexist file...
...name too long enfile too many open files on the system enoent no such file or directory enomem cannot allocate memory enospc no space on device enotdir is not a directory enxio device no configured or does not support operation eopnotsupp (not always available under windows) operation not supported. eoverflow (not always available under windows) value too large to be stored in datatype. eperm operation not permitted erange result too large etimedout (not always available under windows) operation timed out. ewouldblock (not always available under windows) operation would block. exdev cross-device link opening files unix access ri...
...or appending. o_creat create the file if it does not exist yet. o_directory (linux only) succeed only of the file is a directory. o_evtonly descriptor requested for event notifications only. o_excl raise an error if o_creat is set and the file exists. o_exlock atomically obtain an exclusive lock. o_largefile o_nofollow do not follow symbolic links. o_nonblock do not block on open or for data to become available. o_rdonly open the file for read only. o_rdwr open the file for read and write. o_rsync o_shlock atomically obtain a shared lock. o_symlink allow opening of symbolic links. o_sync (linux only) open for purely synchro...
Using JavaScript code modules
have a chrome.manifest with a content instruction in it, you can put the code module in your content folder and reference it like your other content files via chrome://<yourextension>/content/<yourmodule>.jsm. if your extension or application needs to support mozilla 1.9.x (firefox 3.x), you should register a new resource url. details on doing this are in the "extending resource: urls" section below. sharing objects using code modules an extremely important behavior of components.utils.import() is that modules are cached when loaded and subsequent imports do not reload a new version of the module, but instead use the previously cached version. this means that a given module will be shared when imported multiple times. any modifications to data, objects, or functions will be available in a...
...le.jsm"); alert(bar); // displays "[object object]" the main effect of the by-value copy is that global variables of simple types won't be shared across scopes. always put variables in a wrapper class and export the wrapper (such as bar in the above example). unloading code modules requires gecko 7.0(firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) components.utils.unload() allows you to unload a previously imported code module. once this method has been called, references to the module will continue to work but any subsequent import of the module will reload it and give a new reference. examples a template to download and edit is seen here on github - gists - _template-bootstrapjsm.xpi extending resource: urls prior to gecko 2.0, the most common way to load code m...
...called, references to the module will continue to work but any subsequent import of the module will reload it and give a new reference. examples a template to download and edit is seen here on github - gists - _template-bootstrapjsm.xpi extending resource: urls prior to gecko 2.0, the most common way to load code modules was using resource: urls. the basic syntax of a resource url is as follows: resource://<alias>/<relative-path>/<file.js|jsm> the <alias> is an alias to a location, usually a physical location relative to the application or xul runtime. there are multiple pre-defined aliases set up by the xul runtime: app - alias to the location of the xul application gre - alias to the location of the xul runtime the <relative-path> can be multiple levels deep and is always re...
...se in which it's remotely useful: a firefox 4-only add-on which must be installed unpacked. otherwise placing code modules in a jar file breaks compatibility unnecessarily. importing commonjs modules the javascript code modules described here are not the same thing as commonjs modules, but you can import commonjs modules into any scope where you can use components.utils.import. just call the following: const { require } = cu.import("resource://gre/modules/commonjs/toolkit/require.js", {}) this will import require() into your scope. you can then use that to import commonjs modules. you can import add-on sdk modules in just the same way you could from an sdk add-on: // import the sdk's base64 module var base64 = require("sdk/base64"); base64.encode("hello"); // "agvsbg8=" you can import...
Localizing with Pontoon
here we'll discuss how to use pontoon to localize projects, from first sign-in to finalizing your contributions. ...
...pontoon's home page is very easy to use. to begin localizing the project, click on the persona icon and sign in. next, simply select the project you want to work on and your locale from the dropdown menus. pontoon will automatically open that locale's project for you to get started. note that for our purposes here, we'll be using firefox affiliates website to demo pontoon's functionality and workflow. and there it is, opened inside pontoon: main toolbar as you can see, most of the interface is taken by the website being translated. only the toolbar on top belongs to pontoon, containing the following items (from left to right): list of strings opens a sidebar with a list of all strings to localize. project selector (affiliates) switches between projects to localize. resource selec...
...homepage) switches between project resources to localize, like subpages or localization files. hidden if no resources available for project. locale selector (slovenian) switches between languages to localize. go opens project-resource-locale selection. progress indicator displays your progress on the resource being localized. more details are available in the popup. user menu allows for user-specific tasks, like commiting to repository, downloading files and signing out. info menu gives important information, like the anticipated project timeline and a list of keyboard shortcuts. alright, how about we do some translating now? translate strings when using pontoon for localization, you have a couple of options to translate your strings. you can translate in-contex...
...es or different plural forms. by clicking on the hamburger icon in the main toolbar, a list of all strings and available translations will open in the sidebar. you can also use the sidebar for out-of-context localization: click on the string you'd like to translate. translation panel with original string and its details (e.g. comments) opens. translate the string in the translation area below. click the save button to save your translation. as you translate strings out-of-context, translations will also appear in website, if they could also be translated in-context. translation helpers as you can see, suggestions from history, translation memory, machine translation and other locales are also available in the out-of-context translation panel. we call all of these translation hel...
Release phase
for more information on the release part of the l10n process, visit the mozilla wiki here. your official release repository now that your locale has been registered, the localization files will live on mozilla mercurial server at hg.mozilla.org. depending on which branch you work on, the url of your repository might look like this: http://hg.mozilla.org/releases/l10n-central/x-testing if you followed the koala or plain text approach, you probably already have a local clone of the repository. otherwise, in order to be able to make any changes to the localization files, you will need to clone the repository on your local machine and work in the local clone. there are two different protocols you can use to connet with your mercurial repository: http and ssh. be advised that there's an importan...
...ugh ssh. consequently, if you already have a local clone that you pulled using http, you'll need to modify a config file to tell mercurial to push through ssh. let's go over configuring your connection protocols. configuration before you try pushing, you need to tell ssh which username you wish to use for connecting with hg.mozilla.org. this should be your mozilla ldap account name. ...
...s! your changeset has been successfully pushed to hg.mozilla.org! you can now visit http://hg.mozilla.org/releases/l10n-central/x-testing in your browser to see the new changeset in the remote repository. troubleshooting ssh if pushing fails, make sure your ~/.ssh/config has the correct user set under the hg.mozilla.org host. this should be your mozilla ldap account name. next, try issuing the following command: $ ssh hg.mozilla.org if ssh is working fine, you should see the following message: no interactive shells allowed here! connection to hg.mozilla.org closed. if you don't see this message, try running the same command in a more verbose mode (with the debugging information): $ ssh -vvv hg.mozilla.org this should tell you why your connection is not succeeding. if you can't figure it out ...
...ered and the previously approved release revision. focus is still on technical accuracy and completion of l10n work; not translation quality. release revisions are evaluated, not entire l10n repos. sign-offs do not need to be approved before revision merge between release channels, although it is recommended. there is a specific process to follow in bugzilla for requesting these reviews: file a bug requesting the review. attach your files to the bug. once attached, open the attachment details. in the attachment details, select the ? from the dropdown menu next to the review flag or the appropriate approval flags (see image). this will display a text box to assign the review to someone. enter :pike as the requestee. we will perfo...
SVN for Localizers
first things first, we need to give you a brief introduction to what svn is and where you can find the necessary tools to get started. if you're already familiar with this information, skip ahead to mozilla's svn repositories. brief intro to svn svn (abbreviation for subversion) is a free and open source repository tool we use to manage the localized mozilla web pages. it's a handy tool that allows us to grab, change, and store versions of source files in one location. you should know that when we say svn we are referring to either the svn server and the svn client. this may seem confusing, but don't fret because we'll make sure to differentiate between the two here: svn server: this is installed on one of mozilla's servers that we use to manage our localizable web system. svn client: ...
...s of the terms staging and production) to refer to testing and publicly visible websites, respectively. working with svn now that you understand the mozilla svn repository layout (in particular the layout for mozilla.com), let's get some files into your hands to start localizing! the first thing you need to do is copy the mozilla repository you want to work on to your computer. enter the following command in your command-line tool: svn checkout https://svn.mozilla.org/projects/mozilla.com/trunk/locales/[your locale code] mozilla-l10n-[your-localecode] this command creates the mozilla-l10n-[your-localecode] directory on your computer and copies into it all of the files from https://svn.mozilla.org/projects/moz...om/trunk/locales/[your locale code]. note: the directory you create wil...
...ut/file.diff to save the output to 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. wit...
...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 important for you to update your working copy with the newest files from mozilla svn repository before you start making changes. enter the following command from the command-line: svn update your local svn repository (i.e., working directory) will be updated with the newest files from the url you initially cloned your repository from. it's very important that you do this often. as a general rule, you should at least do it before translating anything. sometimes mistakes happen and you need to start over. go back to the root of your w...
Mozilla Quirks Mode Behavior
miscellaneous & style all of the style rules in layout/style/res/quirk.css apply only in quirks mode: orphaned li has an inside bullet (bug 1049). add padding if the very first node in an li is another ul or ol (bug 98636). obsolete since gecko 50 list bullets do not inherit the font size of the list (bug 97351). removed in firefox 50 (bug 648331). don't inherit font properties into tables except for font-family. make table borders gray rather than using the foreground color. collapse top margin of body and td and bottom margin of td. collapse the bottom or top margins of empty elements (bug 97361). ...
...an advisory mime type of text/css will still be treated as css even if the server gives a content-type header other than text/css. the css parser accepts colors not beginning with #, except in shorthands. the css parser interprets unitless numbers as px (except for line-height and any other properties where they have distinct meaning, and except in shorthands). in quirks mode, the css parser allows {} around the contents of style attributes (bug 99554). this behavior is being removed in firefox 27, for interoperability. (bug 915053) an empty string for the background attribute sets the background url to empty only in quirks mode. the topmargin, bottommargin, leftmargin, and rightmargin attributes on body are supported only in quirks mode (bug 9258). obsolete since gecko 35 (firefox 35.
...or 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. tables td, th, tr, thead, tbody, ...
...e are supported on table only in quirks mode (bug 41893). proposed to remove: bug 725646. in quirks mode, when tables have a border style of inset or outset, the border color is based on the background color of the table or of the nearest ancestor with non-transparent background. [this may have been an accurate description when written in june 2001, but it no longer appears correct. i don't follow the code in nscssrenderingborders well enough to tell, though.] in quirks mode a fixed width specified on a table cell resets the nowrap attribute. if the nowrap attribute is present the cell width will never be smaller than the specified fixed width (bug 277232). in quirks mode, tables with no rows/rowgroups have zero height even when a height is specified (bug 241161). something about the ov...
Mozilla Style System Documentation
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. ...
...s 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. ...
... 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 context tree and rule tree) allows for sharing of style data, which allows the data to take up less memory and allows the data computation to take less time. ...
...tree) allows for sharing of style data, which allows the data to take up less memory 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 n...
Activity Monitor, Battery Status Menu and top
users or software developers and it should be avoided. activity monitor can still be useful, however. power-related measurements activity monitor has several tabs. they can all be customized to show any of the available measurements (by right-clicking on the column strip) but only the "energy" tab groups child processes with parent processes, which is useful, so it's the best one to use. the following screenshot shows a customized "energy" tab. the power-related columns are as follows. energy impact / avg energy impact: see the separate section below. % cpu: cpu usage percentage. this can exceed 100% if multiple cores are being used. idle wake ups: in mac os 10.9 this measured "package idle exit" wakeups. this is the same value as powermetrics' "pkg idle" measurement (i.e. tas...
...rm_idle_wakeups obtained from the task_info function.) in mac os 10.10 it appears to have been changed to measure interrupt-level wakeups (a superset of idle wakeups), which are less interesting. this is the same value as powermetrics' "intr" measurement (i.e. task_power_info::task_interrupt_wakeups obtained from the task_info function.) requires high perf gpu: many macs have two gpus: a low-power, low-performance integrated gpu, and a high-power, high-performance external gpu. using the high-performance gpu can greatly increase power consumption, and should be avoided whenever possible. this column indicates which gpu is being used. activity monitor can be useful for cursory measurements, but for more precise and detailed measurements other tools such as powermetrics are better. ...
...d. activity monitor can be useful for cursory measurements, but for more precise and detailed measurements other tools such as powermetrics are better. what does "energy impact" measure? "energy impact" is a hybrid proxy measure of power consumption. 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 onl...
... 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 will show periodically-updating data like the following. pid command %cpu idlew power 50300 firefox 12.9 278 26.6 76256 plugin-container ...
Leak-hunting strategies and tips
ying to find a leak of reference-counted objects, there are a number of patterns that could cause the leak: ownership cycles. the most common source of hard-to-fix leaks is ownership cycles. if you can avoid creating cycles in the first place, please do, since it's often hard to be sure to break the cycle in every last case. sometimes these cycles extend through js objects (discussed further below), and since js is garbage-collected, every pointer acts like an owning pointer and the potential for fan-out is larger. see bug 106860 and bug 84136 for examples. (is this advice still accurate now that we have a cycle collector? --jesse) dropping a reference on the floor by: forgetting to release (because you weren't using nscomptr when you should have been): see bug 99180 or bug 93087 fo...
...debugging leaks that go through xpconnect many large object graphs that leak go through xpconnect. this can mean there will be xpconnect wrapper objects showing up as owning the leaked objects, but it doesn't mean it's xpconnect's fault (although that has been known to happen, it's rare). debugging leaks that go through xpconnect requires a basic understanding of what xpconnect does. xpconnect allows an xpcom object to be exposed to javascript, and it allows certain javascript objects to be exposed to c++ code as normal xpcom objects. when a c++ object is exposed to javascript (the more common of the two), an xpcwrappednative object is created. this wrapper owns a reference to the native object until the corresponding javascript object is garbage-collected. this means that if there are leak...
... debugging tools don't have very good symbol information (since they just show the results of dladdr). the stacks can be significantly improved (better symbols, and file name / line number information) by post-processing. stacks can be piped through the script tools/rb/fix_stacks.py to do this. these scripts are designed to be run on balance trees in addition to raw stacks; since they are rather slow, it is often much faster to generate balance trees (e.g., using make-tree.pl for the refcount balancer or diffbloatdump.pl --use-address for trace-malloc) andthen run the balance trees (which are much smaller) through the post-processing. getting symbol information for system libraries windows setting the environment variable _nt_symbol_path to something like symsrv*symsrv.dll*f:\localsymbols*...
...nal debugging symbols for system libraries. fix_stacks.py uses this debugging information (although it does not verify that they match the library versions on the system). for example, on fedora, these are in *-debuginfo rpms (which are available in yum repositories that are disabled by default, but easily enabled by editing the system configuration). tips disabling arena allocation with many lower-level leak tools (particularly trace-malloc based ones, like leaksoup) it can be helpful to disable arena allocation of objects that you're interested in, when possible, so that each object is allocated with a separate call to malloc. some places you can do this are: layout engine define debug_tracemalloc_framearena where it is commented out in layout/base/nspresshell.cpp glib set the e...
Profiling with Xperf
the symbol path directly from within the program via the trace menu. just make sure you set the symbol paths before enabling "load symbols" and before opening a summary view. you can also modify the _nt_symbol_path and _nt_symcache_path environment variables to make these changes permanent. the standard symbol path that includes both mozilla's and microsoft's symbol server configuration is as follows: _nt_symcache_path: c:\symbols _nt_symbol_path: srv*c:\symbols*http://msdl.microsoft.com/download/symbols;srv*c:\symbols*http://symbols.mozilla.org/firefox/ to add symbols from your own builds, add c:\path\to\objdir\dist\bin to _nt_symbol_path. as with all windows paths, the symbol path uses semicolons (;) as separators. make sure you select the trace -> load symbols menu option in the windows ...
... aifi, aifo, aofi. this is shorthand for "allocated inside, freed inside", "allocated inside, freed outside", "allocated outside, freed inside". these refer to the time range that was selected for the summary graph; for example, something that's in the aofi category was allocated before the start of the selected time range, but the free event happened inside. tips in the summary views, the yellow bar can be dragged left and right to change the grouping -- for example, drag it to the left of the module column to have grouping happen only by process (stuff that's to the left), so that you get symbols in order of weight, regardless of what module they're in. dragging the columns around will change grouping in various ways; experiment to get the data that you're looking for. also experiment ...
...-- for example, drag it to the left of the module column to have grouping happen only by process (stuff that's to the left), so that you get symbols in order of weight, regardless of what module they're in. dragging the columns around will change grouping in various ways; experiment to get the data that you're looking for. ...
...traces can be captured fine without this option (for example, from nightlies), but the stack information will not be useful. ...
Reporting a Performance Problem
d select 'capture'. try to do this within a few seconds from reproducing the performance problem as only the last few seconds are recorded. if the timeline has a large red block it's a good sign. the data will open in a new tab. wait until the "symbolicating call stacks" notification disappears before sharing the profile. there will be a button in the top right labeled 'publish' which will allow you to upload this profile and once completed will write out a link. before uploading, the publish button asks you what data you'd like to publish to our servers. note that while it's possible to strip profiles of potentially privacy sensitive information, the less information a profile contains, the harder it is to analyze and turn into actionable data. once uploaded, copy permalink url to you...
...l to your clipboard by right clicking and add the profile url to a bug for your performance problem and/or send it to the appropriate person. try to give some context about what you were doing when the performance problem arose such as the url you were viewing and what actions were you doing (ex. scrolling on gmail.com). viewing addon performance in geckoview sometimes an addon or more are slowing down firefox. these addons might be using the extension api in ways that were not meant to. you can see which of these addons are causing problems by adding the "moz-extension" filter. make sure you are selecting the process that is using up the cpu since all of the processes are shown. you might have a content process using up the cpu and not the main one. make sure you are doing whatever...
...fox. these addons might be using the extension api in ways that were not meant to. you can see which of these addons are causing problems by adding the "moz-extension" filter. make sure you are selecting the process that is using up the cpu since all of the processes are shown. you might have a content process using up the cpu and not the main one. ...
... see which of these addons are causing problems by adding the "moz-extension" filter. make sure you are selecting the process that is using up the cpu since all of the processes are shown. you might have a content process using up the cpu and not the main one. make sure you are doing whatever it is that slows down firefox while recording the profile. for example you might have one addon that slows down page load and another one that slows down tab switch. your first reflex once you find what addon is slowing down the profile might be to disable it and search for alternatives. before you do this, please share the performance profile with the addon authors through a bug report. gecko profiler allows you to share a link with the profile. ...
TraceMalloc
oved from the codebase. this documentation is only relevant to older versions of the codebase that still contain it. tracemalloc captures stack traces of all malloc, calloc , realloc, and free calls (this currently covers all operator new and delete calls in mozilla, too). to enable tracemalloc in your build, configure with --enable-trace-malloc. the built mozilla application will support the following additional command-line options: --trace-malloc filename the application will log allocation and deallocation events with stack traces in a binary format to the given file. if filename is -, nothing is written to a file, but tracemalloc will be active and will track live allocations and their stack traces. --shutdown-leaks=filename on shutdown, the application will save live allocations (...
...and down each graph. bloatblame accumulates allocation counts and ignores free calls. if you run with --trace-malloc -, your code can call ns_tracemallocdumpallocations(pathname) at opportune times, and a human-readable listing of the current heap, including stack traces for every allocation, will be written to pathname. ...
...mldocument.mreferrer 177 21550 691 85460 514 63910 3.53 nshtmlvalue 139 7846 1215 68734 1076 60888 3.36 htmlcontentsink 6 4816 12 57782 6 52966 2.92 uncategorized.pl, which lists all the void* allocations (the ones that couldn't be categorized by type), sorted by size. also, your javascript can call the following dom window methods: tracemallocdisable() - turn off tracing, first flushing any buffered log events for all log files. tracemallocenable() - turn on tracing. tracemallocopenlogfile(filename) - open a new log file and return its log file descriptor (or -1 on error). tracemallocchangelogfd(logfd) - change the current log file to the one identified by logfd, returning the previous fd (so you...
....log # convert raw log to text representation of call trees perl source/tools/trace-malloc/diffbloatdump.pl --depth=15 --use-address /dev/null sdleak.log > sdleak.tree.raw # frobulate trees to remove extraneous junk perl source/tools/rb/fix-macosx-stack.pl sdleak.tree.raw > sdleak.tree you can also use the leakstats program to analyze a log for shutdown leaks. it will produce a report like the following. leaks: 382739 bytes, 3465 allocations maximum heap size: 7751799 bytes 62095212 bytes were allocated in 391091 allocations. detecting memory usage growth in a running process to do this, dump the existing allocations to a file by calling the function tracemallocdumpallocations from javascript. you can use the following web page to do so. <script type="text/javascript"> var filename = wind...
I/O Functions
etopenfileinfo pr_getopenfileinfo64 pr_seek pr_seek64 pr_available pr_available64 pr_sync pr_getdesctype pr_getspecialfd pr_createpipe directory i/o functions pr_opendir pr_readdir pr_closedir pr_mkdir pr_rmdir socket manipulation functions the network programming interface presented here is a socket api modeled after the popular berkeley sockets. 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_opentcpsocket pr_newtcpsocket pr_importtcpsocket pr_connect pr_connectcontinue pr_accept pr_bind pr_listen pr_shutdo...
... memory-mapped i/o functions are currently implemented for unix, linux, mac os x, and win32 only. pr_createfilemap pr_memmap pr_memunmap pr_closefilemap anonymous pipe function pr_createpipe polling functions this section describes two of the most...
... memory-mapped i/o functions are currently implemented for unix, linux, mac os x, and win32 only. pr_createfilemap pr_memmap pr_memunmap pr_closefilemap anonymous pipe function pr_createpipe polling functions this section describes two of the most important polling functions provided by nspr: pr_poll...
...define pr_top_io_layer (prdescidentity)-2 #define pr_nspr_io_layer (prdescidentity)0 pr_invalid_io_layer: an invalid layer identify (for error return). pr_top_io_layer: the identity of the top of the stack. pr_nspr_io_layer: the identity for the layer implemented by nspr. ...
NSPR Error Handling
dress_not_supported_error the type of network address specified is not supported. pr_is_connected_error an attempt to connect on an already connected network file descriptor. pr_bad_address_error the network address specified is invalid (as reported by the network). pr_address_in_use_error network address specified (prnetaddr) is in use. pr_connect_refused_error the peer has refused to allow the connection to be established. pr_network_unreachable_error the network address specifies a host that is unreachable (perhaps temporary). pr_connect_timeout_error the connection attempt did not complete in a reasonable period of time. pr_not_connected_error the preceding function attempted to use connected semantics on a network file descriptor that was not connected. pr_load_library_er...
...at is already bound. pr_no_access_rights_error calling thread does not have privilege to perform the operation requested. pr_operation_not_supported_erro the requested operation is not supported by the 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. ...
...mpleting 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_error unused. pr_no_seek_device_error unused. pr_is_directory_error attempt to perform a normal file operation on a directory. pr_loop_error symbolic link loop. pr_name_too_long_error filename is longer than allowed by the host operating system. pr_file_not_found_error the requested file was not found. pr_not_directory_error attempt to perform directory specific operations on a normal file. pr_read_only_filesystem_error attempt to write to a read-only file system. pr_directory_not_empty_error attempt to delete a directory that is not empty. pr_filesystem_mounted_error attempt to delete or rename ...
...ile the file system is busy. pr_not_same_device_error request to rename a file to a file system on another device. pr_directory_corrupted_error the directory object in the file system is corrupted. pr_file_exists_error attempt to create or rename a file when the new name is already being used. pr_max_directory_entries_error attempt to add new filename to directory would exceed the limit allowed. pr_invalid_device_state_error the device was in an invalid state to complete the desired operation. pr_device_is_locked_error the device needed to perform the desired request is locked. pr_no_more_files_error there are no more entries in the directory. pr_end_of_file_error unexpectedly encountered end of file (mac os only). pr_file_seek_error an unexpected seek error (mac os only). ...
PRThreadPriority
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 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 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. ...
...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 host platforms, nspr priorities are not precisely defined. at best they are intended to specify a preference in the amount of cpu time that a higher-priority thread might expect relative to a lower-priority thread. this preference is still subject to resource availability and must not be used in pl...
PR_InitializeNetAddr
initializes or reinitializes a network address. the storage for the network address structure is allocated by, and remains the responsibility of, the calling client. syntax #include <prnetdb.h> prstatus pr_initializenetaddr( prnetaddrvalue val, pruint16 port, prnetaddr *addr); parameters the function has the following parameters: val the value to be assigned to the ip address portion of the network address. this must be pr_ipaddrnull, pr_ipaddrany, or pr_ipaddrloopback. port the port number to be assigned in the network address structure. the value is specified in host byte order. addr a pointer to the prnetaddr structure to be manipulated. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. this may occ...
...e order. addr a pointer to the prnetaddr structure to be manipulated. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. this may occur, for example, if the value of val is not within the ranges defined by prnetaddrvalue. you can retrieve the reason for the failure by calling pr_geterror. description pr_initializenetaddr allows the assignment of special network address values and the port number, while also setting the state that indicates the version of the address being used. ...
... 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. ...
... address values and the port number, while also setting the state that indicates the version of the address being used. the special network address values are identified by the enum prnetaddrvalue: typedef enum prnetaddrvalue{ pr_ipaddrnull, pr_ipaddrany, pr_ipaddrloopback } prnetaddrvalue; the enum has the following enumerators: pr_ipaddrnull do not overwrite the ip address. 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 h...
PR_Open
in most cases, only one of the first three flags may be used. ...
...in most cases, only one of the first three flags may be used. ...
... action and null is returned. mode when pr_create_file flag is set and the file is created, these flags define the access permission bits of the newly created file. this feature is currently only applicable on unix platforms. it is ignored by any other platform but it may apply to other platforms in the future. possible values of the mode parameter are listed in the table below. name value description pr_irwxu 0700 read, write, execute/search by owner. pr_irusr 0400 read permission, owner. pr_iwusr 0200 write permission, owner. pr_ixusr 0100 execute/search permission, owner. pr_irwxg 0070 read, write, execute/search by group pr_irgrp ...
...the prfiledesc should be freed by calling pr_close. if the file was not opened successfully, a null pointer. description pr_open creates a file descriptor (prfiledesc) for the file with the pathname name and sets the file status flags of the file descriptor according to...
PR_Writev
writes data to a socket from multiple buffers. syntax #include <prio.h> print32 pr_writev( prfiledesc *fd, priovec *iov, print32 size, printervaltime timeout); #define pr_max_iovector_size 16 parameters the function has the following parameters: fd a pointer to a prfiledesc object for a socket. iov an array of priovec structures that describe the buffers to write from. size number of priovec structures in the iov array. the value of this parameter must not be greater than pr_max_iovector_size. ...
... the value -1 indicates that the operation failed. the reason for the failure can be obtained by calling pr_geterror. ...
... the value -1 indicates that the operation failed. ...
...urns -1, part of the data may have been written before an error occurred. if the timeout parameter is not pr_interval_no_timeout and all the data cannot be written in the specified interval, pr_writev returns -1 with the error code pr_io_timeout_error. this is the type definition for priovec: typedef struct priovec { char *iov_base; int iov_len; } priovec; the priovec structure has the following fields: iov_base a pointer to the beginning of the buffer. iov_len the size of the buffer. ...
NSS 3.15.2 release notes
users are encouraged to upgrade immediately. bug 894370 - (cve-2013-1739) avoid uninitialized data read in the event of a decryption failure. ...
...rk security services (nss) 3.15.2 is a patch release for nss 3.15. the bug fixes in nss 3.15.2 are described in the "bugs fixed" section below. distribution information nss 3.15.2 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_2_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.15.2. users are encouraged to upgrade immediately. bug 894370 - (cve-2013-1739) avoid uninitialized data read in the event of a decryption failure. ...
...new types no new types have been introduced. ...
...ug 880543 - support for aes-gcm ciphersuites that use the sha-256 prf bug 663313 - md2, md4, and md5 signatures are no longer accepted for ocsp or crls, consistent with their handling for general certificate signatures. bug 884178 - add pk11_cipherfinal macro bugs fixed in nss 3.15.2 bug 734007 - sizeof() used incorrectly bug 900971 - nssutil_readsecmoddb() leaks memory bug 681839 - allow ssl_handshakenegotiatedextension to be called before the handshake is finished. bug 848384 - deprecate the ssl cipher policy code, as it's no longer relevant. it is no longer necessary to call nss_setdomesticpolicy because all cipher suites are now allowed by default. a complete list of all bugs resolved in this release can be obtained at https://bugzilla.mozilla.org/buglist.cgi?resolution=fix...
NSS 3.16.3 release notes
introduction network security services (nss) 3.16.3 is a patch release for nss 3.16. the bug fixes in nss 3.16.3 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_16_3_rtm. nss 3.16.3 requires nspr 4.10.6 or newer. nss 3.16.3 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_3_rtm/src/ new in nss 3.16.3 this release consists primarily of ca certificate changes as listed below, and fixes an issue with a recently added utility function. new functions in cert.h ​cert_getgeneralnametypefromstring - an utlity function to lookup a value of type certgeneralnametype given a human readable string. this function was alr...
...ate changes as listed below, and fixes an issue with a recently added utility function. new functions in cert.h ​cert_getgeneralnametypefromstring - an utlity function to lookup a value of type certgeneralnametype given a human readable string. this function was already added in nss 3.16.2, however, it wasn't declared in a public header file. ...
...nt: e5:df:74:3c:b6:01:c4:9b:98:43:dc:ab:8c:e8:6a:81:10:9f:e4:8e ou = valicert class 2 policy validation authority sha1 fingerprint: 31:7a:2a:d0:7f:2b:33:5e:f5:a1:c3:4e:4b:57:e8:b7:d8:f1:fc:a6 ou = valicert class 3 policy validation authority sha1 fingerprint: 69:bd:8c:f4:9c:d3:00:fb:59:2e:17:93:ca:55:6a:f3:ec:aa:35:fb additionally, the following ca certificate was removed as requested by the ca ou = tdc internet root ca sha1 fingerprint: 21:fc:bd:8e:7f:6c:af:05:1b:d1:b3:43:ec:a8:e7:61:47:f2:0f:8a the following ca certificates were added cn = certification authority of wosign sha1 fingerprint: b9:42:94:bf:91:ea:8f:b6:4b:e6:10:97:c7:fb:00:13:59:b6:76:cb cn = ca 沃通根证书 ...
... g3 sha1 fingerprint: 1b:8e:ea:57:96:29:1a:c9:39:ea:b8:0a:81:1a:73:73:c0:93:79:67 cn = quovadis root ca 2 g3 sha1 fingerprint: 09:3c:61:f3:8b:8b:dc:7d:55:df:75:38:02:05:00:e1:25:f5:c8:36 cn = quovadis root ca 3 g3 sha1 fingerprint: 48:12:bd:92:3c:a8:c4:39:06:e7:30:6d:27:96:e6:a4:cf:22:2e:7d the trust bits were changed for the following ca certificates ou = class 3 public primary certification authority sha1 fingerprint: a1:db:63:93:91:6f:17:e4:18:55:09:40:04:15:c7:02:40:b0:ae:6b turned off websites and code signing trust bits (1024-bit root) ou = class 3 public primary certification authority sha1 fingerprint: 74:2c:31:92:e6:07:e4:24:eb:45:49:54:2b:e1:bb:c5:3e:61:74:e2 turned o...
NSS 3.18.1 release notes
introduction network security services (nss) 3.18.1 is a patch release for nss 3.18. the bug fixes in nss 3.18.1 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_18_1_rtm. nss 3.18.1 requires nspr 4.10.8 or newer. nss 3.18.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_18_1_rtm/src/ new in nss 3.18.1 no new functionality is introduced in this release. this is a patch release to update the list of root ca certificates. ...
...spr 4.10.8 or newer. nss 3.18.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_18_1_rtm/src/ new in nss 3.18.1 no new functionality is introduced in this release. this is a patch release to update the list of root ca certificates. notable changes in nss 3.18.1 the following ca certificate had the websites and code signing trust bits restored to their original state to allow more time to develop a better transition strategy for affected sites. 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...
...8 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. ...
...cate authority sha1 fingerprint: d2:32:09:ad:23:d3:14:23:21:74:e4:0d:7f:9d:62:13:97:86:63:3a the following ca certificate was removed after discussion about it in the mozilla.dev.security.policy forum. cn = e-guven kok elektronik sertifika hizmet saglayicisi sha1 fingerprint: dd:e1:d2:a9:01:80:2e:1d:87:5e:84:b3:80:7e:4b:b1:fd:99:41:34 the following intermediate ca certificate has been added as actively distrusted because it was misused to issue certificates for domain names the holder did not own or control. cn=mcsholding test, o=mcsholding, c=eg sha1 fingerprint: e1:f3:59:1e:76:98:65:c4:e4:47:ac:c3:7e:af:c9:e2:bf:e4:c5:76 the version number of the updated root ca list has been set to 2.4 bugs fixed in ns...
NSS 3.24 release notes
te of standards and technology (nist) guidance (as of 2015): software integrity checks and post functions are executed on shared library load. these checks have been disabled by default, as they can cause a performance regression. to enable these checks, you must define symbol nss_force_fips when building nss. counter mode and galois/counter mode (gcm) have checks to prevent counter overflow. additional csps are zeroed in the code. nss softoken uses new guidance for how many rabin-miller tests are needed to verify a prime based on prime size. nss softoken has also been updated to allow nss to run in fips level 1 (no password). this mode is triggered by setting the database password to the empty string. in fips mode, you may move from level 1 to level 2 (by setting an appr...
...ena pool, to be used for temporary arena allocations. new macros in pkcs11t.h ckm_tls12_mac in secoidt.h sec_oid_tls_ecdhe_psk - this oid governs the use of the tls_ecdhe_psk_with_aes_128_gcm_sha256 cipher suite, which is used only for session resumption in tls 1.3. notable changes in nss 3.24 additions, deprecations, and other changes in nss 3.24 are listed below. deprecate the following functions. (applications should instead use the new ssl_configservercert function.) ssl_setstapledocspresponses ssl_setsignedcerttimestamps ssl_configsecureserver ssl_configsecureserverwithcertchain deprecate the nss_findcertkeatype function, as it reports a misleading value for certificates that might be used for signing rather than key exchange. ...
...s that might be used for signing rather than key exchange. update sslauthtype to define a larger number of authentication key types. deprecate the member attribute authalgorithm of type sslciphersuiteinfo. instead, applications should use the newly added attribute authtype. rename ssl_auth_rsa to ssl_auth_rsa_decrypt. add a shared library (libfreeblpriv3) on linux platforms that define freebl_lowhash. remove most code related to ssl v2, including the ability to actively send a sslv2-compatible client hello. however, the server-side implementation of the ssl/tls protocol still supports processing of received v2-compatible client hello messages. disable (by default) nss support in optimized builds for logging ssl/tls key material to a logfile if the sslkeylogfile environment variable is s...
...lv2-compatible client hello. however, the server-side implementation of the ssl/tls protocol still supports processing of received v2-compatible client hello messages. disable (by default) nss support in optimized builds for logging ssl/tls key material to a logfile if the sslkeylogfile environment variable is set. to enable the functionality in optimized builds, you must define the symbol nss_allow_sslkeylogfile when building nss. update nss to protect it against the cachebleed attack. disable support for dtls compression. improve support for tls 1.3. this includes support for dtls 1.3. note that tls 1.3 support is experimental and not suitable for production use. bugs fixed in nss 3.24 this bugzilla query returns all the bugs fixed in nss 3.24: https://bugzilla.mozilla.org/buglist.c...
NSS 3.48 release notes
ere possible. see bug 1575411 for details. the master password pbe now uses 10,000 iterations by default when using the default sql (key4.db) storage. ...
...m (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. ...
...ble 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: 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 ...
...33 for details. ...
nss tech note7
rsa signing and encryption with nss nss technical note: 7 this technical note explains how to use nss to perform rsa signing and encryption. the industry standard for rsa signing and encryption is pkcs #1. nss supports pkcs #1 v1.5. nss doesn't yet support pkcs #1 v2.0 and v2.1, in particular oaep, but oaep support is on our to-do list. your contribution is welcome. data types nss uses the following data types to represent keys: 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 ...
...ver 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 modulus size greater than 8192 bits. how are these keys created in nss? there are a few possibilities. rsa key pairs may be generated inside a crypto module (also known as a token). use pk11_generatekeypair() to generate a key pair in a crypto module. key pairs may be generated elsewhere, exported in encrypted form, and imported into a crypto module. public keys may be imported into nss. ...
... rsa public key. if you have the modulus and public exponent, you need to first encode them into an rsa public key and then import the public key into nss. pkcs #1 defines an rsa public key as a sequence of modulus and public exponent, both of which are integers. here is the asn.1 type definition: rsapublickey ::= sequence { modulus integer, -- n publicexponent integer -- e } the following sample code (error handling omitted for brevity) encodes a rsapublickey from a modulus and a public exponent and imports the public key into nss. struct myrsapublickey { secitem m_modulus; secitem m_exponent; } inpubkey; secitem derpubkey; seckeypublickey *pubkey; const sec_asn1template myrsapublickeytemplate[] = { { sec_asn1_sequence, 0, null, sizeof(myrsapublickey) }, { ...
...ocol that isn't implemented by nss, then you may need to use the pk11_ functions. (this api pretty much consists of what was needed to implement ssl and s/mime, plus a few enhancements over the years to support jss.) when using the pk11_ interfaces, the same principal applies: use the highest available function. if you are really trying to send a key, you should use pk11_pubwrapsymkey(). for a low level signature, use pk11_sign(). both of these functions do the pkcs #1 wrapping of the data. pk11_sign does not do the ber encoding of the hash (as is done in sgn_ functions). if you are trying to just send data, use pk11_pubencryptpkcs1. pk11_pubencryptraw is the lowest level function. it takes a modulus size data and does a raw rsa operation on the data. it's used to support ssl2, which...
PKCS #11 Module Specs
nss currently implements this proposal internally. the file format consists of name/value pairs of the form name=value. each name/value pair is separated by a blank value. a single line, terminated by a '\n', '\r\n', or '\r' represents a single pkcs #11 library. names 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 <. ...
...ding 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 #11 module 'on-the-fly'. recognized names all applications/libraries must be able recognize the following name values: library this specifies the path to the pkcs #11 library. name this specifies the name of the pkcs #11 library. parameter this specifies a pkcs #11 library parameter with the application must pass to the pkcs #11 library at c_initialize() time (see below). in additions applications/libraries should be able to ignore additional name value pairs which are used to specify...
... 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. timeout- whenever the last explicit login was longer than 'timeout' minutes ago. only - authenticate to the token only when necessary (default). sample file: library= name="netscape internal crypto module" parameters="...
...kens parameter specifies a space separated list of slotids, each of which specify their own set of parameters affecting that token. typically 'tokens' would not be specified unless additional databases are to be opened as additional tokens. if tokens is specified, then all tokens (including the default tokens) need to be specified. ...
PKCS11 Implement
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. currently pkcs #12 isn't allowed to import onto a token. the nss also uses c_createobject to create new session keys. the nss sometimes loads raw key data and builds a key from that. the nss will be doing more and more session key generation on tokens in the future. it's also possible for nss to load a key if the private key that decrypted the key is located on a different slot. for example, if a particular token can't do des ...
...lways attempts to use these two functions but uses c_encrypt and c_decrypt instead if c_wrapkey and c_unwrapkey aren't implemented. installation you can install your module in any convenient location on the user's hard disk, but you must tell the user to type the module name and location in the cryptographic modules portion of the communicator security info window. to do so, the user should follow these steps: click the security icon near the top of any communicator window. in the security info window, click cryptographic modules. in the cryptographic modules frame, click add. in the create a new security module dialog box, add the security module name for your module and the full pathname for the security module file. to avoid requiring the user to type long pathnames, make sure you...
... semantics unique to nss these sections describe semantics required by nss but not specified by pkcs #11. supporting multiple sessions if you support multiple sessions simultaneously and if you wish to support c_initpin, c_setpin, or c_generatekeypair, you must support simultaneous read-only and read/write sessions. random-number generation and simple digesting the nss requires that the following functions operate without authenticating to the token: c_seedrandom, c_generaterandom, and c_digest (for sha, md5, and md2). if your token requires authentication before executing these functions, your token cannot provide the default implementation for them. (you can still use your token for other default functions.) nss does not support replacement of default functions. later versions will p...
... and c_digest (for sha, md5, and md2). if your token requires authentication before executing these functions, your token cannot provide the default implementation for them. (you can still use your token for other default functions.) nss does not support replacement of default functions. later versions will provide such support. read/write and read-only requirements the nss assumes that the following operations always require a read/write session: creating a token object, such as with c_createobject (token) or c_destroyobject (token) changing a password initializing a token creating session objects must work with a read-only session. creating an rsa private key when nss creates an rsa private key with c_createobject, it writes the entire set of rsa components. it expects to be able...
NSS tools : modutil
rmat. --dbprefix prefix specify the prefix used on the database files, such as my_ for my_cert8.db. this option is provided as a special case. changing the names of the certificate and key databases is not recommended. -installdir root-installation-directory specify the root installation directory relative to which files will be installed by the -jar option. this directory should be one below which it is appropriate to store dynamic library files, such as a server's root directory. -libfile library-file specify a path to a library file containing the implementation of the pkcs #11 interface module that is being added to the database. -mechanisms mechanism-list specify the security mechanisms for which a particular module will be flagged as a default provider. the mechanism-list...
... --> valuelist valuelist --> value valuelist <null> value ---> key_value_pair string key_value_pair --> key { valuelist } key --> string string --> simple_string "complex_string" simple_string --> [^ \t\n\""{""}"]+ complex_string --> ([^\"\\\r\n]|(\\\")|(\\\\))+ quotes and backslashes must be escaped with a backslash...
...nss database types nss originally used berkeleydb databases to store security information. the last versions of these legacy databases are: o cert8.db for certificates o key3.db for keys o secmod.db for pkcs #11 module information berkeleydb has performance limitations, though, which prevent it from being easily used by multiple applications simultaneously. nss has some flexibility that allows applications to use their own, independent database engine while keeping a shared database and working around the access issues. still, nss requires more flexibility to provide a truly shared security database. in 2009, nss introduced a new set of databases that are sqlite databases rather than berkleydb. these new databases provide more accessibility and performance: o cert9.db for certi...
...s listing of all of the pkcs #11 modules contained in a new subdirectory in the security databases directory because the sqlite databases are designed to be shared, these are the shared database type. the shared database type is preferred; the legacy format is included for backward compatibility. by default, the tools (certutil, pk12util, modutil) assume that the given security databases follow the more common legacy type. using the sqlite databases must be manually specified by using the sql: prefix with the given security directory. for example: modutil -create -dbdir sql:/home/my/sharednssdb to set the shared database type as the default type for the tools, set the nss_default_db_type environment variable to sql: export nss_default_db_type="sql" this line can be added to the ~...
NSS tools : vfychain
ule contents, enable or disable slots, enable or disable fips 140-2 compliance, and assign default providers for cryptographic operations. this tool can also create certificate, key, and module security database files. the tasks associated with security module database management are part of a process that typically also involves managing key databases and certificate databases. ...
...ficate databases. options -a the following certfile is base64 encoded -b yymmddhhmmz validate date (default: now) -d directory database directory -f enable cert fetching from aia url -o oid set policy oid for cert validation(format oid.1.2.3) -p use pkix library to validate certificate by calling: * cert_verifycertificate if specified once, * cert_pkixverifycert if specified twice and more. -r following certfile is raw binary der (default) -t following cert is explicitly trusted (overrides db trust) -u usage 0=ssl client, 1=ssl server, 2=ssl stepup, 3=ssl ca, 4=email signer, 5=email recipient, 6=object signer, 9=protectedobjectsigner, 10=ocsp responder, 11=any ca -v verbose mode. prints root cert subject(double the argument for whole root cert info) -w password database password -w pwfile pas...
...rust) -u usage 0=ssl client, 1=ssl server, 2=ssl stepup, 3=ssl ca, 4=email signer, 5=email recipient, 6=object signer, 9=protectedobjectsigner, 10=ocsp responder, 11=any ca -v verbose mode. prints root cert subject(double the argument for whole root cert info) -w password database password -w pwfile password file revocation options for pkix api (invoked with -pp options) is a collection of the following flags: [-g type [-h flags] [-m type [-s flags]] ...] ... where: -g test-type sets status checking test type. possible values are "leaf" or "chain" -g test type sets status checking test type. possible values are "leaf" or "chain". -h test flags sets revocation flags for the test type it follows. possible flags: "testlocalinfofirst" and "requirefreshinfo". -m method type sets method type for th...
...e [-h flags] [-m type [-s flags]] ...] ... where: -g test-type sets status checking test type. possible values are "leaf" or "chain" -g test type sets status checking test type. possible values are "leaf" or "chain". -h test flags sets revocation flags for the test type it follows. possible flags: "testlocalinfofirst" and "requirefreshinfo". -m method type sets method type for the test type it follows. possible types are "crl" and "ocsp". -s method flags sets revocation flags for the method it follows. possible types are "donotuse", "forbidfetching", "ignoredefaultsrc", "requireinfo" and "failifnoinfo". additional resources for information about nss and other tools related to nss (like jss), check out the nss project wiki at [1]http://www.mozilla.org/projects/security/pki/nss/. the nss site r...
sslintro.html
this page is part of the ssl reference that we are migrating into the format described in the mdn style guide. if you are inclined to help with this migration, your help would be very much appreciated. upgraded documentation may be found in the current nss reference overview of an ssl application chapter 1 overview of an ssl application ssl and related apis allow compliant applications to configure sockets for authenticated, tamper-proof, and encrypted communications. this chapter introduces some of the basic ssl functions. chapter 2, "getting started with ssl" illustrates their use in sample client and server applications. an ssl application typically includes five parts: initialization configuration communication functions used by callbacks cl...
...d certificate, key, and pkcs #11 apis) that are described in this document, the ssl reference. other apis that may be exposed in the header files are not supported for application use. initialization initialization includes setting up configuration files, setting global defaults, and setting up callback functions. functions used in the initialization part of an application can include the following: pr_init. initializes nspr. must be called before any other nss functions. pk11_setpasswordfunc. sets the global callback function to obtain passwords for pkcs #11 modules. required. nss_init. sets up configuration files and performs other tasks required to run network security services. nss_init is not idempotent, so call it only once. required. ssl_optionsetdefault. changes def...
...change from those established with ssl_optionsetdefault. optional. ssl_configsecureserver. for servers only. configures the socket with the information needed to handshake as an ssl server. required for servers. ssl_seturl. for clients only. records the target server url for comparison 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 ...
...that this step would not be necessary if the socket weren't already connected. for an ssl socket that is configured before it is connected, ssl figures this out when the application calls pr_connect or pr_accept. if the socket is already connected before ssl gets involved, you must provide this extra hint. functions that can be used by both clients and servers during communication include the following: pr_send or pr_write pr_read or pr_recv pr_geterror pr_getpeername pr_sleep pr_malloc pr_free pr_poll pr_now pr_intervaltomilliseconds pr_millisecondstointerval pr_shutdown pr_close ssl_invalidatesession after establishing a connection, an application first calls pr_send, pr_recv, pr_read, pr_write, or ssl_forcehandshake to initiate the handshake. the application's...
NSS tools : modutil
Mozilla › Projects › NSS › tools › modutil
he database files, such as my_ for my_cert8.db. this option is provided as a special case. changing the names of the certificate and key databases is not recommended. -installdir root-installation-directory specify the root installation directory relative to which files will be installed by the -jar option. this directory should be one below which it is appropriate to store dynamic library files, such as a server's root directory. -libfile library-file specify a path to a library file containing the implementation of the pkcs #11 interface module that is being added to the database. -mechanisms mechanism-list specify the security mechanisms for which a particular module will ...
... --> valuelist valuelist --> value valuelist <null> value ---> key_value_pair string key_value_pair --> key { valuelist } key --> string string --> simple_string "complex_string" simple_string --> [^ \t\n\""{""}"]+ complex_string --> ([^\"\\\r\n]|(\\\")|(\\\\))+ quo...
...originally used berkeleydb databases to store security information. the last versions of these legacy databases are: o cert8.db for certificates o key3.db for keys o secmod.db for pkcs #11 module information berkeleydb has performance limitations, though, which prevent it from being easily used by multiple applications simultaneously. nss has some flexibility that allows applications to use their own, independent database engine while keeping a shared database and working around the access issues. still, nss requires more flexibility to provide a truly shared security database. in 2009, nss introduced a new set of databases that are sqlite databases rather than berkleydb. these new databases provide more accessibility and performance: o ...
...f the pkcs #11 modules contained in a new subdirectory in the security databases directory because the sqlite databases are designed to be shared, these are the shared database type. the shared database type is preferred; the legacy format is included for backward compatibility. by default, the tools (certutil, pk12util, modutil) assume that the given security databases follow the more common legacy type. using the sqlite databases must be manually specified by using the sql: prefix with the given security directory. for example: modutil -create -dbdir sql:/home/my/sharednssdb to set the shared database type as the default type for the tools, set the nss_default_db_type environment variable to sql: export nss_default_db_type="sql" this line can be ...
NSS tools : vfychain
ts, enable or disable fips 140-2 compliance, and assign default providers for cryptographic operations. this tool can also create certificate, key, and module security database files. the tasks associated with security module database management are part of a process that typically also involves managing key databases and certificate databases. ...
...default: now) -d directory database directory -f enable cert fetching from aia url -o oid set policy oid for cert validation(format oid.1.2.3) -p use pkix library to validate certificate by calling: * cert_verifycertificate if specified once, * cert_pkixverifycert if specified twice and more. -r following certfile is raw binary der (default) -t following cert is explicitly trusted (overrides db trust) -u usage 0=ssl client, 1=ssl server, 2=ssl stepup, 3=ssl ca, 4=email signer, 5=email recipient, 6=object signer, 9=protectedobjectsigner, 10=ocsp responder, 11=any ca -v verbose mode. prints root cert subject(double the argument f...
... recipient, 6=object signer, 9=protectedobjectsigner, 10=ocsp responder, 11=any ca -v verbose mode. prints root cert subject(double the argument for whole root cert info) -w password database password -w pwfile password file revocation options for pkix api (invoked with -pp options) is a collection of the following flags: [-g type [-h flags] [-m type [-s flags]] ...] ... where: -g test-type sets status checking test type. possible values are "leaf" or "chain" -g test type sets status checking test type. possible values are "leaf" or "chain". -h test flags sets revocation flags for the test type it follows. possible ...
...cking test type. possible values are "leaf" or "chain" -g test type sets status checking test type. possible values are "leaf" or "chain". -h test flags sets revocation flags for the test type it follows. possible flags: "testlocalinfofirst" and "requirefreshinfo". -m method type sets method type for the test type it follows. possible types are "crl" and "ocsp". -s method flags sets revocation flags for the method it follows. possible types are "donotuse", "forbidfetching", "ignoredefaultsrc", "requireinfo" and "failifnoinfo". additional resources for information about nss and other tools related to nss (like jss), check out the nss project wiki at [1]http:/...
Necko Architecture
warning: the content of this article may be out of date. it was last updated in 1999. necko is a modular networking library developed as part of the mozilla project. necko has been designed to accommodate pluggable protocols so developers can contribute their own protocol libraries that can be dynamically loaded and used by applications utilizing necko. necko provides the following libraries: necko - core networking functionality. mimetype - mime <-> file extension mapping nkabout - about: protocol nkdata - data: protocol nkfile - file: protocol nkftp - ftp: protocol nkkeyword - keyword: protocol nkresrc - resource: protocol cnvts - stream converters stremcnv - stream converter service these libraries will change with time and illustrate the modularity of necko. ar...
...ls and channels (nsichannel) in necko. given a string representation of a url, you can ask the nsiioservice for a url instance representing that string. once you have a url interface in hand (nsiurl), you have a completely parsed representation of the original url string, and you can query for the various parts of the url. handlers & channels nsichannel provides a data access interface which allows you to read or write data from or to a uri. there is a 1-to-1 relationship between uris and channels (if you go so far as to create a channel from a uri, which is not required if all you need is a parsed representation of a uri string). for every uri you want to transact with, there is exactly one channel. in order to get a channel from a uri an intermediary layer was introduced. because a uri h...
...stener to actually retrieve data that the channel has acquired. one of the arguments to the ondataavailable() notification is an nsiinputstream (which can be considered the underlying data). streams necko represents data in the form of streams (nsibasestream is the root interface. nsiinputstream is read from. nsioutputstream is written to). streams provide a generic interface to the data and allow for many underlying implementations that permit multiple data sources to be used. as a user, you don't care where the data came from, or where it "is," as long as you get the data. the data may be in memory, it may be on disk, or it may be located somewhere else. the point is that streams provide a loose interface for data access. if you initiate a synchronous transfer on a channel, you are hande...
...your protocol handler registered for. please use existing protocol handler's for reference (the data: protocol handler is the simplest handler necko provides, http is a fairly complex (uses many classes) implementation utilizing asynchronous i/o, and ftp provides an example of a protocol implementation that creates an extra thread which uses synchronous i/o). dependencies necko requires the following libraries for linking: nspr xpcom original document information author(s): jud valeski last updated date: november 8, 1999 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
GC Rooting Guide
ocated and managed by the spidermonkey garbage collector. the main types of gc thing pointer are: js::value jsobject* jsstring* jsscript* jsid note that js::value and jsid can contain pointers internally even though they are not a normal pointer type, hence their inclusion in this list. if you use these types directly, or create classes, structs or arrays that contain them, you must follow the rules set out in this guide. if you do not your program will not work correctly - if it works at all. gc things on the stack js::rooted<t> all gc thing pointers stored on the stack (i.e., local variables and parameters to functions) must use the js::rooted<t> class. this is a template class where the template parameter is the type of the gc thing it contains. from the user perspective, ...
... js::handle<t> all gc thing pointers that are parameters to a function must be wrapped in js::handle<t>. a js::handle<t> is a reference to a js::rooted<t>, and is created implicitly by referencing a js::rooted<t>: it is not valid to create a js::handle<t> manually (the whole point of a handle is that it only reference ...
... for example, instead of: jsobject * somefunction(jscontext *cx, jsobject* obj) { // ... } you should write: jsobject * somefunction(jscontext *cx, js::handleobject obj) { // ... } js::mutablehandle<t> all gc thing pointers that are used as out-parameters must be wrapped in a js::mutablehandle<t>. a js::mutablehandle<t> is a reference to a js::rooted<t> that, unlike a normal hand...
... the gc things contained in the object by calling js::traceedge. gc things on the heap js::heap<t> gc thing pointers on the heap must be wrapped in a js::heap<t>. the only exception to this is if they are added as roots with the js::persistentrooted class, but don't do this unless it's really necessary. js::heap<t> pointers must also continue to be traced in the normal way, which is covered below. js::heap<t> doesn't require a jscontext*, and can be constructed with or without an initial value parameter. like the other template classes, it functions as if it were the gc thing pointer itself. one consequence of having different rooting requirements for heap and stack data is that a single structure containing gc thing pointers cannot be used on both the stack and the heap. in this case...
Invariants
ariants regarding locks: we do not reenter them (it would be nice to check this as there might be an exception or two); we do not wait on a condition variable unless the corresponding lock is held. there are the usual invariants regarding various fields: they are protected by certain locks or more complex locking schemes. in particular, native objects' fields are protected by property locking (below); and several things are protected by the request model, such that there may be either one writer (in gc) or many readers (in requests). no jsnative or other object-related callback ever runs at the same time as a finalizer for that object. property locks each thread may have a lock on at most one property at a time. (nesting them would risk deadlock. js_setwatchpoint violates this rule.) wh...
...rule.) whether a property is locked, and which one, is static information for almost every line of code. the locking scheme is described under jsobjectops.dropproperty. (note that the locking scheme applies to all objects and talks about properties being locked. as implemented for native objects, the locking is not really that fine-grained, but that is a transparent optimization as long as we follow the rules.) a thread holding a property lock never leaves or suspends the current request. with a few exceptions (known to brendan and probably jst and mrbkap), we never call a jsapi callback with a property locked. (that would risk deadlock too.) name instructions the first operand to a jsop_setname instruction is always produced by a preceding jsop_bindname instruction. (taken together, ec...
...lback with a property locked. (that would risk deadlock too.) name instructions the first operand to a jsop_setname instruction is always produced by a preceding jsop_bindname instruction. (taken together, ecma 262-3 §11.13.1 and ecma 262-3 §10.1.4 specify that in an assignment such as x = f(), the name lookup for x occurs before f is called. ...
... if it cannot be statically proven that a name always refers to a specific variable (meaning either a parameter or a variable introduced by var/let/function/const) in the program, then a name op must be emitted. ...
SpiderMonkey Internals
g up to 'divisor' has its sumofdivisors // expression calculated, so we can determine whether it's perfect // already by evaluating. ...
...l.*, jsdate.*, jsfun.*, jsmath.*, jsnum.*, jsstr.* these file pairs implement the standard classes and (where they exist) their underlying primitive types. they have similar structure, generally starting with class definitions and continuing with internal constructors, finalizers, and helper functions. jsobj.*, jsscope.* these two pairs declare and implement the js object system. all of the following happen here: creating objects by class and prototype, and finalizing objects; defining, looking up, getting, setting, and deleting properties; creating and destroying properties and binding names to them. the details of a native object's map (scope) are mostly hidden in jsscope.[ch]. jsatom.cpp, jsatom.h the atom manager. contains well-known string constants, their atoms, the global a...
...ect's map (scope) are mostly hidden in jsscope.[ch]. jsatom.cpp, jsatom.h the atom manager. contains well-known string constants, their atoms, the global atom hash table and related state, the js_atomize() function that turns a counted string of bytes into an atom, and literal pool (jsatommap) methods. jsarena.cpp, jsarena.h last-in-first-out allocation 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...
... useful in calculating base-2 logarithms of integers. jsutil.cpp, jsutil.h the js_assert macro is used throughout the source as a proof device to make invariants and preconditions clear to the reader, and to hold the line during maintenance and evolution against regressions or violations of assumptions that it would be too expensive to test unconditionally at run-time. certain assertions are followed by run-time tests that cope with assertion failure, but only where i'm too smart or paranoid to believe the assertion will never fail... jsclist.h doubly-linked circular list struct and macros. jscpucfg.cpp this standalone program generates jscpucfg.h, a header file containing bytes per word and other constants that depend on cpu architecture and c compiler type model. it tries to discover ...
Property attributes
any object property can have zero or more property attributes set. some property attributes are defined in the ecmascript standard, in ecma 262-3 §8.6.1. spidermonkey additionally defines several non-standard property attributes. the jsapi expresses property attributes as a value of type unsigned, the bitwise or of zero or more of the jsprop flags described below. an application can set property attributes when creating a property. see js_defineproperty, js_fs, and js_fn flag description jsprop_enumerate the property is visible to javascript for...in and for each ... in loops, as well as to js_enumerate. this is the inverse of the ecma standard dontenum attribute. mxr id search for jsprop_enumerate jsprop_readonly the propert...
...defineproperty, js_fs, and js_fn flag description jsprop_enumerate the property is visible to javascript for...in and for each ... in loops, as well as to js_enumerate. this is the inverse of the ecma standard dontenum attribute. mxr id search for jsprop_enumerate jsprop_readonly the property's value cannot be set. ...
...in javascript 1.3 and higher, as in ecmascript, such attempts are ignored. this is the ecma standard dontdelete attribute. the javascript language does not provide any way for a script to delete a permanent property. ...
...b_gsops use js_propertystub getter/setter instead of defaulting to class gsops for property holding function. added in spidermonkey 17 mxr id search for jsfun_stub_gsops jsfun_constructor native that can be called as a constructor. added in spidermonkey 17 mxr id search for jsfun_constructor jsprop_redefine_nonconfigurable if set, will allow redefining a non-configurable property, but only on a non-dom global. this is a temporary hack 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 ...
Parser API
objects whether in spidermonkey shell or firefox (after importing), the global singleton object reflect currently contains just the parse method. properties of the reflect object the reflect object currently consists of a single method. reflect.parse(src[, options]) coerces src to a string and parses the result as a javascript program. by default, the parsing returns a program object (see below) representing the parsed abstract syntax tree (ast). additional options may be provided via the options object, which can include any of the following properties: loc boolean default: true when loc is true, the parser includes source location information in the returned ast nodes. source string default: null a description of the input source; typi...
...s the same message property as the syntax error that would be thrown by eval(src). the linenumber and filename properties of the syntax error object indicate the source location of the syntax error. node objects by default, reflect.parse() produces node objects, which 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 n...
...pattern. clauses interface switchcase <: node { type: "switchcase"; test: expression | null; consequent: [ statement ]; } a case (if test is an expression) or default (if test === null) clause in the body of a switch statement. interface catchclause <: node { type: "catchclause"; param: pattern; guard: expression | null; body: blockstatement; } a catch clause following a try block. the optional guard property corresponds to the optional expression guard on the bound variable. note: the guard expression is spidermonkey-specific. interface comprehensionblock <: node { type: "comprehensionblock"; left: pattern; right: expression; each: boolean; } a for or for each block in an array comprehension or generator expression. interface comprehens...
...tents: string | null; } an xml processing instruction. builder objects the optional builder parameter to reflect.parse() makes it possible to construct user-specified data from the parser, rather than the default node objects. builder objects may contain any of the callback methods described in this section. each callback can produce any custom, user-defined datatype; these are referred to below as customexpression, customstatement, etc. note: because this library uses null for optional nodes, it is recommended that user-defined datatypes not use null as a representation of an ast node. if the loc option is enabled (see the reflect.parse() options above), then each callback is provided with the source location information of the parsed node as an extra parameter. all builder callbacks...
Split object
e to that function, then by calling it, it is indirectly accessing tab tb's window. the function object carries a reference to the window, via the scope chain. to further complicate matters, a and b are in the same security domain, so security checks between them automatically succeed. this makes the problem resistant to a wrapper-based approach.) older versions of firefox accomplished this by blowing away all window properties every time a user navigated to another page, then reusing the window. each page, even on back, had to load from scratch. this was slow. circa firefox 1.5, the decision was made to cache layout information and javascript state across navigation. a new approach for window was needed. security privileges are granted to js code on the basis of the scope chain of ...
...ner window properties is fast. the outer window object is the object returned by window.open. it represents the window or tab itself and survives as the user navigates in that window or tab. the window object's jsclass.resolve hook ensures that properties of the inner object are visible via the outer object, if the running code has the right principals to access them. this privilege check may be slow. see wikimo:gecko:splitwindow and bug 296639 for more discussion. see also http://groups.google.com/group/mozil...81825b338fb84f details this section describes split objects as a feature of the jsapi. it catalogues (and tries to explain) the subtle ways in which split objects affect spidermonkey's behavior. split objects are only useful for implementing objects that will be on the scope chain of ...
...in which split objects affect spidermonkey's behavior. split objects are only useful for implementing objects that will be on the scope chain of functions. spidermonkey assumes that inner and outer objects are dangerous in two different and complementary ways. inner objects are dangerous because they have fast property accessors that do not perform security checks. therefore, no function may be allowed to see an inner object that has different jsprincipals. apart from the security issue, if one page directly or indirectly gets a reference to another page's window object, that window object must appear to behave like the outer window and navigate from page to page. spidermonkey arranges this by not allowing js code to see inner objects at all. to enforce this rule: if this would evaluate to ...
...n a function's scope chain. again, spidermonkey enforces a slightly stronger rule: outer objects may never appear in a scope chain at all, except when put there by an explicit c-level jsapi call (to js_setparent or equivalent). (several objects, such as window.location and window.navigator, are intentionally parented to the outer window object using such apis.) to enforce this rule: apis that allow the caller to pass a scope object always check that object first and fail if any outer objects are on its scope chain. in the spirit of this rule, js_getscopechain should always return an inner object. but there is a special case when js_getscopechain is called on a jscontext in which no code is currently running. by convention, the context's global object is returned in this case. for consist...
TPS Tests
volving the same or different profiles, so that one test file may be used to test the effect of syncing and modifying a common set of data (from a single sync account) over a series of different events and clients. set up an environment and run a test to run tps, you should create a new firefox account using a restmail.net email address (strictly speaking, restmail isn't required, but it will allow tps to automatically do account confirmation steps for you. 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 ...
... to unregister the devices with fxa. this is an implementation detail, but if you work with tps for any amount of time you will almost certainly see cleanup-profile1 or similar in the logs. that's what that phase is doing, it does any necessary cleanup for the phase, primarially unregistering the device associated with that profile. tps tests tend to be broken down into three sections, in the following order (we'll cover these out of order, for the sake of simplicity) phase declarations (mandatory). data definitions/asset list (optional, but all current tests have them). phase implementation (mandatory) it's worth noting that some parts of tps assume that it can read the number off the end of the phase or profile to get to the next one, so try to stick to the convention established...
... relevant to sync. the format of these asset lists vary somwhat depending on asset type. bookmarks passwords history tabs form data prefs test phases 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', [ [...
...ch are parameters to pass to the function. each type of asset list has a number of built-in functions you can call, described in the section on asset lists; there are also some additional built-in functions. built-in functions sync(options) initiates a sync operation. if no options are passed, a default sync operation is performed. otherwise, a special sync can be performed if one of the following are passed: sync_wipe_server, sync_wipe_client, sync_reset_client. this will cause tps to set the firstsync pref to the relevant value before syncing, so that the described actionwill take place logger.loginfo(msg) logs the given message to the tps log. logger.asserttrue(condition, msg) asserts that condition is true, otherwise an exception is thrown and the test fails. logger.assertequa...
Mozilla Projects
thunderbird. it provides a number of functions and capabilities, including: mccoy mccoy uses xulrunner which is bound to break, for details see this post. mozilla calls mccoy a "simple system" which is a clear sign that something probably is not working, and indeed, is not. mccoy is an application that allows add-on authors to provide secure updates to their users. applications periodically look for and install updates to their add-ons. it's important that the update information retrieved has not been tampered with since being written by the add-on author. specifically, it focuses on the process of digitally signing update manifests so the applications can verify the integrity of a manife...
... certificate management (including issuance and revocation), and other common pki functions. pork pork is a c++ parsing and rewriting tool chain. the core of pork is a c++ parser that provides exact character positions for the start and end of every ast node, as well as the set of macro expansions that contain any location. this information allows c++ to be automatically rewritten in a precise way. the inputs driving the rewriting would normally be provided by a program-analysis system outside of pork. (see dehydra, treehydra). rhino rhino is an open-source implementation of javascript written entirely in java. it is typically embedded into java applications to provide scripting to end...
...found on the thread sanitizer wiki. tps tests tps is an end to end test for sync. it's name stands for testing and profiling tool for sync (which is a misnomer, since it doesn't do any profiling), and it should not be confused with the similarly named tests in talos. web replay web replay allows firefox content processes to record their behavior, replay it later, and rewind to earlier states. replaying processes preserve all the same js behavior, dom structures, graphical updates, and most other behaviors that occurred while recording. webreplayroadmap this document describes existing, planned, and potential features for the firefox ...
...and rewind to earlier states. replaying processes preserve all the same js behavior, dom structures, graphical updates, and most other behaviors that occurred while recording. webreplayroadmap this document describes existing, planned, and potential features for the firefox developer tools that are based on web replay, along with their ui. the low level, yet flexible architecture (described here) provides an extremely powerful platform for implementing debugging and analysis features. we would like to use web replay to radically improve not just the debugging experience but the entire web development experience. to that end, this document will be revised over time as we find new and better ways of helping developers. ...
Signing Mozilla apps for Mac OS X
ificate. while testing and debugging for test and debug purposes, the easiest way to get a signing certificate is to use apple's keychain feature to create one. there are good instructions available under "to use the certificate assistant to create a self-signed signing identity". for release creating a developer id requires a paid apple developer account. once you have that you can do the following to create your id: open the developer certificate utility. click "certificates" from the left hand menu. click "create a certificate" at the top right corner select the "developer id" radio button and uncheck the "developer id installer certificate" box. click "create" and follow the instructions in the wizard. it will guide you through creating a private key, certificate signing reques...
...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. ...
... 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. the path specified must be a full path; it's usually something similar to /users/username/library/keychains/keychain-name.keychain. --resource-rules /path/to/coderesources specifies a file to use when generating the rules to be applied to the code signing. when you're signing mozilla applications with v1 signatures, you'll need to specify a custom co...
...must be the same as the value of the cfbundleidentifier specified in your application's info.plist file. leaf[subject.ou]: this needs to be the subject ou of your developer id. you can find it by running this command in the terminal: openssl x509 -text -noout -inform der -in devloperid_application.cer | grep subject putting it all together, you'll wind up using a command similar to the one below to sign your app. you'll of course need to change the signing id, keychain, bundle path, and requirements. codesign -s mac-testing -fv \ --keychain /users/user/library/keychains/mykeychain.keychain \ --resource-rules ./application.app/contents/_codesignature/coderesources \ --requirements '=designated => identifier "org.you.yourapp" and ( (anchor apple generic and cert...
Components.utils.Sandbox
x 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.nsiprincipal); content principal you can specify a ...
... var sandbox = components.utils.sandbox(principal); null principal you can create a null principal using code like: cc["@mozilla.org/nullprincipal;1"].createinstance(ci.nsiprincipal); from firefox 37 onwards, you can also specify the null principal by simply passing null as the principal argument. options the constructor accepts an optional parameter. this parameter is an object with the following optional properties: freshzone if true creates a new gc region separate from both the calling context's and the sandbox prototype's region. addons creating sandboxes whose expected lifetime is tied to that of a content window object will want to use samezoneas instead. samezoneas a javascript object in whose garbage collection region the sandbox should be created in. this helps to im...
... freshzone if true creates a new gc region separate from both the calling context's and the sandbox prototype's region. addons creating sandboxes whose expected lifetime is tied to that of a content window object will want to use samezoneas instead. samezoneas a javascript object in whose garbage collection region the sandbox should be created in. this helps to improve memory usage by allowing sandboxes to be discarded when that zone goes away. content scripts should pass the window they're running in as this parameter, in order to ensure that the script is cleaned up at the same time as the content itself. sandboxname a string value which identifies the sandbox in about:memory (and possibly other places in the future). this property is optional, but very useful for tracking me...
...able in the sandbox. default: false. wantglobalproperties an array of strings. each string is the name of an object that you want to make available as a global to code running in the sandbox. the exception is "-promise": the promise constructor is available by default for sandboxes, and you use this option to remove it from the sandbox. note that "-promise" is removed in firefox 37. ...
XPCShell Reference
hermore, 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 toggles the javascript strict option on and off. by default it is off. -v version this allows you to specify a specific version of js to use, and should be set to an integral value specified by the jsversion enumerated type. for instance, specifying -v 180 will set the interpreter to use javascript version 1.8. -w (lower case) this option turns on javascript warnings. -w (upper case) this turns off javascript warnings. the last option listed is the one that takes effect. -x t...
...n on and off. by default it is off. [scriptfile] this is the file name of the script to execute. [scriptarg…] these are arguments to be passed to the script. these arguments are only passed to “scriptfile” and not the scripts designated by –f options. these arguments appear on the global property arguments. ...
...criptarg…] these are arguments to be passed to the script. these arguments are only passed to “scriptfile” and not the scripts designated by –f options. these arguments appear on the global property arguments. for instance, assume that you have a file called test.js with the following contents: for (prop in arguments) { print(prop + "=" + arguments[prop]); } entering the following at the command line should produce the following output: $ xpcshell test.js this is a test 0=this 1=is 2=a 3=test xpcshell extensions once you execute xpcshell without a script you'll be at the js> command line. the following are some useful functions that can be invoked from the command line: clear(object) clear() removes all properties from an object. for example, if you created ano...
...() removes all properties from an object. for example, if you created anobject with a property named value and then called clear(anobject), the property value would no longer exist. gc(heapdumpfilename) gc() will invoke garbage collection. it takes an optional argument that can be used to dump the heap to. if specified, it should equate to a valid filename. load(scriptfilename) load() allows you to load and run a script from the command line. for example, load("myscript.js") will execute the script myscript.js in the current directory. print(obj1, obj2, …) print() is useful to print something to the screen. it dumps whatever is passed to the screen, putting spaces between arguments and appending a newline at the end. an example print(1, 2, 3) will print 1 2 3<newline>. du...
Language bindings
jects from that language (where access means reading/writing/creating xpcom objects as well as calling methods on them). exposes modules written in the bound language as xpcom objects, thereby enabling all other languages for which xpcom bindings exist to access these modules. since the xpcom layer itself is written in c/c++, its api can be accessed out-of-the-box using c or c++. in order to allow any other language to use the xpcom api, a bridging layer is required. the following bridging layers are currently available: components objectthe components object is the object through which xpconnect functionality is reflected into javascript. the components object is actually a native instance of the nsixpccomponents interface which is reflected into javascript as a top level object us...
...javaxpcom is not actively maintained.plxpcomplxpcom (perl xpcom) provides language bindings letting you use xpcom from perl code. the resources here provide information about this language binding and how to use it.pyxpcompyxpcom...
...or communication between java and xpcom, such that a java application can access xpcom objects, and xpcom can access any java class that implements an xpcom interface. javaxpcom is not actively maintained.plxpcomplxpcom (perl xpcom) provides language bindings letting you use xpcom from perl code. the resources here provide information about 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 us...
...en 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. ...
NS ConvertASCIItoUTF16 external
methods constructors void ns_convertasciitoutf16_external(const nsacstring&) - source parameters nsacstring& astr void ns_convertasciitoutf16_external(co...
... parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string...
... parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if n...
... prbool operator!=(const prunichar*) const - source parameters prunichar* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* aasciistring lowercaseequalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32...
NS ConvertUTF8toUTF16 external
methods constructors void ns_convertutf8toutf16_external(const nsacstring&) - source parameters nsacstring& astr void ns_convertutf8toutf16_external(cons...
... parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string...
... parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if n...
... prbool operator!=(const prunichar*) const - source parameters prunichar* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* aasciistring lowercaseequalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32...
PromiseFlatString (External)
methods get prunichar* get() const - source operator= nsstring_external& operator=(const nsstring_external&) - source parameters nsstring_ex...
... parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string...
... parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if n...
... prbool operator!=(const prunichar*) const - source parameters prunichar* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* aasciistring lowercaseequalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32...
nsAString (External)
methods beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source returns the length, beginning, and end of a string in one operation. parameters prunichar** begin prunichar** end prunichar* beginreading() const - source endreading prunichar...
...parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if not found parameters...
...parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(p...
...tor!= prbool operator!=(const nsastring&) const - source parameters nsastring& other prbool operator!=(const prunichar*) const - source parameters prunichar* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* aasciistring lowercaseequalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32) c print32 find(const nsastring&, pruint32, print32 (*)(co...
nsAutoString (External)
methods get prunichar* get() const - source operator= nsstring_external& operator=(const nsstring_external&) - source parameters nsstring_ex...
... parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string...
... parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if n...
... prbool operator!=(const prunichar*) const - source parameters prunichar* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* aasciistring lowercaseequalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32...
nsDependentString external
methods constructors void nsdependentstring_external() - source void nsdependentstring_external(const prunichar*, pruint32) - source parameters prunicha...
... parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string...
... parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if n...
... prbool operator!=(const prunichar*) const - source parameters prunichar* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* aasciistring lowercaseequalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32...
nsDependentSubstring external
methods...
... parameters char aasciistring find(const nsastring&, print32 (*) print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occu...
... parameters char aasciistring find(const nsastring&, print32 (*) print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return t...
... prbool operator!=(const prunichar*) const - source parameters prunichar other equalsliteral prbool equalsliteral(const char*) const - source parameters char aasciistring lowercaseequalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char aasciistring find(const nsastring&, print32 (*) print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if not found parameters nsastring astr print32* c ...
nsStringContainer (External)
methods beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source returns the length, beginning, and end of a string in one operation. parameters ...
... parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string...
... parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if n...
... prbool operator!=(const prunichar*) const - source parameters prunichar* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* aasciistring lowercaseequalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32...
nsString external
methods constructors void nsstring_external() - source void nsstring_external(const nsstring_external&) - source parameters nsstring_external& astring ...
... parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string...
... parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if n...
... prbool operator!=(const prunichar*) const - source parameters prunichar* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* aasciistring lowercaseequalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. @return the offset of astr, or -1 if not found parameters nsastring& astr print32 (*)(prunichar*, prunichar*, pruint32...
IAccessibleTable2
returned. 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. selectcolumn() selects a column and unselects all previously selected columns. the behavior should mimic that of the application, but for those applications which do not have a means in the gui to select a full column of cells the behavior should be as follows: first any selected columns in the table are unselected. then the entire column of cells for the specified column is selected. if any of the cells in the selected column span additional columns, the cells in those columns are also selected. hresult selectcolumn( [in] long column ); parameters column 0 based index of the column to be selected. return value e_invalidarg if bad [in] passed. s_...
...he number of row indexes returned; the size of the returned array. return value s_false if there are none, [out] values are null and 0 respectively. s_ok. selectrow() selects a row and unselects all previously selected rows. the behavior should mimic that of the application, but for those applications which do not have a means in the gui to select a full row of cells the behavior should be as follows: first any selected rows in the table are unselected. then the entire row of cells for the specified row is selected. if any of the cells in the selected row span additional rows, the cells in those rows are also selected. hresult selectrow( [in] long row ); parameters row 0 based index of the row to be selected. return value e_invalidarg if bad [in] passed. s_ok. summary() returns the summ...
...ll pointer if the table does not support a summary. return value s_false if there is nothing to return, [out] value is null. s_ok. unselectcolumn() unselects one column, leaving other selected columns selected (if any). the behavior should mimic that of the application, but for those applications which do not have a means in the gui to unselect a full column of cells the behavior should be as follows: the entire column of cells for the specified column is unselected. if any of the cells in the selected column span additional columns, the cells in those columns are also unselected. hresult unselectcolumn( [in] long column ); parameters column 0 based index of the column to be unselected. return value e_invalidarg if bad [in] passed. s_ok. unselectrow() unselects one row, leaving other se...
...n( [in] long column ); parameters column 0 based index of the column to be unselected. return value e_invalidarg if bad [in] passed. s_ok. unselectrow() unselects one row, leaving other selected rows selected (if any). the behavior should mimic that of the application, but for those applications which do not have a means in the gui to unselect a full row of cells the behavior should be as follows: the entire row of cells for the specified row is unselected. if any of the cells in the selected row span additional rows, the cells in those rows are also unselected. hresult unselectrow( [in] long row ); parameters row 0 based index of the row to be unselected. return value e_invalidarg if bad [in] passed. s_ok. see also iaccessibletable iaccessibletablecell ...
nsIAlertsService
topic: "alertfinished" when the alert disappears, "alertclickcallback" if the user clicks the text or "alertshow" (since gecko 22) when the alert is shown. data: the value of the cookie parameter passed into the showalertnotification method. name optional a name for the notification; this is not displayed in the alert. however, certain notification systems (such as growl on mac os x) allow the user to disable alerts by name. this name is used in that configuration panel. on android the name is hashed and used as a notification id. dir optional bidi 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 ...
...lert. 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 notification. var alertsservice = components.classes["@mozilla.org/alerts-service;1"]. getservice(components.interfaces.nsialertsservice); try { alertsservice.showalertnotification("chrome://mozapps/skin/downloads/downloadicon.png", "alert title", "alert text goes here.", ...
... void closealert( in astring name, optional in nsiprincipal principal optional ); parameters name the name of the notification to close. if no name is provided then only a notification created with no name (...
... } else if (atopic == 'alertshow') { console.log('just showed notification'); } else if (atopic == 'alertfinished') { console.log('just alertfinished') } } }; as.showalertnotification('chrome://branding/content/icon64.png', 'stackoverflow - new messages', 'there are ## new messages. click here to focus the tab', true, null, notiflistener, 'stackoverflow notifier'); closealert() closes alerts created by the service. void closealert( in astring name, optional in nsiprincipal principal optional ); parameters name the name of the notification to close. if no name is provided then only a notification created with no name (if any) will be closed. principal the title for the alert. see also alerts and notifications bug 782211 - ...
nsIBrowserHistory
@mozilla.org/browser/nav-history-service;1. ...
... attributes attribute type description count obsolete 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. ...
...p information. it is called by history importing code and is used in the history migration tool. void addpagewithdetails( in nsiuri auri, in wstring atitle, in long long alastvisited ); parameters auri the page that will be added to the history. atitle the title of the page. alastvisited when the page was last visited, in microseconds since the unix epoch. ...
...ge that will be added to the history. atitle the title of the page. alastvisited when the page was last visited, in microseconds since the unix 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() ...
nsIContentSecurityPolicy
calls to this may trigger violation reports when queried, so this value should not be cached. read only. isi...
...calls to this may trigger violation reports when queried, so this value should not be cached. read only. isinitialized boolean set to true when the ...
...calls to this may trigger violation reports when queried, so this value should not be cached. read only. ...
...calls to this may trigger violation reports when queried, so this value should not be cached. read only. isinitialized boolean set to true when the content security policy has been read in and parsed and is ready to enforce. ...
nsIDOMEvent
currenttarget nsidomeventtarget used to indicate the eventtarget whose eventlisteners are currently being processed. this is particularly useful during capturing and bubbling. read only. defaultprevented boolean used to indicate whether preventdefault() has been called for this event. read only. eventphase unsigned short used to indicate which phase of event flow is currently being evaluated. read only. explicitoriginaltarget nsidomeventtarget the explicit original target of the event. if the event was retargeted for some reason other than an anonymous boundary crossing, this will be set to the target before the retargeting occurs. for example, mouse events are retargeted to their parent node when they happen over text nodes (bug 185889), a...
...ent method are modified, all other attributes are left unchanged. void initevent( in domstring eventtypearg, in boolean canbubblearg, in boolean cancelablearg ); parameters eventtypearg specifies the event type. this type may be any event type currently defined in this specification or a new event type. the string must be an xml name. any new event type must not begin with any upper, lower, or mixed case version of the string "dom". this prefix is reserved for future dom event sets. it is also strongly recommended that third parties adding their own events use their own prefix to avoid confusion and lessen the probability of conflicts with other new events. canbubblearg specifies whether or not the event can bubble. cancelablearg specifies whether or not the event's default a...
...reventbubble(); parameters none. preventcapture() note: use stoppropagation() instead. void preventcapture(); parameters none. preventdefault() if an event is cancelable, the preventdefault method is used to signify that the event is to be canceled, meaning any default action normally taken by the implementation as a result of the event will not occur. if, during any stage of event flow, the preventdefault method is called the event is canceled. any default action associated with the event will not occur. calling this method for a non-cancelable event has no effect. once preventdefault has been called it will remain in effect throughout the remainder of the event's propagation. this method may be used during any stage of event flow. void preventdefault(); parameters none. ...
...ative code only!settrusted void settrusted( in boolean atrusted ); parameters atrusted stopimmediatepropagation() prevents other event listeners from being triggered and, unlike stoppropagation() its effect is immediate. void stopimmediatepropagation(); parameters none. stoppropagation() the stoppropagation method is used prevent further propagation of an event during event flow. if this method is called by any eventlistener the event will cease propagating through the tree. the event will complete dispatch to all listeners on the current eventtarget before event flow stops. this method may be used during any stage of event flow. void stoppropagation(); parameters none. ...
nsIDragService
as finished, otherwise the drag has just left the window. firedrageventatsource() obsolete since gecko 43 (firefox 43 / thunderbird 43 / seamonkey 2.40)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. fire a drag event at the source of the drag. this was changed in gecko 43, see the following section. void firedrageventatsource( in unsigned long amsg ); obsolete since gecko 43 parameters amsg one of the ns_dragdrop_* contants which was defined in widget/basicevents.h fire a drag event at the fource of the drag. this is available only from native code since gecko 43. [noscript] void firedrageventatsource( in mozilla::eventmessage aeventmessage ); parameters aeve...
...mnode adomnode, in nsisupportsarray atransferables, in nsiscriptableregion aregion, in unsigned long aactiontype ); parameters adomnode the source node on which the drag gesture was started. atransferables an array of transferables to be dragged. aregion a region containing rectangles for cursor feedback, in window coordinates. aactiontype specified which of copy/move/link are allowed. invokedragsessionwithimage() starts a modal drag session using an image. a 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.
...e aimage, in long aimagex, in long aimagey, in nsidomdragevent adragevent, in nsidomdatatransfer adatatransfer ); parameters adomnode the source node on which the drag gesture was started. atransferables an array of transferables to be dragged. aregion a region containing rectangles for cursor feedback, in window coordinates. aactiontype specified which of copy/move/link are allowed. aimage image object. aimagex x position of image. aimagey y position of image. adragevent the drag gesture event that initiated the drag. adatatransfer a data transfer object that is available on the current drag session. invokedragsessionwithselection() start a modal drag session using the selection as the drag image. the adragevent must be supplied as the current screen coordin...
...n. void invokedragsessionwithselection( in nsiselection aselection, in nsisupportsarray atransferablearray, in unsigned long aactiontype, in nsidomdragevent adragevent, in nsidomdatatransfer adatatransfer ); parameters aselection the selection that is to be dragged. atransferablearray an array of transferables to be dragged. aactiontype specified which of copy/move/link are allowed adragevent the drag gesture event that initiated the drag. adatatransfer a data transfer object that is available on the current drag session. startdragsession() tells the drag service to start a drag session. this is called when an external drag occurs void startdragsession(); parameters none. suppress() increase dragging suppress level by one. this disables dragging if it is not...
nsIFrameScriptLoader
idl file: mozilla-central/source/dom/base/nsimessagemanager.idl inherits from: nsisupports this interface is used to load frame scripts. methods void loadframescript(in astring aurl, in boolean aallowdelayedload, [optional] in boolean aruninglobalscope) void removedelayedframescript(in astring aurl); jsval getdelayedframescripts(); loadframescript() load a script in the remote frame. frame scripts are loaded as soon as loadframescript() is called. if this function is called on a chromemessagebroadcaster (for example, a global frame message manager or a window message manager) then: loadframescript() will load the frame script independently into each applicable frame: every open fra...
...n as loadframescript() is called. if this function is called on a chromemessagebroadcaster (for example, a global frame message manager or a window message manager) then: loadframescript() will load the frame script independently into each applicable frame: every open frame in the given window for the window message manager, or every frame in every window for the global message manager if aallowdelayedload is true, then the script will also be loaded into any applicable new frames opened after the loadframescript() call. otherwise it will only be loaded into frames that exist at the time of the call. if this function is called on a chromemessagesender: it will load the frame script only into this chromemessagesender's frame aallowdelayedload should always be true. it's possible tha...
...on't get reloaded when the user navigates. if you want a frame script to do something whenever a new document is loaded, you can listen for the document-element-inserted notification. parameters name type description aurl string url for the script to load. aurl must be the absolute url. data: urls are also supported. for example data:,dump("foo\n"); aallowdelayedload boolean if true, this flag means that the frame script will be loaded into any new frames opened after the loadframescript() call, until removedelayedframescript() is called for that script. aruninglobalscope boolean optional, defaults to false. by default, frame scripts each have their own scope, so they can declare global variables without causing confl...
...re global variables without causing conflicts with any other frame scripts. if present and set to true, this flag switches off that behavior, meaning that the script's scope is shared with any other frame scripts in the same frame that have also set the flag. removedelayedframescript() removes aurl from the list of scripts which support delayed load. this cancels the effect of the aallowdelayedload flag, meaning that the loader will no longer load the script into new frames. if you used aallowdelayedload, you should call this as part of your cleanup (for example, when your add-on is disabled or uninstalled). parameters name type description aurl string url for the script to remove. getdelayedframescripts() returns all delayed scripts that w...
nsIIOService
spects the scheme in order to delegate creation of the new uri to the appropriate protocol handler). note: nsiioservice may only be used from the main thread. ...
...type description offline boolean returns true if networking is in "offline" mode. when in offline mode, attempts to access the network will fail (although this does not necessarily correlate with whether there is actually a network available -- that's hard to detect without causing the dialer to come up). observers will be notified of changes to this attribute. methods allowport() checks if a port number is banned. this involves consulting a list of unsafe ports, corresponding to network services that may be easily exploitable. if the given port is considered unsafe, then the protocol handler (corresponding to ascheme) will be asked whether it wishes to override the io service's decision to block the port. this gives the protocol handler ultimate control over its ow...
...ding to network services that may be easily exploitable. if the given port is considered unsafe, then the protocol handler (corresponding to ascheme) will be asked whether it wishes to override the io service's decision to block the port. this gives the protocol handler ultimate control over its own security policy while ensuring reasonable, default protection. is similar to nsiprotocolhandler.allowport(). boolean allowport( in long aport, in string ascheme ); parameters aport the port to check ascheme the scheme for the protocol handler that could override the ioservice's decision. return value true if the port is allowed, false otherwise. extractscheme() utility to extract the scheme from a url string, consistently and according to spec (see rfc 3986). note: most url pa...
... parameters aspec the spec for the desired uri. aorigincharset the charset for the uri. may be null. abaseuri the base uri for the spec. may be null. if aspec is an absolute url, this parameter is ignored. return value an nsiuri object corresponding to aspec and abaseuri. exceptions thrown ns_error_malformed_uri if uri does not begin with a valid scheme (as defined by rfc 3986) followed by a colon. remarks note: the proper way to create a new nsiuri is with newuri() method defined above. do not create a new nsiuri with createinstance(). this was a frozen interface see bug 157131 for details. from gecko 2.0 interfaces are no longer frozen. see also rfc 3986 ...
nsILocalFile
opennsprfiledesc(in long flags, 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 syst...
...nored 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 intended to be used whenever a nsilocalfile needs to be serialized to disk and later recovered. this string is not intended for display to users. note: the value of the followlinks attribute is not encoded in the persistent descriptor. constants constant value description delete_on_close 0x80000000 optional parameter used by opennsprfiledesc(). methods native code only! appendrelativenativepath appends a relative, native character encoding, path to the current path of the nsilocalfile object. void appendrelative...
...t. prfiledescstar opennsprfiledesc( in long flags, in long mode ); parameters flags the pr_open() flags from nsprpub/pr/include/prio.h, plus optionally delete_on_close. delete_on_close may be implemented by removing the file (by path name) immediately after opening it, so beware of possible races; the file should be exclusively owned by this process. a bitwise combination of the following open flags: pr_rdonly open for reading only. pr_wronly open for writing only. pr_rdwr open for reading and writing. pr_create_file if the file does not exist, the file is created. if the file exists, this flag has no effect. pr_append the file pointer is set to the end of the file prior to each write. pr_truncate if the file exists, its length is truncated to 0. pr_sync if set...
...n; while ((n = pr_read(fd, buf, sizeof(buf))) > 0) { // do something with n-byte block of data from file... } if (n < 0) rv = ns_error_unexpected; pr_close(fd); return rv; } reveal() ask the operating system to open the folder which contains this file or folder. this routine only works on platforms which support the ability to open a folder. see the note in the remarks below. void reveal(); parameters none. setrelativedescriptor() initializes the file to the location relative to fromfile using a string returned by getrelativedescriptor(). void setrelativedescriptor( in nsilocalfile fromfile, in acstring relativedesc ); parameters fromfile the file to which the descriptor is relative. relativedesc the relative descriptor obtained from getrelativedes...
nsILocalFileMac
t) rather than just the size of the data fork as returned by getfilesize() read only. filetype ostype file type and creator attributes. native code only! constants constant value description current_process_creator 0x8000000 use with setfiletype() to specify the signature of current process. obsolete since gecko 2.0 methods native code only!getcfurl note: observes the state of the followlinks attribute. if the file object is an alias and followlinks is true, returns the target of the alias. if followlinks is false, returns the unresolved alias file. note: supported only for xp_macosx. cfurlref getcfurl(); parameters none. return value the cfurlref of the file object. the caller is responsible for calling cfrelease() on it. native code only!getfsref note: observes the state of th...
... attribute. if the file object is an alias and followlinks is true, returns the target of the alias. if followlinks is false, returns the unresolved alias file. note: supported only for xp_macosx. cfurlref getcfurl(); parameters none. return value the cfurlref of the file object. the caller is responsible for calling cfrelease() on it. native code only!getfsref note: observes the state of the followlinks attribute. if the file object is an alias and followlinks is true, returns the target of the alias. if followlinks is false, returns the unresolved alias file. note: supported only for xp_macosx. fsref getfsref(); parameters none. return value the fsref of the file object. native code only!getfsspec note: observes the state of the followlinks attribute. if the file object is an alias and fo...
...fsspec getfsspec(); parameters none. return value the fsspec of the file object. native code only!inittoappwithcreatorcode obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)this feature is obsolete. ...
...fsspec getfsspec(); parameters none. return value the fsspec of the file object. native code only!inittoappwithcreatorcode obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)this feature is obsolete. ...
nsIMemoryReporter
xpcom/base/nsimemoryreporter.idlscriptable reports memory usage information for a single area of the software. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) any piece of code that wishes to allow its memory use to be monitored may create an nsimemoryreporter object and then register it by calling nsimemoryreportermanager.registerreporter(). once that has been done, the reporter will be found by any client accessing the enumerator returned by nsimemoryreportermanager.enumeratereporters(). this includes the about:memory page. note: this interface is undergoing heavy development, and is subject to rapid changes. attributes attribute type description ...
...nits indicated by the units attribute. read only. note: this attribute was called memoryused prior to gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4), and its type was long long. description autf8string a human-readable description of this memory usage report. read only. kind print32 the memory kind, one of the memory reporter kind constants below. read only. path autf8string the path that this memory usage should be reported under. paths are delimited with '/' characters to allow a hierarchy of memory to be displayed in about:memory. as of gecko 6.0, the path should start with "explicit/" if the memory report accounts for all memory reported under sub-paths. read only. process acstring the name of the proces...
...irectly by os calls e.g. mmap, virtualalloc, vm_allocate etc. kind_heap 1 allocated by the heap allocator, e.g. malloc, new etc. kind_other 2 an allocation that does not fit into another kind category. unit type constants requires gecko 7.0(firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) the amount reported by a memory reporter may use one of the following units. constant value description units_bytes 0 the amount is specified as a number of bytes. units_count 1 the amount is an instantaneous count of things currently in existence. for example, the number of tabs currently open. units_count_cumulative 2 the amount contains the number of times some event has occurred since the applicatio...
...d up. for example, the number of times the user has opened a new tab. the amount returned must never decrease over the lifetime of the application. units_percentage 3 the amount contains a fraction that should be expressed as a percentage. note: the amount field should be given a value 100 times the actual percentage; this number will be divided by 100 when shown. this allows a fractional percentage to be shown even though amount is an integer. for example if the actual percentage is 12.34%, amount should be 1234. see also nsimemoryreportermanager ...
nsINavBookmarksService
toolbarfolder long long the item id of the personal toolbar folder. read only. note: renamed from toolbarroot in gecko 1.9 unfiledbookmarksfolder long long the item id of the unfiled bookmarks folder. read only. constants constant value description default_index -1 this is the default index; this value should be used for apis that allow passing in an index where the index is not known or is not required to be specified, such as when appending an item to a folder. type_bookmark 1 this is an index for type "bookmark". type_folder 2 this is an index for type "folder". type_separator 3 this is an index for type "separator". type_dynamic_container 4 this is an index for type...
...refox 3) saves the current bookmarks hierarchy to a bookmarks.html file. void exportbookmarkshtml( in nsifile file ); parameters file the nsifile to export the bookmarks to. getbookmarkedurifor() this method is used to see if the given uri is bookmarked, or any page that redirected to it is bookmarked. for example, if i bookmark "mozilla.org" by manually typing it in, and follow the bookmark, i will get redirected to "www.mozilla.org". logically, this new page is also bookmarked. this function, if given "www.mozilla.org", will return the uri of the bookmark, in this case "mozilla.org". note: will only return bookmarks in the first 3 levels of redirection (1 -> 2 -> 3 -> auri). nsiuri getbookmarkedurifor( in nsiuri auri ); parameters auri the uri that needs to b...
...getfolderidforitem() this method retrieves the parent folder's id for an item. long long getfolderidforitem( in long long aitemid ); parameters aitemid the item whose parent folder's id is to retrieved. return value returns the parent folder's id for the given item. getfolderreadonly() this method checks whether a folder is marked as read-only. if this is set to true, ui will not allow the user to add, remove, or reorder children in this folder. the default for all folders is false. note: this does not restrict api calls, only ui actions. boolean getfolderreadonly( in long long aitemid ); parameters aitemid the item id of the folder. return value returns true if the folder is marked as read-only, otherwise returns false. getfoldertitle() obsolete ...
...sinavbookmarkobserver.onendupdatebatch(). void runinbatchmode( in nsinavhistorybatchcallback acallback, in nsisupports auserdata ); parameters acallback nsinavhistorybatchcallback interface to call. auserdata opaque parameter passed to nsinavbookmarksbatchcallback. setfolderreadonly() this method sets or unsets the readonly flag from a folder. if this is set to true, ui will not allow the user to add, remove, or reorder children in this folder. the default for all folders is false. note: this does not restrict api calls, only ui actions. void setfolderreadonly( in long long afolder, in boolean areadonly ); parameters afolder the item-id of the folder. areadonly the read-only state. setfoldertitle() obsolete since gecko 1.9 (firefox 3) ...
nsIPromptService
all flags are defined as unsigned long constants and can be accessed as components.interfaces.nsipromptservice.flagname from javascript and as nsipromptservice::flagname from c++. button position flags on linux and mac, button 2 is on the left of the prompt, while buttons 1 and 0 are on the right. on windows and os/2, t...
...pt. it typically has the label "ok", "yes", or "save". button_pos_1 256 this is the button used to cancel the prompt. it typically has the label "cancel" or "no". it is equivalent to pressing the escape key (or cmd+. on the mac), or closing the window through the os controls. button_pos_2 65536 this button can be used to give the user a choice of options, but still allowing the user to cancel the prompt. for instance, it might have the label "don't save". button title flags these flags are used along with button position flags to set the labels of buttons in the prompt. constant value description button_title_ok 1 these flags are used to select standard labels from the user's current locale. button_title_cancel 2 ...
...fied (see button default flags). a button may use a predefined title, specified by one of the button title flags values. each title value can be multiplied by a position value to assign the title to a particular button. if button_title_is_string is used for a button, the string parameter for that button will be used. if the value for a button position is zero, the button will not be shown. the following example creates a dialog with an ok button and a custom button description. abuttonflags = (button_pos_0) * (button_title_ok) + (button_pos_1) * (button_title_is_string) + button_pos_1_default; confirmex always returns 1 if the user closes the window using the close button in the titlebar! bug 345067 print32 confirmex( in nsidomwindow aparent, in wstring adialogtitle, in wstring at...
...kmsg, inout boolean acheckstate ); parameters aparent the parent window for the dialog. if set to null the parent window will be nsiwindowwatcher.activewindow. adialogtitle text to appear in the title of the dialog. atext text to appear in the body of the dialog. abuttonflags abuttonflags is a combination of button flags as described in using the button flags below. abutton0title caption displayed for button 0 if(button_title_is_string*button_title_pos_0) flags are set in abuttonflags abutton1title caption displayed for button 1 if(button_title_is_string*button_title_pos_1) flags are set in abuttonflags abutton2title caption displayed for button 2 if(button_title_is_string*button_title_pos_2) flags are set in abuttonflags acheckm...
nsIRequest
error status associated with the request. read only. constants various load flags which may be or'd together. constant value description load_normal 0 no special load flags. load_background 1 << 0 do not deliver status notifications to the nsiprogresseventsink, or keep this load from completing the nsiloadgroup it may belong to. the following flags control the flow of data into the cache. constant value description inhibit_caching 1 << 7 this flag prevents caching of any kind. it does not, however, prevent cached content from being used to satisfy this request. inhibit_persistent_caching 1 << 8 this flag prevents caching on disk (or other persistent media), which may be needed to preser...
... value description inhibit_caching 1 << 7 this flag prevents caching of any kind. it does not, however, prevent cached content from being used to satisfy this request. inhibit_persistent_caching 1 << 8 this flag prevents caching on disk (or other persistent media), which may be needed to preserve privacy. for https, this flag is set automatically. the following flags control what happens when the cache contains data that could perhaps satisfy this request. they are listed in descending order of precedence. constant value description load_bypass_cache 1 << 9 force an end-to-end download of content data from the origin server. this flag is used for a shift-reload. load_from_cache 1 << 10 load from the cache...
...force an end-to-end download of content data from the origin server. this flag is used for a shift-reload. load_from_cache 1 << 10 load from the cache, bypassing protocol specific validation logic. this flag is used when browsing via history. it is not recommended for normal browsing as it may likely violate reasonable assumptions made by the server and confuse users. the following flags control the frequency of cached content validation when neither load_bypass_cache or load_from_cache are set. by default, cached content is automatically validated if necessary before reuse. note: these flags are intended for normal browsing, and they should therefore not apply to content that must be validated before each use. consider, for example, a http response with a "cache-contro...
...ust 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 nsistreamlistener must not call ondataavailable anymore after cancel has been called. note: most nsirequest implementations expect astatus to be a failure code; however, some implementations may allow astatus to be a success code such as ns_ok. in general, astatus should be a failure code. void cancel( in nsresult astatus ); parameters astatus the reason for canceling this request. ispending() indicates whether the request is pending. ispending is true when there is an outstanding asynchronous event that will make the request no longer be pending. requests do not necessarily start ...
nsISelection2
ed gecko 1.8 obsolete gecko 8.0 inherits from: nsiselection last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) in gecko 8.0 this interface was merged into the nsiselectionprivate interface. ...
...read only. methods getrangesforinterval() retur...
...e type description type short returns the type of the selection (see nsiselectioncontroller for available constants). read only. methods getrangesforinterval() return array of ranges intersecting with the given dom interval. void getrangesforinterval( in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, out pruint32 resultcount, [retval, array, size_is(resultcount)] out nsidomrange results ); parameters beginnode beginoffset endnode endoffset these four parameters represent the range to compare against the selection. allowadjacent specifies whether the returned ranges are allowed to touch the input range rather than merely overlapping it. resultcount returns th...
...nput range rather than merely overlapping it. resultcount returns the number of ranges that overlap (or touch) the input range. results returns the ranges that overlap (or touch) the input range. native code only!getrangesforintervalcomarray void getrangesforintervalcomarray( in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, in rangearray results ); parameters beginnode beginoffset endnode endoffset these four parameters represent the range to compare against the selection. allowadjacent specifies whether the returned ranges are allowed to touch the input range rather than merely overlapping it. results returns the ranges that overlap (or touch) the input range. scrollintoview() sc...
nsISound
ent constants constant value description event_new_mail_received 0 the system receives email. event_alert_dialog_open 1 an alert dialog is opened. event_confirm_dialog_open 2 a confirm dialog is opened. event_prompt_dialog_open 3 a prompt dialog (one that allows the user to enter data, such as an authentication dialog) is opened. event_select_dialog_open 4 a select dialog (one that contains a list box) is opened. event_menu_execute 5 a menu item is executed. event_menu_popup 6 a popup menu is shown. event_editor_max_len 7 more characters t...
...r data, such as an authentication dialog) is opened. event_select_dialog_open 4 a select dialog (one that contains a list box) is opened. event_menu_execute 5 a menu item is executed. event_menu_popup 6 a popup menu is shown. event_editor_max_len 7 more characters than the maximum allowed are typed into a text field. methods beep() plays a beep sound. void beep(); parameters none. init() not strictly necessary, but avoids a delay before the first sound. other methods will call init if they need to. void init(); parameters none. play() plays a sound specified by url. void play( in nsiurl aurl ); parameters aurl the url of the sound file to play. pla...
...is not supported on the macintosh. void playsystemsound( in astring soundalias ); parameters soundalias two different types of names are supported: you can specify the name of a system sound provided by the host operating system; for example, if you specify "systemexclamation", you can play the windows alert sound, but it's played only on windows. similarly, if you specify "blow", you can play the mac os x "blow" system sound, but, similarly, it's played only on the macintosh. if you wish to use this method for playing sounds, you should check the platform before you call playsystemsound(). note: this second usage is obsolete starting in gecko 1.9.2. you should instead use playeventsound() instead. typically, it will be more useful to request that appropri...
...g on: _moz_mailbeep the system sound when the system receives email. _moz_alertdialog the system sound when an alert dialog is opened. _moz_confirmdialog the system sound when a confirm dialog is opened. _moz_promptdialog the system sound when a prompt dialog (one that allows the user to enter data, such as an authentication dialog) is opened. _moz_selectdialog the system sound when a select dialog (one that contains a list box) is opened. _moz_menucommand the system sound when a menu item is executed. _moz_menupopup the system sound when a popup menu is shown. ...
nsISupports proxies
obsolete since gecko 12 (firefox 12 / thunderbird 12 / seamonkey 2.9)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. xpcom proxies were a technology which allowed code to make asynchronous or synchronous xpcom calls to a different thread on arbitrary xpcom interfaces. this technology has been removed in firefox 12 because it was very complex and often lead to strange deadlock conditions. ...
...is technology has been removed in firefox 12 because it was very complex and often lead to strange deadlock conditions. it is no longer needed because javascript code can no longer run on arbitrary threads, and compiled code can use compiled runnable to achieve the same effect in a much simpler manner. for more information about alternatives, see making cross-thread calls using runnables. the following interface is now obsolete: nsiproxyobjectmanager. about xpcom proxies a proxy, in this context, is a stub object which enables a method of any class which is derived from nsisupports and has a typelib to be called on any in-process thread. the main reason for nsisupports proxies is that javascript and ui are on a single thread. when one is busy, the other is blocked. a good example of th...
...cess ui elements such as a progress meter or a confirmation dialog. how can a separate non-ui thread act as if it was on the ui thread? herein lays the utility of nsisupports proxies. i believe that other people working on mozilla need similar solutions. in this document, i will try to explain how to use nsisupports proxies. how do i use it? the api has changed in mozilla 1.9, but the prose below hasn't been updated yet. see xpcom/proxy/public/nsiproxyobjectmanager.idl for the updated interface and its documentation. see also . from a users point of view, you need only to look at the nsiproxyobjectmanager. it has two entry points: ns_imethod getproxyforobject(nsieventqueue *destqueue, const nsiid & iid, nsisupports *object, ...
...to you. warning about proxy_async: you must take very special care when using this flag. as soon as the calling function or method exits, there is no guarantee about the data at the location that used to be part of that stack frame. accessing it might even cause a crash. for example: myfoo->bar(&x) ... stack frame goes away ... bar(print32 *x) { ... *x = 0; <----- you will blow up here. } so, given an event queue to execute methods on, and either an nsisupports object that has been created or cid, and a flag, a new nsisupports proxy object will be returned to you. once you have a proxy object, you may use it as if it is the "real" object. all the methods that are in the "real" object are stubbed into the proxy object. when you are finished with a proxy object, you s...
nsITextInputProcessor
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 be updated, i.e., the implementation of this class can be a cushion from the impact of gecko's change. you can create an instance of this interface with the following code: var tip = components.classes["@mozilla.org/text-input-processor;1"]. createinstance(components.interfaces.nsitextinputprocessor); next, you need to get the rights to create composition or dispatch keyboard events with begininputtransaction() or begininputtransactionfortests(): if (!tip.begininputtransaction(window, callback)) { return; } if begininputtransaction() or ...
...ces cannot create composition nor dispatch keyboard events on the window. the second argument, callback, should be an object which implements nsitextinputprocessorcallback or just a function which is the same as nsitextinputprocessorcallback.onnotify(). see the document of nsitextinputprocessorcallback for the detail. next, you can set the composition string or dispatch keyboard events. the following example sets "foo-bar-buzz", "bar" is selected clause to convert, and caret position is the end of the selected clause: // first, sets composition string. tip.setpendingcompositionstring("foo-bar-buzz"); // next, append clauses. tip.appendclausetopendingcomposition("foo-".length, tip.attr_converted_clause); tip.appendclausetopendingcomposition("bar".length, tip.attr_selected_clause); tip.a...
... when there is no composition which was created by the instance and if compositionstart is consumed by web contents, i.e., failed to start new composition, this returns false. otherwise, returns true. how to create keyboardevent instance for nsitextinputprocessor this section describes how to create keyboardevent for arguments of some methods of nsitextinputprocessor. you should/can specify following attribute values at creating a keyboardevent instance. other attributes are always ignored. especially, please note that modifier key states such as shiftkey are also ignored because each instance of nsitextinputprocessor manages modifier state which is modified when keydown() or keyup() is called with modifier key event. type when you use the keyboardevent instance for a call of either ke...
...y); // this activates capslock state. tip.keyup(capslockkey); // this doesn't inactivate capslock state. tip.keyup(capslockkeyonvirtualkeyboard); // this also doesn't inactivate capslock state. tip.keydown(capslockkey); // this inactivates capslock state. tip.keyup(capslockkey); // this doesn't modify capslock state. sharing modifier state during multiple instances sharemodifierstateof() allows to share modifier state between multiple instances: var shiftkey = new keyboardevent("", { key: "shift", code: "shiftleft" }); var ctrlkey = new keyboardevent("", { key: "control", code: "controlleft" }); var altkey = new keyboardevent("", { key: "alt", code: "altleft" }); tip1.keydown(shiftkey); // tip1's shift state becomes active. tip1.keyup(shiftkey); tip2.keydown(ctrlkey); // tip2'...
nsITransport
se() close the transport and any open streams. void close( in nsresult areason ); parameters areason the reason for closing the stream. openinputstream() open an input stream on this transport. nsiinputstream openinputstream( in unsigned long aflags, in unsigned long asegmentsize, in unsigned long asegmentcount ); parameters aflags optional transport specific flags. flags have the following meaning: open_blocking if specified, then the resulting stream will have blocking stream semantics. this means that if the stream has no data and is not closed, then reading from it will block the calling thread until at least one byte is available or until the stream is closed. if this flag is not specified, then the stream has non-blocking stream semantics. this means that if the stream has ...
...ock the calling thread until at least one byte is available or until the stream is closed. if this flag is not specified, then the stream has non-blocking stream semantics. this means that if the stream has no data and is not closed, then reading from it returns ns_base_stream_would_block. in addition, in non-blocking mode, the stream is guaranteed to support nsiasyncinputstream. this interface allows the consumer of the stream to be notified when the stream can again be read. open_unbuffered if specified, the resulting stream may not support readsegments. readsegments is only guaranteed to be implemented when this flag is not specified. asegmentsize if open_unbuffered is not set, then this parameter specifies the size of each buffer segment (pass 0 to use default value). asegmentcount if op...
...unbuffered is not set, then this parameter specifies the maximum number of buffer segments (pass 0 to use default value). return value openoutputstream() open an output stream on this transport. nsioutputstream openoutputstream( in unsigned long aflags, in unsigned long asegmentsize, in unsigned long asegmentcount ); parameters aflags optional transport specific flags. flags have the following meaning: open_blocking if specified, then the resulting stream will have blocking stream semantics. this means that if the stream is full and is not closed, then writing to it will block the calling thread until all of the data can be written or until the stream is closed. if this flag is not specified, then the stream has non-blocking stream semantics. this means that if the stream is full an...
...l block the calling thread until all of the data can be written or until the stream is closed. if this flag is not specified, then the stream has non-blocking stream semantics. this means that if the stream is full and is not closed, then writing to it returns ns_base_stream_would_block. in addition, in non- blocking mode, the stream is guaranteed to support nsiasyncoutputstream. this interface allows the consumer of the stream to be notified when the stream can again accept more data. open_unbuffered if specified, the resulting stream may not support writesegments and writefrom. writesegments and writefrom are only guaranteed to be implemented when this flag is not specified. asegmentsize if open_unbuffered is not set, then this parameter specifies the size of each buffer segment (pass 0 to...
nsIXPCScriptable
constants constant value description want_precreate 1 << 0 want_create 1 << 1 want_postcreate 1 << 2 want_addproperty 1 << 3 want_delproperty 1 << 4 want_getproperty 1 << 5 want_setproperty 1 << 6 want_enumerate 1 << 7 want_newenumerate 1 << 8 indicates that the object wants to have its newenumerate method called...
...no implementor of this interface should ever return flags with this bit set. me...
...no implementor of this interface should ever return flags with this bit set. methods precreate() void precreate( in ns...
...id, in jsvalptr vp ); parameters wrapper cx obj id vp return value ns_success_i_did_something if this method does something. enumerate() prbool enumerate( in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj ); parameters wrapper cx obj return value newenumerate() this method is called when the want_newenumerate flag is set. it allows the object to implement the for..in enumeration in javascript. this is very similar to jsclass.enumerate. prbool newenumerate( in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in pruint32 enum_op, in jsvalptr statep, out jsid idp ); parameters wrapper cx the pointer to the jscontext newenumerate is being called from. obj the pointer to the ...
nsIXULTemplateQueryProcessor
rocessor. the template builder creates the query processor, and there is no other means to retrieve it. a template query is the contents inside a <query> element within the template. the actual syntax 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. the template builder will supply two variables, the reference variable and the member variable to further indicate what part of the datasource is to be examined in addition to the query itself. the reference is always a placeholder for the starting point and the member is always a placeholder for the end points (the results). the reference point is important w...
...variable to use. the member variable may be specified in a similar way using the "member" attribute, or it may be specified in the first <action> body in the template as the value of a uri attribute on an element. a breadth-first search of the first action is performed to find this element. if unspecified, the default value of the reference variable is ?uri. for example, a query might have the following syntax: (?id, ?name, ?url) from bookmarks where parentfolder = ?start this query might generate a result for each bookmark within a given folder. the variable ?start would be the reference variable, while the variable ?id would be the member variable, since it is the unique value that identifies a result. each result will have the four variables referred to defined for it and the values may be...
...domnode arootnode, in boolean aistrusted, in nsixultemplatebuilder abuilder, out boolean ashoulddelaybuilding); void initializeforbuilding(in nsisupports adatasource, in nsixultemplatebuilder abuilder, in nsidomnode arootnode); nsixultemplateresult translateref(in nsisupports adatasource, in astring arefstring); methods addbinding() add a variable binding for a particular rule. a binding allows an additional variable to be set for 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. ...
...is not supported. ns_error_unexpected if generateresults() has already been called. translateref() translate a ref attribute string into a result. this is used as the reference point by the template builder when generating the first level of content. for recursive generation, the result from the parent generation phase will be used directly as the reference so a translation is not needed. this allows all levels to be generated using objects that all implement the nsixultemplateresult interface. this method may be called before initializeforbuilding(), so the implementation may use the supplied datasource if it is needed to translate the reference. nsixultemplateresult translateref( in nsisupports adatasource, in astring arefstring ); parameters adatasource datasource for the data. aref...
nsIAbCard/Thunderbird3
note: this interface has been overhauled completely for thunderbird 3. documentation for the old nsiabcard interface is currently at nsiabcard. the nsiabcard interface is used to represent and manipulate cards in the address book. in a big change from the original nsiabcard, properties are now stored in a hash table instead of as attributes on the interface, allowing it to be more flexible. properties currently supported on the card: names: firstname, lastname phoneticfirstname, phoneticlastname displayname, nickname spousename, familyname primaryemail, secondemail home contact: homeaddress, homeaddress2, homecity, homestate, homezipcode, homecountry homephone, homephonetype work contact. same as home, but with `work' instead of `home' othe...
...larnumbertype jobtitle, department, company _aimscreenname dates: anniversaryyear, anniversarymonth, anniversaryday birthyear, birthmonth, birthday webpage1 (work), webpage2 (home) custom1, custom2, custom3, custom4 notes integral properties: lastmodifieddate popularityindex prefermailformat (see nsiabprefermailformat) boolean properties: allowremotecontent inherits from: nsiabitem method overview nsivariant getproperty(in autf8string name, in nsivariant defaultvalue); [noscript] astring getpropertyasastring(in string name); [noscript] autf8string getpropertyasautf8string(in string name); [noscript] pruint32 getpropertyasuint32(in string name); [noscript] boolean getpropertyasbool(in...
...roperty of the given name. should the property exist, its value will be overwritten. an implementation may impose additional semantic constraints for certain properties. however, such constraints might not be checked by this method. these functions convert values in the same manner as the default implementation of nsivariant. a value must be convertible to a string; if this convention is not followed, consumers of cards may fail unpredictably or return incorrect results. the non-variant functions are marked [noscript] since xpconnect uses magic with nsivariant such that the other functions are not needed, although c++ does need them. void setproperty(in autf8string name, in nsivariant value); [noscript] void setpropertyasastring(in string name, in astring value); [noscript] void setpro...
...name. some properties may not be deleted. however, the implementation will not check this constraint at this method. if such a property is deleted, an error may be thrown when the card is modified at the database level. void deleteproperty(in autf8string name); parameters name the case-sensitive name of the property to set. translateto() translates a card into a specific format. the following types are supported: base64xml xml vcard autf8string translateto(in autf8string atype); parameters atype the type of item to translate the card into. return value a string containing the translated card. exceptions thrown ns_error_illegal_value type not recognized. copy() this function will copy all values from one card to another. void copy(in nsiabcard srccard) pa...
Setting HTTP request headers
itiated by your code explicitly opening an http channel, because of xmlhttprequest activity, an <img> element in content, or even from css. http channels when you deal with http requests and responses, typically you are doing this with an nsihttpchannel. the nsihttpchannel interface has a number of properties and methods, but the method that is of interest to us is setrequestheader. this method allows us to set an http request header. below is some sample code where we set an http header. // adds "x-hello: world" header to the request httpchannel.setrequestheader("x-hello", "world", false); in the example code above we have a variable named httpchannel which points to an object implementing nsihttpchannel. (this variable could have been named anything though.) the setrequestheader method tak...
...tion 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. and once the observer is registered for a topic, it will get notified about the topic by having its observe method called. ...
... be familiar to you. it is the same code we used before, earlier in this article, to add the http request header. the name of this object -- httprequestobserver -- isn't important. we could have named it anything we liked. registering after we've created the observer, we need to register it. in our case, we want to register it for the "http-on-modify-request" topic. we can do this with the code below. var observerservice = cc["@mozilla.org/observer-service;1"] .getservice(ci.nsiobserverservice); observerservice.addobserver(httprequestobserver, "http-on-modify-request", false); the first statement gets the object that will let us register with topics that we want to get notified about. the second statement does the actual registering. we are saying we want http...
... does the actual registering. we are saying we want httprequestobserver to be notified (by calling its observe method) when a "http-on-modify-request" topic takes place (which we know happens just before each http request). unregistering you should unregister the observer on shutdown. failing to do that may cause memory leaks. to unregister the observer use nsiobserverservice.removeobserver as follows: observerservice.removeobserver(httprequestobserver, "http-on-modify-request"); all-in-one example here is a slightly different version of our httprequestobserver object. while the previous version we showed before was good for learning, in an actual real-world application, you'd probably want to code it more like the following. var httprequestobserver = { observe: function(subject, topic, dat...
Storage
omatically as part of system restore functionality. this can result in significantly higher overhead file operation. closing a connection to close a connection on which only synchronous transactions were performed, use the mozistorageconnection.close() method. if you performed any asynchronous transactions, you should instead use the mozistorageconnection.asyncclose() method. the latter will allow all ongoing transactions to complete before closing the connection, and will optionally notify you via callback when the connection is closed. statements this section demonstrates how you can execute sql statements on your database. for a complete reference see mozistoragestatement. creating a statement there are actually two ways to execute a statement. you should choose the right one based ...
... do not put the :boundparametername within apostrophes, because that the binding mechanism does that for you. you can still use this helper object by manually creating the statement wrapper, mozistoragestatementwrapper, which is provided in gecko 1.9.1 and later. using named parameters in c++ is a lot more difficult, so it's generally accepted to use numerical placeholders instead. the example below uses mozistoragestatement.bindint32parameter(). the full list of binding functions can be found with the mozistoragestatement documentation. c++ example: nscomptr<mozistoragestatement> statement; rv = mdbconn->createstatement(ns_literal_cstring("select * from table_name where id = ?1"), getter_addrefs(statement)); ns_ensure_success(rv, rv); rv = statement->bindint...
...ly, and the statement will get each set of bindings bound to it before execution asynchronously. executing a statement you may execute statements either synchronously (which is supported in firefox gecko 1.8 and 1.9) or asynchronously (starting in gecko 1.9.1). if your code needs to work with applications based on gecko 1.8 or 1.9, you should the technique covered in the section synchronously below. otherwise, it's strongly recommended that you use asynchronous execution, for performance reasons. asynchronously gecko 1.9.1 introduced support for asynchronous execution of a statement by calling mozistoragestatement.executeasync() on the statement. multiple statements can be executed in a transaction by calling mozistorageconnection.executeasync() on the connection and passing in an array...
...ct that implements mozistoragestatementcallback. see its documentation for more details on each method. the callback is optional, however, so if you do not want to receive feedback, you can pass nothing. synchronously if you are ok with the possibility of locking up your user interface, or if you are running on a background thread, you can use mozistoragestatement.executestep(). this function allows you to enumerate all the results produced by the statement. as you step through each row, you can obtain each parameter by name through a helper object (mozistoragestatementrow) in javascript ( ) like so: while (statement.executestep()) { let value = statement.row.column_name; } you can create this helper object yourself if it's not available in your version of gecko. see mozistoragestatem...
Using nsIDirectoryService
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. ...
...s 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; javascript: var file = components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsiproperties) .get("profd", components.i...
...perties) .set("myfilename", file); now, if your cost is too high to set all of these properties at once, you can register to be a callback that can provide an nsifile. to do this, you must get the implementation again like above. when you have it, queryinterface for the nsidirectoryservice interface. ...
...der, which implements the getfile callback function: var provider = { getfile : function(prop, persistant) { // return an nsifile }, } components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsidirectoryservice).registerprovider(provider); when the callback is called, it will be passed the string key, and should return an nsifile. the persistant flag allows you to specify if you want the nsdirectoryservice to cache this value. in most cases you would set this to be true. the interfaces for this can be found here. known locations the nsiproperties strings for currently defined locations can be found in: nsdirectoryservicedefs.h nsappdirectoryservicedefs.h nsxulappapi.h content formerly at http://www.mozilla.org/projects/xpco...locations.html ba...
Working with Multiple Versions of Interfaces
ting the interface with iid ns_get_iid(nsiaccessibleretrieval). unfortunately we compiled this in the latest sdk, and so this magic number happens to be: "244e4c67-a1d3-44f2-9cab-cdaa31b68046" whereas, inside firefox 2, the iid it happens to know about is: "663ca4a8-d219-4000-925d-d8f66406b626". and this explains our ns_error_no_interface. fortunately there is a plan of action that we can follow to rectify this. we build construct our xpcom component so that first tries to get the interface by it's new iid, then if that fails, attempts plan b. plan b is simply trying to get the interface by it's older iid. for expository purposes we will do this in two stages; buoyed by the fact that it is the actual route we took. the optimist's solution the first thing we do is replace line 6 above ...
...{ return gethwndb(node); } //new line 6. and then implement plan b. we first dredge out the old interface identifiers from our yea olde firefox 1.5 sdk: static const nsiid iar_iid_old = { 0x663ca4a8, 0xd219, 0x4000, { 0x92, 0x5d, 0xd8, 0xf6, 0x64, 0x06, 0xb6, 0x26 }}; static const nsiid iad_iid_old = {0x8781fc88, 0x355f, 0x4439, { 0x88, 0x1f, 0x65, 0x04, 0xa0, 0xa1, 0xce, 0xb6 }}; then follow the recipe. hwnd gethwndb(nsidomnode *node){ hwnd self = null; nsresult rv; nscomptr<nsicomponentmanager> compmgr; rv = ns_getcomponentmanager(getter_addrefs(compmgr)); if (ns_failed(rv)){ return self; } nscomptr<nsiaccessibleretrieval> refp; rv = compmgr->createinstancebycontractid(accretcid, 0, iar_iid_old, getter_addrefs(refp)); if (ns_failed(rv)){ return self; } nscomptr<n...
...06, 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. ...
... having to cut and paste) i followed the kind advice of mike shaver and did: #define nsiaccessibleretrieval nsiaccessibleretrieval_old #include "accessibility/nsiaccessibleretrieval_old.h" static const nsiid ns_iaccessibleretrieval_iid_old = ns_iaccessibleretrieval_iid; #undef nsiaccessibleretrieval #undef __gen_nsiaccessibleretrieval_h__ #include "accessibility/nsiaccessibleretrieval.h" and following the identical principle for the document interface: #define nsiaccessibledocument nsiaccessibledocument_old #include "accessibility/nsiaccessibledocument_old.h" static const nsiid ns_iaccessibledocument_iid_old = ns_iaccessibledocument_iid; #undef nsiaccessibledocument #undef __gen_nsiaccessibledocument_h__ #include "accessibility/nsiaccessibledocument.h" i even silenced my friend the compil...
Address book sync client design
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 client synchronization logic defers to the server peforming some intelligence in handling duplicate entries for the sync process. 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 by the // uab server. // localrecordid - local unique id, for mobile devices this // is assigned by the mobile device. // crc - crc of the record last time we synced. // flags - operation to apply to this record. add // if it's new, mod if it's ...
...here is a very simple interface to the address book sync component. ...
....idl" [scriptable, uuid(91fdfee1-efbc-11d3-8f97-000073757374)] interface nsiabsyncdriver : nsiabsynclistener { void kickit(); }; as you can see, this is a very simple interface which allows for the starting of the address book sync operation. the interface of greater interest is the address book sync listener. this provides feedback of the current sync operation. this interface is as follows: #include "nsisupports.idl" #include "nsrootidl.idl" #include "nsifilespec.idl" [scriptable, uuid(e0ed29e0-098a-11d4-8fd6-00a024a7d144)] interface nsiabsynclistener : nsisupports { /** * notify the observer that the ab sync authorization operation has begun. * */ void onstartauthoperation(); /** * notify the observer that the ab sync operation has been...
Mail and RDF
warning: the content of this article may be out of date. it was imported from mozilla.org and last updated in 1999. mozilla mail exposes many of it's data structures to rdf through a few datasources. this allows exposure of mailnews-specific data to user interface using rdf templates. you should learn about rdf before reading this document or you will be hopelessly confused. overview of mail rdf graph the root resource for all accounts, folders and messages is the rdf resource named msgaccounts:/. from this resource, you can follow a number of arcs to find servers, folders, and finally messages. eventually we'll probably hang mail filters, annotations, etc, off of nodes in the graph. here is an example of how this might be set up: in this tree-style representation of an ...
...er, and so forth. nsmsgmessagedatasource - answers queries about messages in folders. all rdf properties of a message currently come from the database that backs the containing folder. datasources and the ui mail does not link the ui to datasources in a "traditional" manner. instead of having a singleton datasource that is shared across all ui components, we have per-view datasources. this allows each template-based widget to maintain view/window-specific data with each datasource. for example...??? (sorting? what else do we store?) datasources are created when each window's javascript is loaded by declaring the datasource variables in the source javascript as global variables. in the document's onload= handler the datasources are attached to their respective widgets by setting the data...
...ers update ui. an aside: rational behind the design after reviewing this design, it might seem unnecessary to have the double-levels of notification/registration. why can't folders directly notify the rdf content observers when things change? here is the rational behind this design: it keeps all rdf datasource-related code in one place and out of the messages and folders themselves. this allows the mail code to be mostly free of rdf. the actual dependancies on rdf are small, so it makes sense to keep rdf out of folders and messages. there should be a non-rdf mechanism for folder change notification. there are times (for example, from javascript/xul) where we want folder notifications that have nothing to do with rdf. requring these listeners to use rdf would be unnecessarily burdening...
.... there are times (for example, from javascript/xul) where we want folder notifications that have nothing to do with rdf. requring these listeners to use rdf would be unnecessarily burdening them with an unnecessary api. the folders or the mail session would have to know about every rdf observer on each datasource. this means the folder would have to notify each of those observers. this design allows each datasource to manage its own observers, and lets each mail session manage a list of folder listeners without necessarily knowing that some of these listeners are rdf-related. please comment ! alec flett last modified: thu oct 7 11:33:42 pdt 1999 ...
The libmime module
class is responsible for parsing itself, and/or handing the input data off to one of its child objects. the definition of these classes is somewhat idiosyncratic and consists of an internally defined object system, instead of c++. there is one header file and one source file for each class (for example, the mimeinlinetext class is defined in "mimetext.h" and "mimetext.c".) each header file follows the following boiler-plate form: typedefs these come first to avoid circular dependencies. typedef struct foobarclass foobarclass; typedef struct foobar foobar; class declaration theis structure defines the callback routines and other per-class data of the class defined in this module. struct foobarclass { parentclass superclass; ...any callbacks or class-va...
...type of an instance by comparing the value of its class pointer with the address of this variable.) extern foobarclass foobarclass; instance declaration theis structure defines the per-instance data of an object, and a pointer to the corresponding class record. struct foobar { parent parent; ...any instance variables... ...
...ses) and then we define the class object using the mimedefclass macro: #include "foobar.h" #define mime_superclass parentlclass mimedefclass(foobar, foobarclass, foobarclass, &mime_superclass); the definition of mime_superclass is just to move most of the knowlege of the exact class hierarchy up to the file's header, instead of it being scattered through the various methods; see below. method declarations we will be putting function pointers into the class object, so we declare them here. they can generally all be static, since nobody outside of this file needs to reference them by name; all references to these routines should be through the class object. extern int foobarmethod(foobar *); ...etc... class initialization function the mimedefclass macro expects us...
...d on the superclass) is to simply extract them from the superclass's object. but note that you cannot get at methods by indirecting through object->class->superclass: that will only work to one level, and will go into a loop if some subclass tries to continue on this method. the easiest way to do this is to make use of the mime_superclass macro that was defined at the top of the file, as shown below. the alternative to that involves typing the literal name of the direct superclass of the class defined in this file, which will be a maintenance headache if the class hierarchy changes. if you use the mime_superclass idiom, then a textual change is required in only one place if this class's superclass changes. static void foobar_finalize (mimeobject *object) { ((mimeobjec...
Theme Packaging
bes how to package themes for thunderbird. pre-requisites making a theme for thunderbird requires knowledge of cascading stylesheets (css), probably xbl, and some graphic design and aesthetic skill (...or maybe not). this document describes only how themes are packaged in order to be shown in firefox's themes window. theme file layout thunderbird themes are packaged in an xpi file with the following structure: theme.xpi: install.rdf preview.png icon.png chrome/ browser/files communicator/files global/files mozapps/files ... you must have a top-level chrome.manifest file which registers the chrome for the theme (as before) and also an install.rdf manifest that specifies metadata that is displayed in the appearance section of the add-ons manag...
...see the install.rdf reference for more information: em:id em:version em:type em:targetapplication em:name em:internalname optional install.rdf properties em:description em:creator em:contributor em:homepageurl em:updateurl note that if your theme will be made available on the https://addons.mozilla.org website, it may not include an updateurl. sample install.rdf...
...do not add to this list without contacting benjamin smedberg. note that this page i...
...ion 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-item extension packaging: specific information about multiple-item ex...
customDBHeaders Preference
the mailnews.customdbheaders preference will be our focus. some of the functionality described here is really new, so please try to be understanding if some of these things change tomorrow (or have changed already). while i was going through the creating a custom column guide, i built and used thunderbird-2.0b1 checked-out from cvs with the thunderbird_2_0b1_release tag. there is a high probability that your experience will be different should you use an earlier release. ...
...derbird's main view. the data will come from a custom header labeled x-superfluous. setting the preferences although there are various ways to set preferences, i tend to just navigate to the directory where my profile is stored and edit the user.js file with my favorite text editor. ...
...ill come from a custom header labeled x-superfluous. setting the preferences although there are various ways to set preferences, i tend to just navigate to the directory where my profile 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...
... 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 changed to a space in the latest code. when using the latest releases, the line should look like: // space-delimited list in the latest code! user_pref( "mailnews.customdbheaders", "x-superfluous x-other"); adding a column the reply-to column tutorial does a good jo...
Using tab-modal prompts
even if you set it to the browser window ("var thewindow = window") the modal alert will be shown in the current tab. from then on, you can use the nsiprompt object, prompt, as usual. for example: var factory = components.classes["@mozilla.org/prompter;1"] .getservice(components.interfaces.nsipromptfactory); var prompt ...
...nt tab. from then on, you can use the nsiprompt object, prompt, as usual. ...
...devmo alert", "omg! an alert!"]; prompt.alert.apply(null, promptargs); nsiprompt will automatically fall back to window-modal prompts when necessary (such as in situations in which tab-modal prompts aren't supported, or for prompts displayed outside the context of a tab).le to use other forms of the prompts of nsipromptservice interface see the example code. ...
...mple below, here we apply the prompt with a checkbox: var window = gbrowser.contentwindow; var promptfact = components.classes['@mozilla.org/prompter;1'].getservice(components.interfaces.nsipromptfactory); var prompt = promptfact.getprompt(window, components.interfaces.nsiprompt); var promptbag = prompt.queryinterface(components.interfaces.nsiwritablepropertybag2); promptbag.setpropertyasbool('allowtabmodal', true); var check = {value: false}; //initial state of checkbox, however if no text is supplied the checkbox is not shown var input = {value: 'pre filled value'}; var ok = prompt.prompt.apply(null, ['title - but not shown in tab modal', 'text goes here', input, 'check text, if no text, checkbox is not shown', check]); //this here is just an alert, showing the values of the prompt prom...
Using the Mozilla symbol server
the server functions like microsoft's symbol server so the documentation there can be useful. note that because mozilla release builds are heavily optimized, debugging is not always easy. ...
...e to show you the content of all variables and the execution path can seem strange because of inlining, tail calls, and other compiler optimizations. the only workaround is to build an unoptimized local build. the official symbol server url for firefox is https://symbols.mozilla.org/. you cannot visit this url directly: you must add it to the symbol path of your debugging tool. in the examples below, a local cache directory is used to avoid repeatedly fetching the pdb from the server. replace c:\users\bsmedberg\symbols with an appropriate cache directory on your machine. using the symbol server in microsoft visual c++ using the symbol server in windbg the windbg symbol path is configured with a string value delimited with asterisk characters. to use only the mozilla symbol server, add ...
...al cache directory is used to avoid repeatedly fetching the pdb from the server. replace c:\users\bsmedberg\symbols with an appropriate cache directory on your machine. using the symbol server in microsoft visual c++ using the symbol server in windbg the windbg symbol path is configured with a string value delimited with asterisk characters. to use only the mozilla symbol server, add the following entry to your symbol path (note: you can replace c:\symcache\ with any writable directory on your computer, if you'd prefer a different location for downloaded symbols): srv*c:\symcache\*https://symbols.mozilla.org/ set this string as _nt_symbol_path in the environment, using the windbg menus, or by typing the .sympath command. if you would like to get symbols from microsoft's symbol server...
...edlibrary lib on older gdb and mac os x there is a python script to download symbols from the mozilla symbol server for gdb, shark and other software that uses symbols. note that the symbol file for the xul library is very large and takes some time to download. this may make it appear as if the script has gotten stuck, but it will continue. symbol indices are named like so: symbols.mozilla.org/{lowercased:name}/{lowercased:name}-{version}-{platform}-{buildid}-symbols.txt. the platform is either 'darwin' (for mac) or 'linux'. the rest of values are based on the contents of the application.ini file under the [app] heading: for example, the thunderbird 3.1b2 release with name=thunderbird, version=3.1b2, buildid=20100430125415 would have a filename of "thunderbird-3.1b2-linux-20100430125415-sym...
Zombie compartments
...
...system principal], resource://gre/modules/addons/xpiprovider.jsm) when looking at user compartments there are a couple of things to be aware of. first, many sites utilize scripts from other sites to provide advertisements, "like" and "+1" buttons, twitter feeds, etc. so it's common for multiple compartments to be created for a single web page. for example, if i open www.techcrunch.com the following compartments are created. compartment(http://techcrunch.com/) compartment(http://www.facebook.com/plugins/like.php?...) compartment(https://plusone.google.com/_/+1/fastbutton?...) compartment(http://platform.twitter.com/widgets/...utton.html?...) compartment(http://cdn.at.atwola.com/_media/uac/tcode3.html) compartment(https://s-static.ak.fbcdn.net/connec..._proxy.php?...) compartment(...
...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 and making it more likely to crash. reactive checking if you look at about:memory and you see 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. ope...
...ered, add “[memshrink]” to its whiteboard, and mark it as blocking bug 668871. attaching the full contents of about:memory?verbose is very helpful (and you can just cut and paste the page contents, there's no need to take a screenshot). see bug 669545 for an example. if the zombie compartment is caused by an add-on, please mark the bug as also blocking bug 700547. it really is best to follow these instructions. in particular, if you have multiple tabs open it's easy to mis-identify whether a compartment should still be alive. if you only have about:memory open, things are much simpler. proactive checking of add-ons it's not uncommon for add-ons to cause zombie compartments, see bug 700547 for examples. follow these steps to do some basic checking of an add-on. create a new pr...
Type conversion
passing to or returning from a functiontype call, or setting pointer content, an array element or a struct field. ...
...or var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.int16_t } ])(); mystruct.v = 0x41; console.log(mystruct.v.tostring()); // 65 mystruct.v = true; console.log(mystruct.v.tostring()); // 1 mystruct.v = "x"; // throws error integer/float types are implicitly convertible if any data of source type could be representable in the target type. note that the following table does not contain environment dependent types (ctypes.long, etc.). target type source type ctypes.int16_t ctypes.int8_t ctypes.uint8_t ctypes.short ctypes.uint16_t ctypes.uint8_t ctypes.unsigned_short ctypes.short ctypes.int8_t ctypes.uint8_t ctypes.int16_t ctypes.unsigned_short ctype...
...type("mystructtype", [ { "v": ctypes.int16_t.ptr } ])(); mystruct.v = ctypes.int16_t.array(10)(); console.log(mystruct.v.tostring()); // 'ctypes.int16_t.ptr(ctypes.uint64("0x11d6ff400"))' mystruct.v = null; console.log(mystruct.v.tostring()); // 'ctypes.int16_t.ptr(ctypes.uint64("0x0"))' mystruct.v = ctypes.int32_t.array(10)(); // throws error only in functiontype argument, the following rules are also applied: target type source converted value ctypes.char.ptr js string pointer to temporary allocated null-terminated utf8 string ctypes.signed_char.ptr ctypes.unsigned_char.ptr ctypes.char16.ptr js string pointer to temporary allocated null-terminated utf16 string any pointer types any arraybuffer object...
... (only if the object has properties for all fields and no other properties) implicitly convert each enumerable property to corresponding field explicit convert in js-ctypes, data could be converted explicitly, when passing to cdata constructor: ctypes.int32_t("123"); // string "123" is parsed as 10-base string explicit convert tries implicit convert first, and if it fails, the following rules are applied: boolean type target type source converted value ctype.bool js value toboolean(src) console.log(ctypes.bool("123").tostring()); // 'ctypes.bool(true)' console.log(ctypes.bool("").tostring()); // 'ctypes.bool(false)' integer types target type source converted value any integer types js number except -infin...
Drawing and Event Handling - Plugins
whenever the drawable changes. for windowless plugins, a cliprect of 0,0,0,0 signals that the plugin is not visible. the type field indicates the npwindow type of the target area: npwindowtypewindow: windowed plug-in. the window field holds a platform-specific handle to a window. npwindowtypedrawable: windowless plug-in. the window field holds a platform-specific handle to a drawable, as follows: windows: hdc mac os: pointer to np_port structure. unix/x11: not used. (the drawable is provided in the paint message. see below.) in both cases, the drawable can be an off-screen pixmap. drawing plug-ins this section describes the methods and processes you use in drawing both windowed and windowless plug-ins. processes that apply to only one of these plug-in types are desc...
... the plug-in uses these methods to draw plug-ins and to handle events: plug-in methods, called by the browser: npp_handleevent: deliver a platform-specific event to the instance. npp_print: request a platform-specific print operation for the instance. ...
.... windowless plug-ins a windowless plug-in does not require a native window to draw into. instead it draws into a drawable (hdc on windows or cgrafptr on mac os), which can either be on-screen or off-screen. windowless plug-ins provide the plug-in writer with some significant design possibilities: you can place a windowless plug-in within a section; other sections can exist both above and below it. you can create transparent plug-ins. in this case, the browser draws the part of the page that exists behind the plug-in. the windowless plug-in draws only the parts of itself that are opaque. this way, the plug-in can draw an irregularly shaped area, such as a figure, or text over the existing background. the browser supports off-screen drawing of plug-ins. this makes it possible to manipu...
...pports off-screen drawing of plug-ins. this makes it possible to manipulate plug-in contents. for example, a 3d application could use the contents of a plug-in as a texture map. because windowless plug-ins can be layered or drawn to arbitrary drawables, the browser (as opposed to the native windowing system) is responsible for controlling both their drawing and their event handling. ...
Debugger.Environment - Firefox Developer Tools
ugger can use the == operator to recognize when two debugger.environment instances refer to the same environment in the debuggee, and place its own properties on a debugger.environment instance to store metadata about particular environments. (if more than one debugger instance is debugging the same code, each debugger gets a separate debugger.environment instance for a given environment. this allows the code using each debugger instance to place whatever properties it likes on its own debugger.object instances, without worrying about interfering with other debuggers.) if a debugger.environment instance’s referent is not a debuggee environment, then attempting to access its properties (other than inspectable) or call any its methods throws an instance of error. debugger.environment insta...
...ny its methods throws an instance of error. debugger.environment instances protect their referents from the garbage collector; as long as the debugger.environment instance is live, the referent remains live. garbage collection has no visible effect on debugger.environment instances. ...
...function calls, calls to eval, let blocks, catch blocks, and the like create declarative environment records. “object”, indicating that the environment’s bindings are the properties of an object. ...
...rue if this environment is optimized out. false otherwise. for example, functions whose locals are never aliased may present optimized-out environments. when true, getvariable returns an ordinary javascript object whose optimizedout property is true on all bindings, and setvariable throws a referenceerror. function properties of the debugger.environment prototype object the methods described below may only be called with a this value referring to a debugger.environment instance; they may not be used as methods of other kinds of objects. names() return an array of strings giving the names of the identifiers bound by this environment. the result does not include the names of identifiers bound by enclosing environments. getvariable(name) return the value of the variable bound toname i...
Deprecated tools - Firefox Developer Tools
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. 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, ...
...re currently writing. starting firefox 72, you can import a javascript file content in the console input with ctrl + o (cmd + o on macos), as well as saving the console input content to a file using ctrl + s (cmd + s on macos). webide and connect page webide was deprecated as of firefox 69 disabled as of firefox 70 (bug 1539451). removed as of firefox 71 (bug 1539462). description webide allowed you to connect the firefox developer tools to remote browsers, such as firefox for android. it was also intended to support application development for firefox os. alternatives remote debugging is available in about:debugging as of firefox 68. features not ported to about:debugging are: wifi debugging for firefox for android, application development. features that are planned but not ported...
...about:debugging as of firefox 68. features not ported to about:debugging are: wifi debugging for firefox for android, application development. features that are planned but not ported yet: remote browser screenshots and edit remote browser configuration. more details on the mailing-list thread. canvas debugger bugzilla issue: bug 1403938 removed as of firefox 67 description canvas debugger allowed users to inspect 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 all...
...some non-audioparam 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 ...
Inspecting web sockets - Firefox Developer Tools
he reponse tab to inspect web socket frames sent and received through the selected connection. the live-updated table shows data for sent (green arrow) and received (red arrow) frames. each frame expands on click, so you can inspect the formatted data. pausing web socket traffic you can use the pause/resume button in the network monitor toolbar to stop intercepting web socket traffic. ...
... sent displays only messages sent by the browser (by default, except control messages). received displays only messages received from the server (by default, except control messages). control (available starting in firefox 76). ...
...splays only messages received from the server (by default, except control messages). control (available starting in firefox 76). displays messages for control frames (ping, pong, or close). this filter can be combined with the others, to display, for example, only messages for control frames sent by the browser. columns in the response pane in the response pane, you can choose to show the following information about each frame: data size time opcode maskbit finbit the data and time columns are visible by default, but you can customize the interface to see more columns by choosing which ones to show from the context menu that is opened by right-clicking in the table header. expanding each message selecting a message in the list shows a preview of the data being sent in that ...
...isible by default, but you can customize the interface to see more columns by choosing which ones to show from the context menu that is opened by right-clicking in the table header. expanding each message selecting a message in the list shows a preview of the data being sent in that message, at the bottom of the response pane. supported ws protocols the inspector currently supports the following web socket protocols: plain json socket.io sockjs signalr wamp the payload based on those protocols is parsed and displayed as an expandable tree for easy inspection, although you can of course still see the raw data (as sent over the wire) as well. ...
Examine and edit HTML - Firefox Developer Tools
ument 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. full text search the full text search will always be executed, independently of what you enter. that allows you to find css selectors and xpath expressions occurring within the text. css selector search you can search elements by entering a css selector. as you type, an autocomplete popup shows any class or id attributes that match the current search term: press up and down to cycle through suggestions, tab to choose the current suggestion, then enter to select the first node with that attribute...
...tocomplete popup shows any class or id attributes that match the current search term: press up and down to cycle through suggestions, tab to choose the current suggestion, then enter to select the first node with that attribute. to cycle through matches, press enter. you can cycle backwards through matches using shift + enter. xpath search it is also possible to search via xpaths. this allows you to search for specific elements without the conflict of matching words within the text. for example, //a matches all <a> elements but not the letter "a" within the text content. furthermore it allows for some more advanced searches like finding elements that start with a specific text, for example. html tree the rest of the pane shows you the page's html as a tree (this ui is also called...
...sing tag of an element when the node is collapsed if it has larger contents. now children are indicated in the tree with this icon: at the right side of some nodes there are markers shown indicating different pieces of information related to it: event the element has one or several event listeners attached to it. clicking the marker opens a tooltip listing the event listeners and allows you for each listener to switch to the line of javascript code in the debugger where the listener is defined. scroll the element is a scroll container, i.e. it has overflow: scroll or overflow: auto applied to it, and it has scrollable overflow. grid the element is a grid container, i.e. it has display: grid applied to it. clicking the marker enables the grid highlighter.
... find the source of its content. note: shadow dom inspection was implemented in firefox 61, but was hidden behind the dom.webcomponents.shadowdom.enabled pref until firefox 63. it is now turned on by default. element popup context menu you can perform certain common tasks on a specific node using a popup context menu. to activate this menu, context-click the element. the menu contains the following items — click on the links to find the description of each command in the context menu reference: edit as html create new node duplicate node delete node attributes add attribute copy attribute value edit attribute remove attribute break on ... subtree modification attribute modification node removal use in console show dom properties show acce...
Web Console Helpers - Firefox Developer Tools
e) evaluates the xpath xpath expression in the context of element and returns an array of matching nodes. if unspecified, element defaults to document. the resulttype parameter specifies the type of result to return; it can be an xpathresult constant, or a corresponding string: "number", "string", "bool", "node", or "nodes"; if not provided, any_type is used. ...
... clear() clears the console output area. clearhistory() just like a normal command line, the console command line remembers the commands you've typed. ...
...returns a list of the keys (or property names) on that object. this is a shortcut for object.keys. pprint() obsolete since gecko 74 formats the specified value in a readable way; this is useful for dumping the contents of objects and arrays. :screenshot creates a screenshot of the current page with the supplied filename. if you don't supply a filename, the image file will be named with the following format: screen shot yyy-mm-dd at hh.mm.ss.png the command has the following optional parameters: command type description --clipboard boolean when present, this parameter will cause the screenshot to be copied to the clipboard. --delay number the number of seconds to delay before taking the screenshot. --dpr ...
...parameter, even the parts of the webpage which are outside the current bounds of the window will be included in the screenshot. when used, "-fullpage" will be appended to the file name. --selector string the css query selector for a single element on the page. when supplied, only this element will be included in the screenshot. :unblock (starting in firefox 80) followed by an unquoted string, removes blocking for urls containing that string. in the network monitor, the string is removed from the request blocking sidebar. no error is given if the string was not previously blocked. values() given an object, returns a list of the values on that object; serves as a companion to keys(). please refer to the console api for more information about logging from con...
The JavaScript input interpreter - Firefox Developer Tools
ingle-line mode for single-line entry, you can type javascript expressions in the field at the bottom of the console log, at the >> prompt. to enter expressions in single-line mode, type at the prompt and press enter. to enter multi-line expressions, press shift+enter after typing each line, then enter to run all the entered lines. the expression you type is echoed under the input prompt, followed by the result. if your input does not appear to be complete when you press enter, then the console treats this as shift+enter , enabling you to finish your input. for example, if you type: function foo() { and then enter, the console does not immediately execute the input, but behaves as if you had pressed shift+enter , so you can finish entering the function definition. multi-line mode f...
...inux) or cmd+b (macos). the multi-line editing pane opens on the left side the of web console. you can enter multiple lines of javascript by default in this mode, pressing enter after each one. to execute the snippet that is currently in the editing pane, click the run button or press ctrl+enter (or cmd+return on macos). the snippet is echoed under the input prompt (in the right-side pane), followed by the result. you can also select a range of lines in the editing pane, and run just the code on those lines. starting in firefox 76, if the code snippet is more than five lines long, only the first five lines are echoed in the console, preceeded by a disclosure triangle (or "twistie"), and followed by an ellipsis (…). click anywhere in the area containing the echoed code to show the whole ...
...y; this is useful for dumping the contents of objects and arrays. help()deprecated since gecko 62 :help displays help text. actually, in a delightful example of recursion, it will bring you to this page. cd() switch javascript evaluation context to a different iframe in the page. this helper accepts multiple different ways of identifying the frame to switch to. you can supply any of the following: a selector string that will be passed to document.queryselector to locate the iframe element the iframe element itself the content window inside the iframe see working with iframes. copy() new in firefox 38. copy the argument to the clipboard. if the argument is a string, it's copied as-is. if the argument is a dom node, its outerhtml is copied. otherwise, json.stringify will...
...w in firefox 39. just like a normal command line, the console command line remembers the commands you've typed. use this function to clear the console's command history. :screenshot new in firefox 62. create a screenshot of the current page with the supplied filename. if you don't supply a filename, the image file will be named: screen shot yyy-mm-dd at hh.mm.ss.png the command has the following optional parameters: command type description --clipboard boolean when present, this parameter will cause the screenshot to be copied to the clipboard. --delay number the number of seconds to delay before taking the screenshot. --dpr number the device pixel ratio to use when taking the screenshot. -...
AnalyserNode - Web APIs
the analysernode interface represents a node able to provide real-time frequency and time-domain analysis information. it is an audionode that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations. an analysernode has exactly one input and one output. the node works even if the output is not connected. ...
... create audio visualizations. an analysernode has exactly one input and one output. the node works even if the output is not connected. ...
...of outputs 1 (but may be left unconnected) channel count mode "max" channel count 2 channel interpretation "speakers" inheritance this interface inherits from the following parent interfaces: <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" 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...
...ttimedomaindata() copies the current waveform, or time-domain, data into a float32array array passed into it. analysernode.getbytetimedomaindata() copies the current waveform, or time-domain, data into a uint8array (unsigned byte array) passed into it. examples note: see the guide visualizations with web audio api for more information on creating audio visualizations. basic usage the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. 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 |...
AudioNode.channelInterpretation - Web APIs
the channelinterpretation property of the audionode interface represents an enumerated value describing the meaning of the channels. this interpretation will define how audio up-mixing and down-mixing will happen. when the number of channels doesn't match between an input and an output, up- or down-mixing happens according the following rules. this can be somewhat controlled by setting the audionode.channelinterpretation property to speakers or discrete: interpretation input channels output channels mixing rules speakers 1 (mono) 2 (stereo) up-mix from mono to stereo. the m input channel is used for both output channels (l and r). output.l = input.m output.r = input.m 1 (mono) 4 (quad) up-mix from mono to quad. the m ...
...a single channel by multiplying by √2/2. the subwoofer (lfe) channel is lost. output.m = 0.7071 * (input.l + input.r) + input.c + 0.5 * (input.sl + input.sr) 6 (5.1) 2 (stereo) down-mix from 5.1 to stereo. the central channel (c) is summed with each lateral surround channel (sl or sr) and mixed to each lateral channel. ...
...the surround channels are passed unchanged. the subwoofer (lfe) channel is lost. output.l = input.l + 0.7071 * input.c output.r = input.r + 0.7071 * input.c output.sl = input.sl output.sr = input.sr other, non-standard layouts non-standard channel layouts are handled as if channelinterpretation is set to discrete. ...
...ultiplied by √2/2. the surround channels are passed unchanged. the subwoofer (lfe) channel is lost. output.l = input.l + 0.7071 * input.c output.r = input.r + 0.7071 * input.c output.sl = input.sl output.sr = input.sr other, non-standard layouts non-standard channel layouts are handled as if channelinterpretation is set to discrete. the specification explicitly allows the future definition of new speaker layouts. this fallback is therefore not future proof as the behavior of the browsers for a specific number of channels may change in the future. discrete any (x) any (y) where x<y up-mix discrete channels. fill each output channel with its input counterpart, that is the input channel with the same index. channels with no corresponding in...
AudioWorkletProcessor.process - Web APIs
s corresponding audioworkletnode. in other words, every time a new block of audio is ready for your processor to manipulate, your process() function is invoked to do so. important: currently, audio data blocks are always 128 frames long—that is, they contain 128 32-bit floating-point samples for each of the inputs' channels. ...
... 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 channel is a float32array containing 128 samples...
...afe to shut down the node. 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 ...
...xample, take the audiobuffersourcenode — the processor behind such a node 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 t...
BasicCardRequest - Web APIs
f using this property, it is up to the server to check support for the card given the information coded into the account number. card network identifiers the w3c maintains an official list of approved card network identifier strings, which may be used in the supportednetworks list. ...
...ment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object that describes what data is needed to fullfil the payment (e.g., a shipping address). the first of these three (supportedinstruments in the example below) contains a data property that has to conform to the structure defined by the basiccardrequest dictionary. 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...
...', value: '65.00'} } ], shippingoptions: [ { id: 'standard', label: 'standard shipping', amount: {currency: 'usd', value: '0.00'}, selected: true } ] }; var options = {requestshipping: true}; try { var request = new paymentrequest(supportedinstruments, details, options); // add event listeners here. // call show() to trigger the browser's payment flow. ...
...mentrequest(supportedinstruments, details, options); // add event listeners here. // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. }) .catch(function(err) { // do something with the error from request.show(). }); } catch (e) { // catch any other errors. } once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '99...
BasicCardResponse - Web APIs
expirymonth read only secure context optional contains the expiry month of the card used to make the payment. basiccardresponse.expiryyear read only secure context optional contains the expiry year of the card used to make the payment. basiccardresponse.billingaddress read only secure context optional contains the billing address of the card used to make the payment. examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options. the first of these three (supportedinstruments in...
...e paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options. the first of these three (supportedinstruments in the example below) contains a data property that has to conform to the structure defined by the basiccardrequest dictionary. var supportedinstruments = [{ supportedmethods: 'basic-card', data: { supportednetworks: ['visa', 'mastercard', 'amex', 'jcb', 'diners', 'discover', 'mir', 'unionpay'], supportedtypes: ['credit', 'debit'] } }]; var details = { total: {label: 'donatio...
...', value: '65.00'} } ], shippingoptions: [ { id: 'standard', label: 'standard shipping', amount: {currency: 'usd', value: '0.00'}, selected: true } ] }; var options = {requestshipping: true}; try { var request = new paymentrequest(supportedinstruments, details, options); // add event listeners here. // call show() to trigger the browser's payment flow. ...
...mentrequest(supportedinstruments, details, options); // add event listeners here. // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. }) .catch(function(err) { // do something with the error from request.show(). }); } catch (e) { // catch any other errors. } once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '99...
BeforeUnloadEvent - Web APIs
the beforeunload event is fired when the window, the document and its resources are about to be unloaded. when a non-empty string is assigned to the returnvalue event property, a dialog box appears, asking the users for confirmation to leave the page (see example below). when no value is provided, the event is processed silently. some implementations only show the dialog box if the frame or any embedded frame receives a user gesture or user interaction. see browser compatibility for more information. ...
...(see example below). when no value is provided, the event is processed silently. some implementations only show the dialog box if the frame or any embedded frame receives a user gesture or user interaction. see browser compatibility for more information. ...
... window.addeventlistener("beforeunload", function (e) { var confirmationmessage = "\o/"; (e || window.event).returnvalue = confirmationmessage; // gecko + ie return confirmationmessage; /* safari, chrome, and other ...
...ects defaultview interface event examples window.addeventlistener("beforeunload", function( event ) { event.returnvalue = "\o/"; }); // is equivalent to window.addeventlistener("beforeunload", function( event ) { event.preventdefault(); }); webkit-derived browsers don't follow the spec for the dialog box. an almost-cross-browser working example would be close to the below example. window.addeventlistener("beforeunload", function (e) { var confirmationmessage = "\o/"; (e || window.event).returnvalue = confirmationmessage; // gecko + ie return confirmationmessage; /* safari, chrome, and other * webkit-derived browsers */ }); specifications specificatio...
Using dynamic styling information - Web APIs
initially defined in the dom level 2 style recommendation, these interfaces forms now a specification, css object model (cssom) which aims at superseding it. in many cases, and where possible, it really is best practice to dynamically manipulate classes via the classname property since the ultimate appearance of all of the styling hooks can be controlled in a single stylesheet. ...
...lso becomes cleaner since instead of being dedicated to styling details, it can focus on the overall semantics of each section it is creating or manipulating, leaving the precise style details to the stylesheet. however, there are cases where actually obtaining or manipulating the rules can be useful (whether for whole stylesheets or individual elements), and that is described in further detail below. note also that, as with individual element's dom styles, when speaking of manipulating the stylesheets, this is not actually manipulating the physical document(s), but merely the internal representation of the document. the basic style object exposes the stylesheet and the cssstylesheet interfaces. those interfaces contain members like insertrule, selectortext, and parentstylesheet for accessin...
...dified via javascript. </body> </html> the list of properties available in the dom from the style property is given on the dom css properties list page. to modify styles to a document using css syntax, one can insert rules or insert <style> tags whose innerhtml property is set to the desired css. modify an element's style the element style property (see also the section "dom style object" below) can also be used to get and set the styles on an element. however, this property only returns style attributes that have been set in-line (e.g, <td style="background-color: lightblue"> returns the string "background-color:lightblue", or directly for that element using element.style.propertyname, even though there may be other styles on the element from a stylesheet). also, when you set this pro...
...s particular property you are setting. setting the border property, for example, will override settings made elsewhere for that element's border property in the head section, or external style sheets. however, this will not affect any other property declarations for that element's styles, such as padding or margin or font, for example. to change a particular element's style, you can adapt the following example for the element(s) you want to style. <html> <head> <title>simple style example</title> <script type="text/javascript"> function alterstyle(elem) { elem.style.background = 'green'; } function resetstyle(elemid) { elem = document.getelementbyid(elemid); elem.style.background = 'white'; } </script> <style type="text/css"> #p1 { border: solid blue 2px; } </style> </head> <bo...
CSS Properties and Values API - Web APIs
the css properties and values api — part of the css houdini umbrella of apis — allows developers to explicitly define their css custom properties, allowing for property type checking, default values, and properties that do or do not inherit their value. interfaces css.registerproperty defines how a browser should parse a css custom properties. access this interface through css.registerproperty in javascript. @property defines how a browser should parse a css custom properties. access this interface through @property in css. ...
... property type checking, default values, and properties that do or do not inherit their value. interfaces css.registerproperty defines how a browser should parse a css custom properties. access this interface through css.registerproperty in javascript. @property defines how a browser should parse a css custom properties. access this interface through @property in css. ...
...how a browser should parse a css custom properties. access this interface through css.registerproperty in javascript. @property defines how a browser should parse a css custom properties. access this interface through @property in css. ...
...through @property in css. examples the following uses css.registerproperty in javascript to type a css custom properties, --my-color, as a color, give it a default value, and not allow it to inherit its value: window.css.registerproperty({ name: '--my-color', syntax: '<color>', inherits: false, initialvalue: '#c0ffee', }); the same registration can take place in css using the following @property: @property --my-color { syntax: '<color>'; inherits: false; initial-value: #c0ffee; } specifications specification status comment css properties and values api level 1 working draft initial definition. ...
CanvasRenderingContext2D.imageSmoothingQuality - Web APIs
"medium" medium quality. "high" high quality. example setting image smoothing quality this example uses the imagesmoothingquality property with a scaled image. ...
... "medium" medium quality. "high" high quality. example setting image smoothing quality this example uses the imagesmoothingquality property with a scaled image. ...
... "medium" medium quality. "high" high quality. example setting image smoothing quality this example uses the imagesmoothingquality property with a scaled image. ...
...ting image smoothing quality this example uses the imagesmoothingquality property with a scaled image. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let img = new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { ctx.imagesmoothingquality = 'low'; ctx.drawimage(img, 0, 0, 300, 150); }; result specifications specification status comment html living standardthe definition of 'imagesmoothingquality' in that specification. living standard initial definition. ...
Advanced animations - Web APIs
« previousnext » in the last chapter we made some basic animations and got to know ways to get things moving. in this part we will have a closer look at the motion itself and are going to add some physics to make our animations more advanced. drawing a ball we are going to use a ball for our animation studies, so let's first draw that ball onto the canvas. the following code will set us up. <canvas id="canvas" width="600" height="300"></canvas> as usual, we need a drawing context first. to draw the ball, we will create a ball object which contains properties and a draw() method to paint it on the canvas. var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var ball = { x: 100, y: 100, radius: 25, color: 'blue', draw: function...
...= window.requestanimationframe(draw); }); canvas.addeventlistener('mouseout', function(e) { window.cancelanimationframe(raf); }); ball.draw(); boundaries without any boundary collision testing our ball runs out of the canvas quickly. we need to check if the x and y position of the ball is out of the canvas dimensions and invert the direction of the velocity vectors. to do so, we add the following checks to the draw method: if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } first demo let's see how it looks in action so far. move your mouse into the canvas to start the animation. <canvas id="canvas" style="border: 1px solid" width="600" height="300"></canvas> ...
... second demo <canvas id="canvas" style="border: 1px solid" width="600" height="300"></canvas> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var raf; var ball = { x: 100, y: 100, vx: 5, vy: 2, radius: 25, color: 'blue', draw: function() { ctx...
...the click event releases the ball and lets it bounce again. <canvas id="canvas" style="border: 1px solid" width="600" height="300"></canvas> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var raf; var running = false; var ball = { x: 100, y: 100, vx: 5, vy: 1, radius: 25, color: 'blue', draw: ...
Basic animations - Web APIs
o update an animation before the next repaint. if you don't want any user interaction you can use the setinterval() function which repeatedly executes the supplied code. if we wanted to make a game, we could use keyboard or mouse events to control the animation and use settimeout(). by setting eventlisteners, we catch any user interaction and execute our animation functions. in the examples below, we'll use the window.requestanimationframe() method to control the animation. the requestanimationframe method provides a smoother and more efficient way for animating by calling the animation frame when the system is ready to paint the frame. the number of callbacks is usually 60 times per second and may be reduced to a lower rate when running in background tabs. for more information about the ...
... yosemite national park we took from wikipedia, but you could use any image that's larger than the canvas. var img = new image(); // user variables - customize these to change the image being scrolled, its // direction, and the speed. ...
... image is > canvas size else { // reset, start from beginning if (x > (canvasxsize)) { x = canvasxsize - imgw; } // draw aditional image if (x > (canvasxsize-imgw)) { ctx.drawimage(img, x - imgw + 1, y, imgw, imgh); } } // draw image ctx.drawimage(img, x, y,imgw, imgh); // amount to move x += dx; } below is the <canvas> in which the image is scrolled. note that the width and height specified here must match the values of the canvasxzsize and canvasysize variables in the javascript code. <canvas id="canvas" width="800" height="200"></canvas> mouse following animation <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-...
...iv> </div> <div class="banner" id="selector"> <div> time :<span id="time">0</span> </div> <div>lousygames ©</div> <div> score :<span id="score">0</span> </div> <div class="touch off" onclick="touch(this)">touch</div> </div> <canvas id="main"></canvas> </body> <style> body { margin: 0; overflow: hidden; background: #000 } .banner { text-align: center; color: #fff; background: #3f51b5; line-height: 29px; position: fixed; left: 0; top: 0; right: 0; font-family: monospace; height: 30px; opacity: .4; display: flex; transition: .5s } .banner:hover { opacit...
console - Web APIs
Web › API › Console
cope as specific variants in workers via the property console. it's exposed as window.console, and can be referenced as simply console. for example: console.log("failed to open the specified link") this page documents the methods available on the console object and gives a few usage examples. note: this feature is available in web workers. note: the actual console interface is defined as all lower case (i.e. not console), for historical reasons. methods console.assert() log a message and stack trace to console if the first argument is false. console.clear() clear the console. 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 t...
...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, indenting all following output by another level. to move back out a level, call groupend(). console.groupcollapsed() creates a new inline group, indenting all following output by another level. however, unlike group() this starts with the inline group collapsed requiring the use of a disclosure button to expand it. to move back out a level, call groupend(). console.groupend() exits the current inline group. cons...
...ferently in the log, and you can use the filtering controls provided by your browser to only view the kinds of output that interest you. there are two ways to use each of the output methods; you can simply pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you can pass in a string containing zero or more substitution strings followed by a list of objects to replace them. outputting a single object the simplest way to use the logging methods is to output a single object: var someobject = { str: "some text", id: 5 }; console.log(someobject); the output looks something like this: [09:27:13.475] ({str:"some text", id:5}) outputting multiple objects you can also output multiple objects by simply listing them when calling...
...ello, bob. you've called me 1 times. [13:14:13.483] hello, bob. you've called me 2 times. [13:14:13.485] hello, bob. you've called me 3 times. [13:14:13.487] hello, bob. you've called me 4 times. [13:14:13.488] hello, bob. you've called me 5 times. styling console output you can use the %c directive to apply a css style to console output: console.log("this is %cmy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px"); the text before the directive will not be affected, but the text after the directive will be styled using the css declarations in the parameter. the properties usable along with the %c syntax are as follows (at least, in firefox — they may differ in other browsers): background and its longhand equivalents. border and its longha...
DataTransfer.dropEffect - Web APIs
ing a drag and drop operation. it will affect which cursor is displayed while dragging. for example, when the user hovers over a target drop element, the browser's cursor may indicate which type of operation will occur. when the datatransfer 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 dra...
...ation effect. the possible values are: copy a copy of the source item is made at the new location. move an item is moved to a new location. link a link is established to the source at the new location. none the item may not be dropped. assigning any other value to dropeffect has no effect and the old value is retained. example this example shows the use of the dropeffect and effectallowed properties. html content <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element. </p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css content div { margin: 0em; padding: 2em; } #source { color...
.../p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css content div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } javascript content function dragstart_handler(ev) { console.log("dragstart: dropeffect = " + ev.datatransfer.dropeffect + " ; effectallowed = " + ev.datatransfer.effectallowed); // add this element's id to the drag payload so the drop handler will // know which element to add to its tree ev.datatransfer.setdata("text", ev.target.id); ev.datatransfer.effectallowed = "move"; } function drop_handler(ev) { console.log("drop: dropeffect = " + ev.datatransfer.dropeffect + " ; effectallowed = " + ev.datatransfer.effectallowed)...
...tatransfer.dropeffect + " ; effectallowed = " + ev.datatransfer.effectallowed); ev.preventdefault(); // get the id of the target and add the moved element to the target's dom var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover: dropeffect = " + ev.datatransfer.dropeffect + " ; effectallowed = " + ev.datatransfer.effectallowed); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } specifications specification status comment html living standardthe definition of 'dropeffect' in that specification. living standard html 5.1the definition of 'dropeffect' in that specification. recommendation i...
DataTransferItem.webkitGetAsEntry() - Web APIs
ryentry. example in this example, a drop zone is created, which responds to the drop event by scanning through the dropped files and directories, outputting a hierarchical directory listing. html content the html establishes the drop zone itself, which is a <div> element with the id "dropzone", and an unordered list element with the id "listing". <p>drag files and/or directories to the box below!</p> <div id="dropzone"> <div id="boxtitle"> drop files here </div> </div> <h2>directory tree:</h2> <ul id="listing"> </ul> css content the styles used by the example are shown here. #dropzone { text-align: center; width: 300px; height: 100px; margin: 10px; padding: 10px; border: 4px dashed red; border-radius: 10px; } #boxtitle { display: table-cell; vertical-alig...
...scanfiles() function. this function takes as input a filesystementry representing an entry in the file system to be scanned and processed (the item parameter), and an element into which to insert the list of contents (the container parameter). note that to read all files in a directory, readentries needs to be called repeatedly until it returns an empty array. in chromium-based browsers, the following example will only return a max of 100 entries. let dropzone = document.getelementbyid("dropzone"); let listing = document.getelementbyid("listing"); function scanfiles(item, container) { let elem = document.createelement("li"); elem.innerhtml = item.name; container.appendchild(elem); if (item.isdirectory) { let directoryreader = item.createreader(); let directorycontainer = ...
... in the next level down in the list's hierarchy. after that, directoryreader.readentries() is called to read in all the entries in the directory. these are each, in turn, passed into a recursive call to scanfiles() to process them. any of them which are files are simply inserted into the list; any which are directories are inserted into the list and a new level of the list's hierarchy is added below, and so forth. then come the event handlers. first, we prevent the dragover event from being handled by the default handler, so that our drop zone can receive the drop: dropzone.addeventlistener("dragover", function(event) { event.preventdefault(); }, false); the event handler that kicks everything off, of course, is the handler for the drop event: dropzone.addeventlistener("drop", funct...
.... then we iterate over the items in the list of dropped items. for each one, we call its webkitgetasentry() method to obtain a filesystementry representing the file. if that's successful, we call scanfiles() to process the item—either by adding it to the list if it's just a file or by adding it and walking down into it if it's a directory. result you can see how this works by trying it out below. find some files and directories and drag them in, and take a look at the resulting output. specifications specification status comment file and directory entries apithe definition of 'webkitgetasentry()' in that specification. draft initial specification. this api has no official w3c or whatwg specification. browser compatibility the compatibility t...
DirectoryReaderSync - Web APIs
this specification is pretty much abandoned, having failed to reach any substantial traction. ...
...nd the worker thread see the same javascript object; you just need them to access the same files. you can do that by passing a list of filesystem: urls—which are just strings—instead of a list of entries. you can also use the filesystem: url to look up the entry with resolvelocalfilesystemurl(). that gets you back to a directoryentrysync (as well as fileentrysync) object. example in the following code snippet from html5rocks, we create web workers and pass data from it to the main app. // taking care of the browser-specific prefixes. window.resolvelocalfilesystemurl = window.resolvelocalfilesystemurl || window.webkitresolvelocalfilesystemurl; // create web workers var worker = new worker('worker.js'); worker.onmessage = function(e) { var...
...esolvelocalfilesystemurl; // create web workers var worker = new worker('worker.js'); worker.onmessage = function(e) { var urls = e.data.entries; urls.foreach(function(url, i) { window.resolvelocalfilesystemurl(url, function(fileentry) { // print out file's name. console.log(fileentry.name); }); }); }; worker.postmessage({'cmd': 'list'}); the following is worker.js code that gets the contents of the directory. // taking care of the browser-specific prefixes. self.requestfilesystemsync = self.webkitrequestfilesystemsync || self.requestfilesystemsync; // global for holding the list of entry file system urls. var paths = []; function getallentries(dirreader) { var entries = dirreader.readentries(); for (var ...
... paths}); } catch (e) { onerror(e); } }; method overview entrysync readentries () raises (fileexception); method readentries() returns a lost of entries from a specific directory. call this method until an empty array is returned. entrysync readentries ( ) raises (fileexception); returns parameter none exceptions this method can raise a fileexception with the following codes: exception description not_found_err the directory does not exist. 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 st...
DisplayMediaStreamConstraints.video - Web APIs
video track must always be included, a value of false results in a typeerror exception being thrown. more precise control over the format of the returned video track may be exercised by instead providing a mediatrackconstraints object, which is used to process the video data after obtaining it from the device but prior to adding it to the stream. syntax displaymediastreamconstraints.video = allowvideoflag; displaymediastreamconstraints.video = mediatrackconstraints; displaymediastreamconstraints = { video: allowvideoflag | mediatrackconstraints; } value the value may be either a boolean or a mediatrackconstraints object. if a boolean is specified, a value of true (the default) indicates that the stream returned by getdisplaymedia() should be in whatever format the user agent feels ...
...s apply to mediatrackconstraints objects specified as part of the displaymediastreamconstraints object's video property when using getdisplaymedia() to obtain a stream for screen sharing. cursor a constraindomstring which specifies whether or not to include the mouse cursor in the generated track, and if so, whether or not to hide it while not moving. the value may be a single one of the following strings, or an array of them to allow the browser flexibility in deciding what to do about the cursor. always the mouse is always visible in the video content of the {domxref("mediastream"), unless the mouse has moved outside the area of the content. motion the mouse cursor is always included in the video if it's moving, and for a short time after it stops moving. never the mous...
...ss the mouse has moved outside the area of the content. motion the mouse cursor is always included in the video if it's moving, and for a short time after it stops moving. never the mouse cursor is never included in the shared video. displaysurface a constraindomstring which specifies the types of display surface that may be selected by the user. this may be a single one of the following strings, or a list of them to allow multiple source surfaces: application the stream contains all of the windows of the application chosen by the user rendered into the one video track. browser the stream contains the contents of a single browser tab selected by the user. monitor the stream's video track contains the entire contents of one or more of the user's screens. window...
...the stream contains the contents of a single browser tab selected by the user. monitor the stream'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 constrainboolean value which may contain a single boolean value or a set of them, indicating whether or not to allow the user to choose source surfaces which do not directly correspond to display areas. these may include backing buffers for windows to allow capture of window contents that are hidden by other windows in front of them, or buffers containing larger documents that need to be scrolled through to see the entire contents in their windows. example specifications specification status ...
Document.createElement() - Web APIs
knownelement if tagname isn't recognized. syntax let element = document.createelement(tagname[, options]); parameters tagname a string that specifies the type of element to be created. the nodename of the created element is initialized with the value of tagname. don't use qualified names (like "html:a") with this method. when called on an html document, createelement() converts tagname to lower case before creating the element. in firefox, opera, and chrome, createelement(null) works like createelement("null"). options optional an optional elementcreationoptions object, containing a single property named is, whose value is the tag name of a custom element previously defined via customelements.define(). see web component example for more details. return value the new element. exa...
...in this case, our custom element extends the htmlulistelement, which represents the <ul> element. // create a class for the element class expandinglist extends htmlulistelement { constructor() { // always call super first in constructor super(); // constructor definition left out for brev...
... element class expandinglist extends htmlulistelement { constructor() { // always call super first in constructor super(); // constructor definition left out for brevity ... ...
...if we wanted to create an instance of this element programmatically, we'd use a call along the following lines: let expandinglist = document.createelement('ul', { is : 'expanding-list' }) the new element will be given an is attribute whose value is the custom element's tag name. note: for backwards compatibility with previous versions of the custom elements specification, some browsers will allow you to pass a string here instead of an object, where the string's value is the custom element's tag name. specifications specification status comment domthe definition of 'document.createelement' in that specification. living standard ...
Document.getElementsByTagNameNS() - Web APIs
namespace is the namespace uri of elements to look for (see element.namespaceuri). ...
...mplemented, which makes it similar to a htmlcollection. as of january 2012, only in webkit browsers is the returned value a pure nodelist. see bug 14869 for details. note: currently parameters in this method are case-sensitive, but they were case-insensitive in firefox 3.5 and before. see the note in browser compatibility section in element.getelementsbytagnamens for details. ...
... example in the following example getelementsbytagnamens starts from a particular parent element, and searches topdown recursively through the dom from that parent element, looking for child elements matching the tag name parameter. note that when the node on which getelementsbytagname is invoked is not the document node, in fact the element.getelementsbytagnamens method is used. to use the following example, just copy/paste it into a new file saved with the .xhtml extension. <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>getelementsbytagnamens example</title> <script type="text/javascript"> function getallparaelems() { var allparas = document.getelementsbytagnamens("http://www.w3.org/1999/xhtml", "p"); var num = allparas.length; alert("there are " + num + " &lt;p&gt...
...for other browsers which do not support if the desired browser did not support xpath, another approach (such as traversing the dom through all its children, identifying all @xmlns instances, etc.) would be necessary to find all tags with the desired local name and namespace, but xpath is much faster. ...
Document - Web APIs
Web › API › Document
s content, which is the dom tree. the dom tree includes elements such as <body> and <table>, among many others. it provides functionality globally to the document, like how to obtain the page's url and create new elements in the document. ...
... the current document. document.readystateread only returns loading status of the document. document.referrerread only returns the uri of the page that linked to this page. document.title sets or gets the title of the current document. document.urlread only returns the document location as a string. properties included from documentorshadowroot the document interface includes the following properties defined on the documentorshadowroot mixin. note that this is currently only implemented by chrome; other browsers still implement them directly on the document interface. documentorshadowroot.activeelementread only returns the element within the shadow tree that has focus. document.fullscreenelementread only the element that's currently in full screen mode for this document.
... releases the current mouse capture if it's on an element in this document. document.releaseevents() see window.releaseevents(). document.requeststorageaccess() returns a promise that resolves if the access to first-party storage was granted, and rejects if access was denied. document.routeevent() obsolete since gecko 24 see window.routeevent(). document.mozsetimageelement() allows you to change the element being used as the background image for a specified element id. the document interface is extended with the parentnode interface: document.getelementbyid(string id) returns an object reference to the identified element. document.queryselector() returns the first element node within the document, in document order, that matches the specified selectors. document.q...
... 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. document.writeln() writes a line of text in a document. methods included from documentorshadowroot the document interface includes the following methods defined on the documentorshadowroot mixin. note that this is currently only implemented by chrome; other browsers still implement them on the document interface. documentorshadowroot.getselection() returns a selection object representing the range of text selected by the user, or the current position of the caret. documentorshadowroot.elementfrompoint() returns the topmost elemen...
EffectTiming.fill - Web APIs
Web › API › EffectTiming › fill
rrent 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. 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 domstrin...
...nimation effect the fill mode is being applied to is a keyframe effect (keyframeeffect or keyframeeffectreadonly), "auto" is equivalent to "none". otherwise, the result is "both". examples here are a few examples. fill mode: none html content the html is pretty simple. we have a <div> named "main" which is a container for the element we'll be animating, which is a <div> with the id "box". below that, another <div> serves as a button that will trigger the animation to begin. <div class="main"> <div id="box"> <div id="text">look! a box!</div> </div> </div> <div class="button" id="animatebutton"> animate! </div> css content .main { width: 300px; height:300px; border: 1px solid black; } .button { cursor: pointer; width: 300px; border: 1px solid black; font-size...
...etelementbyid("box").animate( boxrotationkeyframes, boxrotationtiming ); }, false); the rest of the code is pretty simple: it adds an event listener to the "animate" button so that when it's clicked by the user, the box is animated by calling element.animate() on it, providing the boxrotationkeyframes and boxrotationtiming objects to describe the animation that should occur. result below we see what the result looks like. notice how before the animation starts running, the box is upright, then upon clicking the "animate!" button, the box is instantly rotated 90° to the left (to correspond to the first keyframe in the animation sequence). then, when the animation finishes running, the box instantaneously leaps back to its original state and is upright once again. give it a try b...
...we see what the result looks like. notice how before the animation starts running, the box is upright, then upon clicking the "animate!" button, the box is instantly rotated 90° to the left (to correspond to the first keyframe in the animation sequence). then, when the animation finishes running, the box instantaneously leaps back to its original state and is upright once again. give it a try below! follow the white rabbit example in the follow the white rabbit example, the white rabbit's animation is formed by coupling a keyframeeffect with an animation object. the keyframeeffect takes an object of timing properties, which is where we pass in fill. forwards makes the rabbit retain its last keyframe rather than reverting to its unanimated state: // create a set of keyframes to slide th...
Element.scrollHeight - Web APIs
the scrollheight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. 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. ...
...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. ...
... est laborum. padding-bottom left top right bottom margin-top margin-bottom border-top border-bottom problems and solutions determine if an element has been totally scrolled the following equivalence returns true if an element is at the end of its scroll, false if it isn't. 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...
... border-radius: 5px; } javascript function checkreading () { if (checkreading.read) { return; } checkreading.read = this.scrollheight - this.scrolltop === this.clientheight; document.registration.accept.disabled = document.getelementbyid("nextstep").disabled = !checkreading.read; checkreading.noticebox.innerhtml = checkreading.read ? ...
Event.eventPhase - Web APIs
Web › API › Event › eventPhase
constant value description event.none 0 no event is being processed at this time. event.capturing_phase 1 the event is being propagated through the target's ancestor objects. ...
... constant value description event.none 0 no event is being processed at this time. event.capturing_phase 1 the event is being propagated through the target's ancestor objects. ...
... constant value description event.none 0 no event is being processed at this time. event.capturing_phase 1 the event is being propagated through the target's ancestor objects. ...
...ent.bubbling_phase 3 the event is propagating back up through the target's ancestors in reverse order, starting with the parent, and eventually reaching the containing window. this is known as bubbling, and occurs only if event.bubbles is true. event listeners registered for this phase are triggered during this process. for more details, see section 3.1, event dispatch and dom event flow, of the dom level 3 events specification. example html <h4>event propagation chain</h4> <ul> <li>click 'd1'</li> <li>analyse event propagation chain</li> <li>click next div and repeat the experience</li> <li>change capturing mode</li> <li>repeat the experience</li> </ul> <input type="checkbox" id="chcapture" /> <label for="chcapture">use capturing</label> <div id="d1">d1 <div i...
EventTarget.removeEventListener() - Web APIs
tly registered eventlistener on the eventtarget has no effect. example this example shows how to add a mouseover-based event listener that removes a click-based event listener. ...
... listener that removes a click-based event listener. ...
... living standard dom4the definition of 'eventtarget.re...
... living standard dom4the definition of 'eventtarget.removeeventlistener()' in that specification. ...
Fetch API - Web APIs
Web › API › Fetch API
the fetch api provides an interface for fetching resources (including across the network). it will seem familiar to anyone who has used xmlhttprequest, but the new api provides a more powerful and flexible feature set. concepts and usage fetch provides a generic definition of request and response 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, ...
...ork failure or if anything prevented the request from completing. fetch() won't can receive cross-site cookies; you can’t can establish a cross site session using fetch. set-cookie headers from other sites are silently ignored. fetch() won’t send cookies, unless you set credentials: 'same-origin'. in august 2017, the spec changed the default credentials policy to 'same-origin'. the following browsers shipped and outdated native fetch, and were updated in these versions: firefox version 61.0b13. safari version 12. chrome version 68. if you are targetting older versions of these browsers, be sure to include credentials: 'same-origin' init option on all api requests that may be affected by cookies/user login state. note: find out more about usi...
...e sure to include credentials: 'same-origin' init option on all api requests that may be affected by cookies/user login state. note: find out more about using the fetch api features in using fetch, and study concepts in fetch basic concepts. aborting a fetch browsers have started to add experimental support for the abortcontroller and abortsignal interfaces (aka the abort api), which allow operations like fetch and xhr to be aborted if they have not already completed. see the interface pages for more details. fetch interfaces windoworworkerglobalscope.fetch() the fetch() method used to fetch a resource. headers represents response/request headers, allowing you to query them and take different actions depending on the results. request represents a resource request. respons...
... interfaces windoworworkerglobalscope.fetch() the fetch() method used to fetch a resource. headers represents response/request headers, allowing you to query them and take different actions depending on the results. request represents a resource request. response represents the response to a request. fetch mixin body provides methods relating to the body of the response/request, allowing you to declare what its content type is and how it should be handled. specifications specification status comment fetch living standard initial definition ...
FileException - Web APIs
cribed in file writer and adds several new error codes. basic concepts synchronous apis do not have error callbacks, which makes it difficult to catch errors. the added complexity of using webworkers with this api makes debugging even more challenging. to simplify things a bit, wrap your worker code in a try/catch. when errors occur, forward them to the main app using postmessage() as in the following: function onerror(e) { postmessage('error:' + e.tostring()); } try { //error is thrown if "log.txt" already exists. var fileentry = fs.root.getfile('log.txt', {create: true, exclusive:true}0; } catch (e) { onerrror(e); } the sample code was borrowed from html5rocks attribute attribute type description code unsigned short the most appropriate error ...
... condition. constants note: do not rely on the numeric values of the constants, which might change as the specifications continue to change. use the constant names instead. constant value description encoding_err 5 the url is malformed. make sure that the url is complete and valid. invalid_modification_err 9 the modification requested is not allowed. examples of invalid modifications include moving a directory into its own child or moving a file into its parent directory without changing its name. invalid_state_err 7 the operation cannot be performed on the current state of the interface object. for example, the state that was cached in an interface object has changed since it was last read from disk. no_modificatio...
...examples of invalid modifications include moving a directory into its own child or moving a file into its parent directory without changing its name. invalid_state_err 7 the operation cannot be performed on the current state of the interface object. for example, the state that was cached in an interface object has changed since it was last read from disk. no_modification_allowed_err 6 the state of the underlying file system prevents any writing to a file or a directory. not_found_err 1 a required file or directory could not be found at the time an operation was processed. for example, a file did not exist but was being opened. not_readable_err 4 the file or directory cannot be read, typically due to permission problems that ...
... locked by another application). path_exists_err 12 the file or directory with the same path already exists. quota_exceeded_err 10 either there's not enough remaining storage space or the storage quota was reached and the user declined to give more space to the database. security_err 2 access to the files were denied for one of the following reasons: the files might be unsafe for access within a web application. too many calls are being made on file resources. other unspecified security error code or situations. type_mismatch_err 11 the user has attempted to look up a file or directory, but the entry found is of the wrong type. for example, the app is accessing a directoryentry when the...
FileList - Web APIs
Web › API › FileList
ls on this usage. note: prior to gecko 1.9.2, the input element only supported a single file being selected at a time, meaning that the filelist would contain only one file. starting with gecko 1.9.2, if the input element's multiple attribute is true, the filelist may contain multiple files. ...
... a single file being selected at a time, meaning that the filelist would contain only one file. starting with gecko 1.9.2, if the input element's multiple attribute is true, the filelist may contain multiple files. using the file list all <input> element nodes have a files attribute of type filelist on them which allows access to the items in this list. ...
...ist would contain only one file. starting with gecko 1.9.2, if the input element's multiple attribute is true, the filelist may contain multiple files. using the file list all <input> element nodes have a files attribute of type filelist on them which allows access to the items in this list. for example, if the html includes the following file input: <input id="fileitem" type="file"> the following line of code fetches the first file in the node's file list as a file object: var file = document.getelementbyid('fileitem').files[0]; method overview file item(index); properties attribute type description length integer a read-only value indicating the number of files in the list. methods item() returns a file object representing th...
...ut = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; var file; // loop through files for (var i = 0; i < files.length; i++) { // get item file = files.item(i); //or file = files[i]; alert(file.name); } here is a complete example. ...
FileSystemDirectoryReader.readEntries() - Web APIs
defined. example in this example, a drop zone is created, which responds to the drop event by scanning through the dropped files and directories, outputting a hierarchical directory listing. html content the html establishes the drop zone itself, which is a <div> element with the id "dropzone", and an unordered list element with the id "listing". <p>drag files and/or directories to the box below!</p> <div id="dropzone"> <div id="boxtitle"> drop files here </div> </div> <h2>directory tree:</h2> <ul id="listing"> </ul> css content the styles used by the example are shown here. #dropzone { text-align: center; width: 300px; height: 100px; margin: 10px; padding: 10px; border: 4px dashed red; border-radius: 10px; } #boxtitle { display: table-cell; vertical-alig...
...scanfiles() function. this function takes as input a filesystementry representing an entry in the file system to be scanned and processed (the item parameter), and an element into which to insert the list of contents (the container parameter). note that to read all files in a directory, readentries needs to be called repeatedly until it returns an empty array. in chromium-based browsers, the following example will only return a max of 100 entries. let dropzone = document.getelementbyid("dropzone"); let listing = document.getelementbyid("listing"); function scanfiles(item, container) { let elem = document.createelement("li"); elem.innerhtml = item.name; container.appendchild(elem); if (item.isdirectory) { let directoryreader = item.createreader(); let directorycontainer = ...
... in the next level down in the list's hierarchy. after that, directoryreader.readentries() is called to read in all the entries in the directory. these are each, in turn, passed into a recursive call to scanfiles() to process them. any of them which are files are simply inserted into the list; any which are directories are inserted into the list and a new level of the list's hierarchy is added below, and so forth. then come the event handlers. first, we prevent the dragover event from being handled by the default handler, so that our drop zone can receive the drop: dropzone.addeventlistener("dragover", function(event) { event.preventdefault(); }, false); the event handler that kicks everything off, of course, is the handler for the drop event: dropzone.addeventlistener("drop", funct...
.... then we iterate over the items in the list of dropped items. for each one, we call its webkitgetasentry() method to obtain a filesystementry representing the file. if that's successful, we call scanfiles() to process the item—either by adding it to the list if it's just a file or by adding it and walking down into it if it's a directory. result you can see how this works by trying it out below. find some files and directories and drag them in, and take a look at the resulting output. specifications specification status comment file and directory entries api draft draft of proposed api this api has no official w3c or whatwg specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd ...
Using the Geolocation API - Web APIs
fined 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 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 wi...
...on is obtained. watching the current position if the position data changes (either by device movement or if more accurate geo information arrives), you can set up a callback function that is called with that updated position information. this is done using the watchposition() function, which has the same input parameters as getcurrentposition(). the callback function is called multiple times, allowing the browser to either update your location as you move, or provide a more accurate location as different techniques are used to geolocate you. the error callback function, which is optional just as it is for getcurrentposition(), can be called repeatedly. note: you can use watchposition() without an initial getcurrentposition() call. const watchid = navigator.geolocation.watchposition((pos...
...umber that can be used to uniquely identify the requested position watcher; you use this value in tandem with the clearwatch() method to stop watching the user's location. navigator.geolocation.clearwatch(watchid); fine tuning the response both getcurrentposition() and watchposition() accept a success callback, an optional error callback, and an optional positionoptions object. this object allows you to specify whether to enable high accuracy, a maximum age for the returned position value (up until this age it will be cached and reused if the same position is requested again; after this the browser will request fresh position data), and a timeout value that dictates how long the browser should attempt to get the position data for, before it times out. a call to watchposition could look ...
...or watchposition(), expects a geolocationpositionerror object instance as its first parameter. this object type contains two properties, a code indicating what type of error has been returned, and a human-readable message that describes what the error code means. you could use it like so: function errorcallback(error) { alert(`error(${error.code}): ${error.message}`); }; examples in the following example the geolocation api is used to retrieve the user's latitude and longitude. if sucessful, the available hyperlink is populated with an openstreetmap.org url that will show their location. body { padding: 20px; background-color:#ffffc9 } button { margin: .5rem 0; } html <button id = "find-me">show my location</button><br/> <p id = "status"></p> <a id = "map-link" target="_bl...
HTMLButtonElement - Web APIs
the htmlbuttonelement interface provides properties and methods (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <button> elements. ...
...is of type="menu". htmlbuttonelement.name is a domstring representing the name of the object when submitted with a form. html5 if specified, it must not be the empty string. htmlbuttonelement.tabindex is a long that represents this element's position in the tabbing order. htmlbuttonelement.type is a domstring indicating the behavior of the button. this is an enumerated attribute with the following possible values: submit: the button submits the form. this is the default value if the attribute is not specified, html5 or if it is dynamically changed to an empty or invalid value. reset: the button resets the form. button: the button does nothing. menu: the button displays a menu. htmlbuttonelement.willvalidate read only is a boolean indicating whether the button is a can...
...status comment html living standardthe definition of 'htmlbuttonelement' in that specification. living standard html 5.2the definition of 'htmlbuttonelement' in that specification. recommendation the menu attribute and type="menu" value have been removed. html 5.1the definition of 'htmlbuttonelement' in that specification. ...
...e have been removed. html 5.1the definition of 'htmlbuttonelement' in that specification. recommendation the following attribute has been added: menu. the type attribute can take one more value, "menu". html5the definition of 'htmlbuttonelement' in that specification. recommendation the attributes tabindex and accesskey, are now defined on htmlelement. the following attributes have been added: autofocus, formaction, formenctype, formmethod, formnovalidate, formtarget, labels, validity, validationmessage, and willvalidate. the following methods have been added: checkvalidity(), setcustomvalidity(). the type attribute is no more read-only. document object model (dom) level 2 html specificationthe definition of 'htmlbuttonelement' in that sp...
HTMLIFrameElement - Web APIs
the htmliframeelement interface provides special properties and methods (beyond those of the htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of inline frame elements. ...
...ndale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmliframeelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmliframeelement.align is a domstring that specifies the alignment of the frame with respect to the surrounding context. htmliframeelement.allow is a list of origins the the frame is allowed to display content from. this attribute also accepts the values self and src which represent the origin in the iframe's src attribute. the default value is src. htmliframeelement.allowfullscreen is a boolean indicating whether the inline frame is willing to be placed into full screen mode. see using full-screen mode for details. htmliframeelem...
... htmliframeelement.contentdocument read only returns a document, the active document in the inline frame's nested browsing context. ...
...ntent to display in the frame. htmliframeelement.width is a domstring that reflects the width html attribute, indicating the width of the frame. methods inherits properties from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmliframeelement' in that specification. living standard the following property has been added: allowfullscreen. html5the definition of 'htmliframeelement' in that specification. recommendation the following properties are now obsolete: scrolling, marginwidth, marginheight, longdesc, frameborder, and align. the following properties have been added: srcdoc, sandbox, and contentwindow. document object model (dom) level 2 html specificati...
HTMLImageElement.align - Web APIs
container. you should instead use the css propertiy vertical-align, which does in fact also work on images despite its name. you can also use the float property to float the image to the left or right margin. the align property reflects the html align content attribute. syntax htmlimageelement.align = alignmode; alignmode = htmlimageelement.align; value a domstring specifying one of the following strings which set the alignment mode for the image. baseline alignment these three values specify the alignment of the element relative to the text baseline. these should be replaced by using the css vertical-align property. bottom the bottom edge of the image is to be aligned vertically with the current text baseline. default value. middle the center of the object should be aligned ve...
...ject should be aligned vertically with the current baseline. it may be worth noting that vertical-align offers several additional options for its value; you may wish to consider these when changing your code to use it. floating images horizontally the left and right properties don't affect the baseline-relative alignment. ...
... aligned vertically with the current baseline. it may be worth noting that vertical-align offers several additional options for its value; you may wish to consider these when changing your code to use it. floating images horizontally the left and right properties don't affect the baseline-relative alignment. ...
...lly with the current baseline. it may be worth noting that vertical-align offers several additional options for its value; you may wish to consider these when changing your code to use it. floating images horizontally the left and right properties don't affect the baseline-relative alignment. instead, they cause the image to "float" to the left or right margin, allowing the following text to flow around the image. you should instead use the css float property, specifying as the value either left or right. left floats the image over to place the left edge flush against the curent margin. any text that follows will flow against the image's right edge. right floats the image to place its right edge flush against the right margin. subsequent text will flow along the image's left edge. ...
HTMLSelectElement.add() - Web APIs
d to the method is an ancestor of the htmlselectelement. examples creating elements from scratch var sel = document.createelement("select"); var opt1 = document.createelement("option"); var opt2 = document.createelement("option"); opt1.value = "1"; opt1.text = "option: value 1"; opt2.value = "2"; opt2.text = "option: value 2"; sel.add(opt1, null); sel.add(opt2, null); /* produces the following, conceptually: <select> <option value="1">option: value 1</option> <option value="2">option: value 2</option> </select> */ the before parameter is optional. so the following is accepted. ... sel.add(opt1); sel.add(opt2); ... append to an existing collection var sel = document.getelementbyid("existinglist"); var opt = document.createelement("option"); opt.value = "3"; opt.tex...
...tion> <option value="2">option: value 2</option> </select> */ the before parameter is optional. so the following is accepted. ... sel.add(opt1); sel.add(opt2); ... append to an existing collection var sel = document.getelementbyid("existinglist"); var opt = document.createelement("option"); opt.value = "3"; opt.text = "option: value 3"; sel.add(opt, null); /* takes the existing following select object: <select id="existinglist"> <option value="1">option: value 1</option> <option value="2">option: value 2</option> </select> and changes it to: <select id="existinglist"> <option value="1">option: value 1</option> <option value="2">option: value 2</option> <option value="3">option: value 3</option> </select> */ the before parameter is optional. s...
...t object: <select id="existinglist"> <option value="1">option: value 1</option> <option value="2">option: value 2</option> </select> and changes it to: <select id="existinglist"> <option value="1">option: value 1</option> <option value="2">option: value 2</option> <option value="3">option: value 3</option> </select> */ the before parameter is optional. ...
...option> <option value="3">option: value 3</option> </select> */ the before parameter is optional. so the following is accepted. ... sel.add(opt); ... ...
HTMLTextAreaElement - Web APIs
the htmltextareaelement interface provides special properties and methods for manipulating the layout and presentation of <textarea> elements. ...
...s the direction in which selection occurred. this is "forward" if selection was performed in the start-to-end direction of the current locale, or "backward" for the opposite direction. this can also be "none" if the direction is unknown. selectionend unsigned long: returns / sets the index of the end of selected text. if no text is selected, contains the index of the character that follows the input cursor. on being set, the control behaves as if setselectionrange() had been called with this as the second argument, and selectionstart as the first argument. selectionstart unsigned long: returns / sets the index of the beginning of selected text. if no text is selected, contains the index of the character that follows the input cursor. on being set, the control behaves a...
...roperty of this interface: input event fires when the value of an <input>, <select>, or <textarea> element has been changed. examples autogrowing textarea example make a textarea autogrow while typing: javascript function autogrow (ofield) { if (ofield.scrollheight > ofield.clientheight) { ofield.style.height = ofield.scrollheight + "px"; } } css textarea.noscrollbars { overflow: hidden; width: 300px; height: 100px; } html <form> <fieldset> <legend>your comments</legend> <p><textarea class="noscrollbars" onkeyup="autogrow(this);"></textarea></p> <p><input type="submit" value="send" /></p> </fieldset> </form> insert html tags example insert some html tags or smiles or any custom text in a textarea. javascript function insertmetachars(sstarttag...
...pecifications specification status comment html living standardthe definition of 'htmltextareaelement' in that specification. living standard html5the definition of 'htmltextareaelement' in that specification. recommendation the attributes tabindex and accesskey, as well as the methods blur() and focus() are now defined on htmlelement. the following attributes have been added: autofocus, placeholder, dirname, wrap, maxlength, required, textlength, labels, selectionstart, selectionend, selectiondirection, validity, validationmessage, and willvalidate. the following methods have been added: checkvalidity(), setcustomvalidity(), and setselectionrange(). document object model (dom) level 2 html specificationthe definition of 'htm...
HashChangeEvent - Web APIs
the hashchangeevent interface represents events that fire when the fragment identifier of the url has changed. the fragment identifier is the part of the url that follows (and includes) the # symbol. ...
... the hashchangeevent interface represents events that fire when the fragment identifier of the url has changed. the fragment identifier is the part of the url that follows (and includes) the # symbol. ...
...ts parent, event. hashchangeevent.newurl read only the new url to which the window is navigating. hashchangeevent.oldurl read only the previous url from which the window was navigated. methods this interface has no methods of its own, but inherits the methods of its parent, event. ...
...hashchange", funcref, false); basic example function locationhashchanged() { if (location.hash === '#somecoolfeature') { somecoolfeature(); } } window.addeventlistener('hashchange', locationhashchanged); polyfill there are several fallback scripts listed on the modernizr github page. basically, those scripts check the location.hash at a regular interval. ...
Headers - Web APIs
Web › API › Headers
these actions include retrieving, setting, adding to, and removing headers from the list of the request's headers. a headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. you can add to this using methods like append() (see examples.) in all methods of this interface, header names are matched by case-insensitive byte sequence. for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. ...
...e: you can find more out about the available headers by reading our http headers reference. constructor headers() creates a new headers object. methods headers.append() appends a new value onto an existing header inside a headers object, or adds the header if it does not already exist. headers.delete() deletes a header from a headers object. ...
... allowing to go through all key/value pairs contained in this object. headers.foreach() executes a provided function once for each array element. headers.get() returns a bytestring sequence of all the values of a header within a headers object with a given name. headers.has() returns a boolean stating whether a headers object contains a certain header. headers.keys() returns an iterator allowing you to go through all keys of the key/value pairs contained in this object. headers.set() sets a new value for an existing header inside a headers object, or adds the header if it does not already exist. headers.values() returns an iterator allowing you to go through all values of the key/value pairs contained in this object. note: to be clear, the difference between headers.set() and h...
... are automatically sorted in lexicographical order, and values from duplicate header names are combined. obsolete methods headers.getall() used to return an array of all the values of a header within a headers object with a given name; this method has now been deleted from the spec, and headers.get() now returns all values of a given name instead of just the first one. ...
Working with the History API - Web APIs
onpopstate event. adding and modifying history entries using pushstate() changes the referrer that gets used in the http header for xmlhttprequest objects created after you change the state. the referrer will be the url of the document whose window is this at the time of creation of the xmlhttprequest object. example of pushstate() method suppose http://mozilla.org/foo.html executes the following javascript: let stateobj = { foo: "bar", } history.pushstate(stateobj, "page 2", "bar.html") this will cause the url bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists. suppose now that the user navigates to http://google.com, then clicks the back button. at this point, the url bar will display http://mozilla.org...
...eter is optional; if it isn't specified, it's set to the document's current url. note: in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) through gecko 5.0 (firefox 5.0 / thunderbird 5.0 / seamonkey 2.2), the passed object is serialized using json. starting in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3), the object is serialized using the structured clone algorithm. this allows a wider variety of objects to be safely passed. in a sense, calling pushstate() is similar to setting window.location = "#foo", in that both will also create and activate another history entry associated with the current document. but pushstate() has a few advantages: the new url can be any url in the same origin as the current url. in contrast, setting window.location keeps you at the same...
...state object or url of the current history entry in response to some user action. note: in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) through gecko 5.0 (firefox 5.0 / thunderbird 5.0 / seamonkey 2.2), the passed object is serialized using json. starting in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3), the object is serialized using the structured clone algorithm. this allows a wider variety of objects to be safely passed. example of replacestate() method suppose http://mozilla.org/foo.html executes the following javascript: let stateobj = { foo: "bar" } history.pushstate(stateobj, "page 2", "bar.html") the explanation of these two lines above can be found at the above section example of pushstate() method section. next, suppose http://mozilla.org/bar.html exec...
...riety of objects to be safely passed. example of replacestate() method suppose http://mozilla.org/foo.html executes the following javascript: let stateobj = { foo: "bar" } history.pushstate(stateobj, "page 2", "bar.html") the explanation of these two lines above can be found at the above section example of pushstate() method section. next, suppose http://mozilla.org/bar.html executes the following javascript: history.replacestate(stateobj, "page 3", "bar2.html") this will cause the url bar to display http://mozilla.org/bar2.html, but won't cause the browser to load bar2.html or even check that bar2.html exists. suppose now that the user navigates to http://www.microsoft.com, then clicks the back button. at this point, the url bar will display http://mozilla.org/bar2.html. if the use...
IDBDatabaseSync - Web APIs
the key path used by the new object store. if a null path is specified, then the object store does not have a key path, and uses out-of-line keys. autoincrement if true, the object store uses a key generator; if false, it does not use one. returns idbobjectstoresync an object to access the newly created object store. exceptions this method can raise an idbdatabaseexception with the following code: constraint_err if an object store with the same name (based on case-sensitive comparison) already exists in the connected database. openobjectstore() opens the object store with the given name in the connected database using the specified mode. idbobjectstoresync openobjectstore ( in domstring name, in optional unsigned short mode ) raises (idbdatabaseexception); parameters...
... mode. idbobjectstoresync openobjectstore ( in domstring name, in optional unsigned short mode ) raises (idbdatabaseexception); parameters name the name of the object store to open. mode the mode that is used to access the object store. returns idbobjectstoresync an object to access the opened object store. exceptions this method can raise an idbdatabaseexception with the following code: not_found_err if an object store with the given name (based on case-sensitive comparison) already exists in the connected database. removeobjectstore() destroys an object store with the given name, as well as all indexes that reference that object store. void removeobjectstore ( in domstring storename ) raises (idbdatabaseexception); parameters storename the name of an ex...
... in the connected database. removeobjectstore() destroys an object store with the given name, as well as all indexes that reference that object store. void removeobjectstore ( in domstring storename ) raises (idbdatabaseexception); parameters storename the name of an existing object store to remove. returns void exceptions this method can raise an idbdatabaseexception with the following code: not_found_err if the object store with the given name (based on case-sensitive comparison) does not exist in the connected database. setversion() sets the version of the connected database. void setversion ( in domstring version ); parameters returns void version the version to store in the database. transaction() creates and returns a transaction, acquiring locks...
...ction, acquiring locks on the given database objects, within the specified timeout duration, if possible. idbtransactionsync transaction ( in optional domstringlist storenames, in optional unsigned int timeout ) raises (idbdatabaseexception); parameters storenames the names of object stores and indexes in the scope of the new transaction. timeout the interval that this operation is allowed to take to acquire locks on all the objects stores and indexes identified in storenames. returns idbtransactionsync an object to access the newly created transaction. exceptions this method can raise an idbdatabaseexception with the following code: timeout_err if reserving all the database objects identified in storenames takes longer than the timeout interval. ...
IDBKeyRange.bound() - Web APIs
Web › API › IDBKeyRange › bound
the bound() method of the idbkeyrange interface creates a new key range with the specified upper and lower bounds. the bounds can be open (that is, the bounds exclude the endpoint values) or closed (that is, the bounds include the endpoint values). by default, the bounds are closed. note: this feature is available in web workers. syntax var myidbkeyrange = idbkeyrange.bound(lower, upper); var myidbkeyrange = idbkeyrange.bound(lower, upper, loweropen); var myidbkeyrange = idbkeyrange.bound(lower, upper, loweropen, upperopen); parameters lower specifies the lower bound of the new key range. upper specifies the upper bound of the new key range. loweropen optional indicates whether the lower bound excludes the endpoint value. the default is false. upperopen optional indicate...
...ey range. upper specifies the upper bound of the new key range. loweropen optional indicates whether the lower bound excludes the endpoint value. the default is false. upperopen optional indicates whether the upper bound excludes the endpoint value. the default is false. return value idbkeyrange: the newly created key range. exceptions this method may raise a domexception of the following type: exception description dataerror the following conditions raise an exception: the lower or upper parameters were not passed a valid key. the lower key is greater than the upper key. the lower key and upper key match and either of the bounds are open. ...
...here we declare a keyrangevalue = idbkeyrange.bound("a", "f"); — a range between values of "a" and "f". we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. ...
...g keyrangevalue as its optional key range value. this means that the cursor will only retrieve records with keys inside that range. this range includes the values "a" and "f", as we haven't declared that they should be open bounds. if we used idbkeyrange.bound("a", "f", true, true);, then the range would not include "a" and "f", only the values between them. ...
IDBObjectStore.add() - Web APIs
workers. syntax var request = objectstore.add(value); var request = objectstore.add(value, key); parameters value the value to be stored. key optional the key to use to identify the record. if unspecified, it results to null. returns an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description readonlyerror the transaction associated with this operation is in read-only mode. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror any of the following conditions apply: the object store uses in-line keys or has a key generator, and a key parameter was provided. ...
... invalidstateerror the idbobjectstore has been deleted or removed. datacloneerror the data being stored could not be cloned by the internal structured cloning algorithm. constrainterror an insert operation failed because the primary key constraint was violated (due to an already existing record with the same primary key value). example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add(). note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = wi...
...ing in the event of success or failure. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBObjectStore.delete() - Web APIs
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. ...
... 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 idbrequest object on which subsequent events related to this operation are fired. the request.result attribute is set to undefined. ...
... domexception of the following types: exception description transactioninactiveerror this object store's transaction is inactive. readonlyerror the object store's transaction mode is read-only. invalidstateerror the object store has been deleted. dataerror the key is not a valid key or a key range. example in the following code snippet, we open a read/write transaction on our database and delete one specific record out of our object store using delete() — a sample record with the key "walk dog". for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { not...
...— a sample record with the key "walk dog". for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction.mode - Web APIs
he transaction (i.e. is the mode to be read-only, or do you want to write to the object stores?) the default value is readonly. note: this feature is available in web workers. syntax var mycurrentmode = idbtransaction.mode; value an idbtransactionmode object defining the mode for isolating access to data in the current object stores: value explanation readonly allows data to be read but not changed. readwrite allows reading and writing of data in existing data stores to be changed. versionchange allows any operation to be performed, including ones that delete and create object stores and indexes. this mode is for updating the version number of transactions that were started using idbdatabase.setversion(). transactions of this mode can...
...note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. at the end, we simply log the mode of the current transaction using mode. ...
... of the current transaction using mode. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...ding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBTransaction.objectStore() - Web APIs
f this method is called on a different transaction object, a different idbobjectstore instance is returned. note: this feature is available in web workers. syntax idbtransaction.objectstore(name); parameters name the name of the requested object store. return value an idbobjectstore object for accessing an object store. ...
...note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. ...
...ing in the event of success or failure. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...ding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IndexedDB API - Web APIs
this api uses indexes to enable high-performance searches of this data. while web storage is useful for storing smaller amounts of data, it is less useful for storing larger amounts of structured data. indexeddb provides a solution. this is the main landing page for mdn's indexeddb coverage — here we provide links to the full api reference and usage guides, browser support details, and some explanation of key concepts. note: this feature is available in web workers. note: indexeddb api is powerful, but may seem too complicated for simple cases. ...
...d update data within a series of transactions. read more about the concepts behind indexeddb. learn to use indexeddb asynchronously from first principles with our using indexeddb guide. combine indexeddb for storing data offline with service workers for storing assets offline, as outlined in making pwas work offline with service workers. note: like most web storage solutions, indexeddb follows a same-origin policy. so while you can access stored data within a domain, you cannot access data across different domains. synchronous and asynchronous operations performed using indexeddb are done asynchronously, so as not to block applications. indexeddb originally included both synchronous and asynchronous apis. the synchronous api was intended for use only with web workers but was remove...
...etrieving 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 record(s) rather than the primary key. this is sometimes faster than using idbobjectstore. idbcursor iterates over object stores and indexes. idbcursorwithvalue iterates over object stores and indexes and re...
...e data from a database in a certain range. idblocaleawarekeyrange defines a key range that can be used to retrieve data from a database in a certain range, sorted according to the rules of the locale specified for a certain index (see createindex()'s optionalparameters.). this interface isn't part of the 2.0 specification. custom event interfaces this specification fires events with the following custom interface: idbversionchangeevent the idbversionchangeevent interface indicates that the version of the database has changed, as the result of an idbopendbrequest.onupgradeneeded event handler function. obsolete interfaces an early version of the specification also defined the following, now removed, interfaces. they are still documented in case you need to update previously writt...
compareVersion - Web APIs
e 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 location of the software on the computer; it is the location of information about the software...
...re 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 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 t...
...as 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 larger (newer) minor number than version. 4 registryname has a larger (newer) major number than version. ...
...registryname has a larger (newer) release number than version. 3 registryname has a larger (newer) minor number than version. 4 registryname has a larger (newer) major number than version. the following constants can be used to check the value returned by compareversion: int major_diff = 4; int minor_diff = 3; int rel_diff = 2; int bld_diff = 1; int equal = 0; in communicator 4.5, the following constants are defined and available for checking the value returned by compareversion: <code>installtrigger.major_diff installtrigger.minor_diff installtrigger.rel_diff installtrigger.bld_diff installtrigger.equal </code> description the compareversion method compares the version of an installed file or package with a specified version. it is often used as a check against which to initiate...
KeyboardEvent.code - Web APIs
handle keyboard events in a game this example establishes an event listener for keydown events that handle keyboard input for a game that uses the typical "wasd" keyboard layout for steering forward, left, backward, and right. this will use the same four keys physically regardless of what the actual corresponding characters are, such as if the user is using an azerty key...
...transitions or animat...
...transitions or animations could be used to make the ship's movement smoother, too. ...
...transitions or animations could be used to make the ship's movement smoother, too. ...
LockedFile - Web APIs
the position of the reading/writing pointer within the file. events handler lockedfile.oncomplete the complete event is triggered each time a read or write operation is successful. lockedfile.onabort the abort event is triggered each time the abort() method is called. lockedfile.onerror the error event is triggered each time something goes wrong. ...
... each time a read or write operation is successful. lockedfile.onabort the abort event is triggered each time the abort() method is called. lockedfile.onerror the error event is triggered each time something goes wrong. methods lockedfile.getmetadata() allows to retrieve the file metadata (size and date of the last modification). returns a filerequest. lockedfile.readasarraybuffer() allows to retrieve a part of the content of the file as an arraybuffer. returns a filerequest object. ...
...od is called. lockedfile.onerror the error event is triggered each time something goes wrong. methods lockedfile.getmetadata() allows to retrieve the file metadata (size and date of the last modification). returns a filerequest. lockedfile.readasarraybuffer() allows to retrieve a part of the content of the file as an arraybuffer. returns a filerequest object. lockedfile.readastext() allows to retrieve a part of the content of the file as a string. returns a filerequest object. lockedfile.write() allows to write some data in the file starting at the location offset. returns a filerequest object. lockedfile.append() allows to write some data at the end of the file. returns a filerequest object. lockedfile.truncate() allows to truncate the file's content. returns a filerequest ...
... lockedfile.abort() makes the lockedfile inactive and cancels all ongoing operations. ...
MediaStreamConstraints.audio - Web APIs
he audio source, the call to getusermedia() will fail. if false, no audio track is included. mediatrackconstraints a constraints dictionary detailing the preferable and/or required values or ranges of values for the track's constrainable properties. if you specify constraints, an audio track meeting the constraints is required. ...
...e samples below need the microphone feature enabled. see security in mediadevices.getusermedia() for details and examples on how to configure this. using a boolean value in this example, we provide a simple value of true for the audio property. this tells getusermedia() that we require an audio track, but we don't care about any specifics beyond that. ...
...r for a click event which uses getusermedia() to obtain an audio-only stream with no specific constraints, then attaches the resulting stream to an <audio> element once the stream is returned. ...
...rr.name + ": " + err.message)); }, false); here we see an event handler for a click event which calls getusermedia(), specifying a set of audio constraints requesting that echo cancellation be enabled and that, if possible, the sample rate be 8 bits per sample instead of the more common 16 bits (possibly as a bandwidth saving measure). as long as an audio input device is available and the user allows it to be used, an audio track will be included in the resulting stream, and it will match the specified constraints as well as possible. result specifications specification status comment media capture and streamsthe definition of 'mediastreamconstraints.audio' in that specification. candidate recommendation initial specification. ...
MediaStream Image Capture API - Web APIs
the mediastream image capture api is an api for capturing images or videos from a photographic device. in addition to capturing data, it also allows you to retrieve information about device capabilities such as image size, red-eye reduction and whether or not there is a flash and what they are currently set to. conversely, the api allows the capabilities to be configured within the constraints what the device allows. mediastream image capture concepts and usage the process of retrieving an image or video stream happens as described below. the example code is adapted from chrome's image capture examples. ...
...this method returns a promise that resolves with a mediastream object. navigator.mediadevices.getusermedia({ video: true }) .then(mediastream => { // do something with the stream. ...
...this method returns a promise that resolves with a mediastream object. navigator.mediadevices.getusermedia({ video: true }) .then(mediastream => { // do something with the stream. }) next, isolate the visual part of the media stream. do this by calling mediastream.getvideotracks(). ...
...more specific capabilities to be requested. this method returns a promise that resolves with a mediastream object. navigator.mediadevices.getusermedia({ video: true }) .then(mediastream => { // do something with the stream. }) next, isolate the visual part of the media stream. do this by calling mediastream.getvideotracks(). this returns an array of mediastreamtrack objects. the code below assumes that the first item in the mediastreamtrack array is the one to use. you can use the properties of the mediastreamtrack objects to select the one you need. const track = mediastream.getvideotracks()[0]; at this point, you might want to configure the device capabilities before capturing an image. you can do this by calling applyconstraints() on the track object before doing anything else...
PaymentRequest.show() - Web APIs
on says this can't be done, some browsers, including firefox, support multiple active payment requests at a time. if your architecture doesn't necessarily have all of the data ready to go at the moment it instantiates the payment interface by calling show(), specify the detailspromise parameter, providing a promise that is fulfilled once the data is ready. if this is provided, show() will not allow the user to interact with the payment interface until the promise is fulfilled, so that data can be updated prior to the user engaging with the payment process. processing the result and, if necessary, calling paymentresponse.retry() to retry a failed payment can all be done either asynchronously or synchronously, depending on your needs. for the best user experience, asynchronous solutions are ...
...ror usually means a user cancellation */ } } in this code, the methods checkaddress() and checkshipping(), respectively, check the shipping address and the shipping option changes and supply in response either a paymentdetailsupdate object or a promise to return one; this object contains the fields in the paymentresponse which have been or need to be changed. ...
...values() be a synchronous function, although that may have performance implications you don't want to deal with: function validateresponse(response) { if (checkallvalues(response) { response.complete("success"); } else { response.complete("fail"); } } see the article using promises for more information if you need more information about working with promises. examples in the following example, a paymentrequest object is instantiated before the show() method is called. this method triggers the user agent's built-in process for retrieving payment information from the user. the show() method returns a promise that resolves to a paymentresponse object when the user interaction is complete. the developer then uses the information in the paymentresponse object to format and send ...
.../ process response here, including sending payment instrument // (e.g., credit card) information to the server. // paymentresponse.methodname contains the selected payment method // paymentresponse.details contains a payment method specific response await response.complete("success"); } catch (err) { console.error("uh oh, something bad happened", err.message); } } the following example shows how to update the payment sheet as it's being presented to the end-user. async function requestpayment() { // we start with au$0 as the total. const initialdetails = { total: { label: "total", amount: { value: "0", currency: "aud" }, }, }; const request = new paymentrequest(methods, initialdetails, options); // check if the the user supports the `me...
Using the Payment Request API - Web APIs
unction() { // finish handling payment }); }) } }) paymentrequest.abort() can be used to abort the payment request if required. detecting availability of the payment request api you can effectively detect support for the payment request api by checking if the user's browser supports paymentrequest, i.e. if (window.paymentrequest). in the following snippet, a merchant page performs this check, and if it returns true updates the checkout button to use paymentrequest instead of legacy web forms. const checkoutbutton = document.getelementbyid('checkout-button'); if (window.paymentrequest) { let request = new paymentrequest(buildsupportedpaymentmethodnames(), buildshoppingcartdetails()); checkoutbutton.addeventlistener('click', fu...
...hoppingcartdetails()); }); } note: see our feature detect support demo for the full code. checking whether users can make payments checking whether users can make payments is always useful. here's a couple of related techniques. customizing the payment button one useful technique to employ is customizing the payment request button depending on whether users can make payments. in the following snippet we do just this — depending on whether the user can make a fast payment or needs to add payment credentials first, the title of the checkout button changes between "fast checkout with w3c" and "setup w3c checkout". in both cases, the checkout button calls paymentrequest.show(). const checkoutbutton = document.getelementbyid('checkout-button'); checkoutbutton.innertext = "loading..."...
...function(error) { // the user may have turned off the querying functionality in their // privacy settings. the website does not know whether they can make // a fast payment, so pick a generic title. checkoutbutton.innertext = "checkout with w3c"; }); } 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.
...entrequest.canmakepayment() .then(function(res) { if (res) { // the payment handler has pre-authorized a transaction // with some static amount, e.g., usd $1.00. } else { // pre-authorization failed or payment handler not installed. } }) .catch(function(ex1) { // unexpected error occurred. }); the payment handler would include the following code: self.addeventlistener('canmakepayment', function(evt) { // pre-authorize here. let preauthsuccess = ...; evt.respondwith(preauthsuccess); }); this payment handler would need to live in a service worker at https://example.com/preauth scope. note: see our pre-authorizing transactions demo for the full code. ...
Payment Request API - Web APIs
t easy for users to jump from desktop to mobile and back again when buying things. consistent error handling: the browser can check the validity of card numbers, and can tell the user if a card has expired (or is about to expire). the browser can automatically suggest which card to use based on past usage patterns or restrictions from the merchant (e.g, "we only accept visa or mastercard"), or allow the user to say which is their default/favorite card. to request a payment, a web page creates a paymentrequest object in response to a user action that initiates a payment, such as clicking a "purchase" button. the paymentrequest allows the web page to exchange information with the user agent while the user provides input to complete the transaction. you can find a complete guide in using the...
... interfaces paymentaddress an object that contains address information; used for billing and shipping addresses, for example. paymentrequest an object that provides the api for creating and managing the user agent's payment interface. ...
... of the payment request in response to a user action. paymentmethodchangeevent represents the user changing payment instrument (e.g., switching from a credit card to debit card). paymentresponse an object returned after the user selects a payment method and approves a payment request. merchantvalidationevent represents the browser requiring the merchant (website) to validate themselves as allowed to use a particular payment handler (e.g., registered as allowed to use apple pay). dictionaries addresserrors a dictionary containing strings providing descriptive explanations of any errors in any paymentaddress entries which have errors. payererrors a dictionary containing strings providing descriptive explanations of any errors in related to paymentresponse's email, phone, and na...
...ptive explanations of any errors in any paymentaddress entries which have errors. payererrors a dictionary containing strings providing descriptive explanations of any errors in related to paymentresponse's email, phone, and name attributes. paymentdetailsupdate an object describing changes that need to be made to the payment details in the event that the server needs to update information following the instantiation of the payment interface but before the user begins to interact with it. related dictionaries for the basic card specification basiccardchangedetails an object providing redacted address information that is provided as the methoddetails on the paymentmethodchange event sent to the paymentrequest when the user changes payment information. basiccarderrors an object prov...
PerformancePaintTiming - Web APIs
tion 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. ...
... performanceentry.name returns either "first-paint" or "first-contentful-paint". performanceentry.starttime returns the timestamp when the paint ocurred. performanceentry.duration returns 0. methods this interface ha...
...solas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">performancepainttiming</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but it extends the following performanceentry properties (for "paint" performance entry types) by qualifying and constraining the properties as follows: performanceentry.entrytype returns "paint". performanceentry.name returns either "first-paint" or "first-contentful-paint". performanceentry.starttime returns the timestamp when the paint ocurred. performanceentry.duration returns 0. methods this interface has no methods. example function showpainttimings() { if (window.performance) { let performance = window.performance; ...
...the time to first-contentful-paint was 2787.460 milliseconds. specifications specification status comment paint timingthe definition of 'performancepainttiming' in that specification. working draft initial definition. ...
Performance Timeline - Web APIs
the performance timeline api defines extensions to the performance interface to support client-side latency measurements within applications. the extensions provide interfaces to retrieve performance entry metrics based on specific filter criteria. the standard also includes interfaces that allow an application to define performance observer callbacks that are notified when specific performance events are added to the browser's performance timeline. this document provides an overview of the standard's interfaces. for more details about the interfaces, see the reference pages and using performance timeline. performance extensions the performance timeline api extends the performance interface with three methods that provide different mechanisms to get a set of performance records (metrics),...
...the recorded performance entries based on the specified name and optionally the performance type. getentriesbytype() returns the recorded performance entries based on the specified performance type. performanceentry interface the performanceentry interface encapsulates a single performance entry — that is, a single data point or metric in the performance timeline. this interface has the following four properties, and these properties are extended (with additional constraints) by other interfaces (such as performancemark): name the name of the performance entry when the metric was created. entrytype the type of performance metric (for example, "mark"). starttime a high resolution timestamp representing the starting time for the performance entry. duration a high resolution tim...
...ing the time value of the duration of the performance event. (some performance entry types have no concept of duration and this value is set to '0' for such types.) this interface includes a tojson() method that returns the serialization of the performanceentry object. the serialization is specific to the performance entry's type. performance observers the performance observer interfaces allow an application to register an observer for specific performance event types, and when one of those event types is recorded, the application is notified of the event via the observer's callback function that was specified when the observer was created. when the observer (callback) is invoked, the callback's parameters include a performance observer entry list that contains only observed performan...
... interface's observe() method (which is used to register the entry types to observe), the performanceobserver interface also has a disconnect() method that stops an observer from receiving further events. performance observers were added to the level 2 version of the standard and were not widely implemented. implementation status a summary of the interfaces' implementation status is provided below, including a link to more detailed information. performance interface extensions: as shown in the performance interface's browser compatibility table, most of these interfaces are broadly implemented by desktop browsers and have less support on mobile devices. performanceentry: as shown in the performanceentry interface's browser compatibility table, most of these interfaces are broadly imple...
Multi-touch interaction - Web APIs
n, preserving a pointer's event state during various event phases is required. this application uses three arrays to cache event state, one cache per target element. // log events flag var logevents = false; // event caches, one per touch target var evcache1 = new array(); var evcache2 = new array(); var evcache3 = new array(); register event handlers event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup. the handler for pointerup is used for the pointercancel, pointerout and pointerleave events, since these four events have the same semantics in this application. function set_handlers(name) { // install event handlers for the given element var el=document.getelementbyid(name); el.onpointerdown = pointerdown_handler; el.onpointermove ...
...e me 2</div> <div id="target3"> tap, hold or swipe me 3</div> <!-- ui for logging/debugging --> <button id="log" onclick="enablelog(event);">start/stop event logging</button> <button id="clearlog" onclick="clearlog(event);">clear the log</button> <p></p> <output></output> </body> miscellaneous functions these functions support the application but aren't directly involved with the event flow. cache management these functions manage the global event caches evcache1, evcache2 and evcache3. function get_cache(ev) { // return the cache for this event's target element switch(ev.target.id) { case "target1": return evcache1; case "target2": return evcache2; case "target3": return evcache3; default: log("error with cache handling",ev); } } function push_event(ev) { // sav...
...is event in the target's cache var cache = get_cache(ev); cache.push(ev); } function remove_event(ev) { // remove this event from the target's cache var cache = get_cache(ev); for (var i = 0; i < cache.length; i++) { if (cache[i].pointerid == ev.pointerid) { cache.splice(i, 1); break; } } } update background color the background color of the touch areas will change as follows: no active touches is white; one active touch is yellow; two simultaneous touches is ping and three or more simultaneous touches is lightblue. function update_background(ev) { // change background color based on the number of simultaneous touches/pointers // currently down: // white - target element has no touch points i.e. no pointers down // yellow - one pointer down // pink - two ...
...lement has no touch points i.e. no pointers down // yellow - one pointer down // pink - two pointers down // lightblue - three or more pointers down var evcache = get_cache(ev); switch (evcache.length) { case 0: // target element has no touch points ev.target.style.background = "white"; break; case 1: // single touch point ev.target.style.background = "yellow"; break; case 2: // two simultaneous touch points ev.target.style.background = "pink"; break; default: // three or more simultaneous touches ev.target.style.background = "lightblue"; } } event logging these functions are used send to event activity to the application window (to support debugging and learning about the event flow). // log events flag var lo...
RTCPeerConnection.setRemoteDescription() - Web APIs
r's current offer or answer. this value is an offer or answer received from the remote peer through your implementation of the sessiondescription parameter is technically of type rtcsessiondescriptioninit, but because rtcsessiondescription serializes to be indistinguishable from rtcsessiondescriptioninit, you can also pass in an rtcsessiondescription. ...
...the promise fulfillment handler receives no input parameters. note: the process of changing descriptions actually involves intermediary steps handled by the webrtc layer to ensure that an active connection can be changed without losing the connection if the change does not succeed. see pending and current descriptions in webrtc connectivity for more details on this process. exceptions the following exceptions are reported to the rejection handler for the promise returned by setremotedescription(): invalidaccesserror the content of the description is 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-prans...
...utside 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 its use is strongly discouraged. you should update any existing code to use the promise-based version of setremotedescription() instead. the parameters for the older form of setremotedescription() are described below, to aid in updating existing code. pc.setremotedescription(sessiondescription, successcallback, errorcallback); parameters successcallback a javascript function which accepts no input parameters to be be called once the description has been successfully set. at that time, the offer can be sent to a remote peer via the signaling server. errorcallback a function matching the signautre r...
...set. it is passed a single domexception object explaining why the request failed. this deprecated form of the method returns instantaneously without waiting for the actual setting to be done: in case of success, the successcallback will be called; in case of failure, the errorcallback will be called. exceptions when using the deprecated callback-based version of setremotedescription(), the following exceptions may occur: invalidstateerror the connection's signalingstate is "closed", indicating that the connection is not currently open, so negotiation cannot take place. invalidsessiondescriptionerror the rtcsessiondescription specified by the sessiondescription parameter is invalid. example here we see a function which handles an offer received from the remote peer. this code ...
SVGAngle - Web APIs
Web › API › SVGAngle
h a grad unit. properties unittype the type of the value as specified by one of the svg_angletype_* constants defined on this interface. value the value as a floating point value, in user units. setting this attribute will cause valueinspecifiedunits and valueasstring to be updated automatically to reflect this setting. ...
... valueasstring the value as a domstring value, in the units expressed by unittype. setting this attribute will cause value, valueinspecifiedunits, and unittype to be updated automatically to reflect this setting. ...
.... valueasstring the value as a domstring value, in the units expressed by unittype. setting this attribute will cause value, valueinspecifiedunits, and unittype to be updated automatically to reflect this setting. exceptions on setting: a domexception with code syntax_err is raised if the assigned string cannot be parsed as a valid <angle>. a domexception with code no_modification_allowed_err is raised when the length corresponds to a read-only attribute, or when the object itself is read-only. methods newvaluespecifiedunits reset the value as a number with an associated unittype, thereby replacing the values for all of the attributes on the object. exceptions: a domexception with code not_supported_err is raised if unittype is svg_angletype_unknown or not a valid u...
...specifiedunits reset the value as a number with an associated unittype, thereby replacing the values for all of the attributes on the object. exceptions: a domexception with code not_supported_err is raised if unittype is svg_angletype_unknown or not a valid unit type constant (one of the other svg_angletype_* constants defined on this interface). a domexception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. converttospecifiedunits preserve the same underlying stored value, but reset the stored unit identifier to the given unittype. object attributes unittype, valueinspecifiedunits, and valueasstring might be modified as a result of this method. specifications specification s...
SVGLength - Web APIs
Web › API › SVGLength
igned short the type of the value as specified by one of the svg_lengthtype_* constants defined on this interface. value float the value as a floating point value, in user units. setting this attribute will cause valueinspecifiedunits and valueasstring to be updated automatically to reflect this setting. exceptions on setting: a domexception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. valueinspecifiedunits float the value as a floating point value, in the units expressed by unittype. setting this attribute will cause value and valueasstring to be updated automatically to reflect this setting. exceptions on setting: a domexception with code n...
...when the length corresponds to a read only attribute or when the object itself is read only. valueinspecifiedunits float the value as a floating point value, in the units expressed by unittype. setting this attribute will cause value and valueasstring to be updated automatically to reflect this setting. exceptions on setting: a domexception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. valueasstring domstring the value as a string value, in the units expressed by unittype. setting this attribute will cause value, valueinspecifiedunits, and unittype to be updated automatically to reflect this setting. exceptions on setting: a domexc...
...ng the value as a string value, in the units expressed by unittype. setting this attribute will cause value, valueinspecifiedunits, and unittype to be updated automatically to reflect this setting. exceptions on setting: a domexception with code syntax_err is raised if the assigned string cannot be parsed as a valid <length>. a domexception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. methods name & arguments return description newvaluespecifiedunits(in unsigned short unittype, in float valueinspecifiedunits) void reset the value as a number with an associated unittype, thereby replacing the values for all of the a...
...eset the value as a number with an associated unittype, thereby replacing the values for all of the attributes on the object. exceptions: a domexception with code not_supported_err is raised if unittype is svg_lengthtype_unknown or not a valid unit type constant (one of the other svg_lengthtype_* constants defined on this interface). a domexception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. converttospecifiedunits(in unsigned short unittype) void preserve the same underlying stored value, but reset the stored unit identifier to the given unittype. object attributes unittype, valueinspecifiedunits, and valueasstring might be modified as a result of this...
Selection - Web APIs
Web › API › Selection
ction.tostring() method returns the text contained within the selection, e.g.: var selobj = window.getselection(); window.alert(selobj); note that using a selection object as the argument to window.alert will call the object's tostring method. multiple ranges in a selection a selection object represents the ranges that the user has selected. typically, it holds only one range, accessed as follows: var selobj = window.getselection(); var range = selobj.getrangeat(0); selobj is a selection object range is a range object as the selection api specification notes, the selection api was initially created by netscape and allowed multiple ranges (for instance, to allow the user to select a column from a <table>). however, browsers other than gecko did not implement multiple ranges, and...
...lection when modifying the selection programmatically; it's possible that this may change in the future (see w3c bug 14383 and webkit bug 38696). behavior of selection api in terms of editing host focus changes the selection api has a common behavior (i.e., shared between browsers) that governs how focus behavior changes for editing hosts after certain methods are called. the behavior is as follows: an editing host gains focus if the previous selection was outside of it. a selection api method is called, causing a new selection to be made with the selection range inside the editing host. focus then moves to the editing host. note: the selection api methods may only move focus to an editing host, not to other focusable elements (e.g., <a>). the above behavior applies to selections...
...st gains focus if the previous selection was outside of it. a selection api method is called, causing a new selection to be made with the selection range inside the editing host. focus then moves to the editing host. note: the selection api methods may only move focus to an editing host, not to other focusable elements (e.g., <a>). ...
... methods may only move focus to an editing host, not to other focusable elements (e.g., <a>). the above behavior applies to selections made using the following methods: selection.collapse() selection.collapsetostart() selection.collapsetoend() selection.extend() selection.selectallchildren() selection.addrange() selection.setbaseandextent() and when the range is modified using the following methods: range.setstart() range.setend() range.setstartbefore() range.setstartafter() range.setendbefore() range.setendafter() range.collapse() range.selectnode() range.selectnodecontents() glossary other key terms used in this section. anchor the anchor of a selection is the beginning point of the selection. when making a selection with a mouse, the anchor is where in the do...
Using server-sent events - Web APIs
except that it will be called automatically whenever the server sends a message with the event field set to "ping"; it then parses the json in the data field and outputs that information. when not used over http/2, sse suffers from a limitation to the maximum number of open connections, which can be especially painful when opening multiple tabs, as the limit is per browser and is set to a very low number (6). the issue has been marked as "won't fix" in chrome and firefox. this limit is per browser + domain, which means that you can open 6 sse connections across all of the tabs to www.example1.com and another 6 sse connections to www.example2.com (per stackoverflow). when using http/2, the maximum number of simultaneous http streams is negotiated between the server and the client (defaults ...
... is negotiated between the server and the client (defaults to 100). sending events from the server the server-side script that sends events needs to respond using the mime type text/event-stream. each notification is sent as a block of text terminated by a pair of newlines. for details on the format of the event stream, see event stream format. the php code for the example we're using here follows: date_default_timezone_set("america/new_york"); header("cache-control: no-cache"); header("content-type: text/event-stream"); $counter = rand(1, 10); while (true) { // every second, send a "ping" event. echo "event: ping\n"; $curdate = date(date_iso8601); echo 'data: {"time": "' . $curdate . '"}'; echo "\n\n"; // send a simple message at random intervals. $counter--; if (!$...
... by a pair of newline characters. a colon as the first character of a line is in essence a comment, and is ignored. note: the comment line can be used to prevent connections from timing out; a server can send a comment periodically to keep the connection alive. each message consists of one or more lines of text listing the fields for that message. each field is represented by the field name, followed by a colon, followed by the text data for that field's value. fields each message received has some combination of the following fields, one per line: event a string identifying the type of event described. if this is specified, an event will be dispatched on the browser to the listener for the specified event name; the website source code should use addeventlistener() to listen for named...
... retry the reconnection time to use when attempting to send the event. this must be an integer, specifying the reconnection time in milliseconds. if a non-integer value is specified, the field is ignored. all other field names are ignored. note: if a line doesn't contain a colon, the entire line is treated as the field name with an empty value string. examples data-only messages in the following example, there are three messages sent. the first is just a comment, since it starts with a colon character. as mentioned previously, this can be useful as a keep-alive mechanism if messages might not be sent regularly. the second message contains a data field with the value "some text". the third message contains a data field with the value "another message\nwith two lines". note the newline...
ServiceWorkerContainer.register() - Web APIs
for a service worker registration is set to the directory where the service worker script is located. see the examples section for more information on how it works. return value a promise that resolves with a serviceworkerregistration object. examples the examples described here should be taken together to get a better understanding of how service workers scope applies to a page. the following example uses the default value of scope (by omitting it). the service worker code in this case, if included in example.com/index.html, will control example.com/index.html, as well as pages underneath it, like example.com/product/description.html. if ('serviceworker' in navigator) { // register a service worker hosted at the root of the // site using the default scope. navigator.servicew...
...a service worker hosted at the root of the // site using the default scope. navigator.serviceworker.register('/sw.js').then(function(registration) { console.log('service worker registration succeeded:', registration); }, /*catch*/ function(error) { console.log('service worker registration failed:', error); }); } else { console.log('service workers are not supported.'); } the following code, if included in example.com/index.html, at the root of a site, would apply to exactly the same pages as the example above. remember the scope, when included, uses the page's location as its base. alternatively, if this code were included in a page at example.com/product/description.html, with the javascript file residing at example.com/product/sw.js, then the service worker would only ap...
...}, /*catch*/ function(error) { console.log('service worker registration failed:', error); }); } else { console.log('service workers are not supported.'); } there is frequent confusion surrounding the meaning and use of scope. since a service worker can't have a scope broader than its own location, only use the scope option when you need a scope that is narrower than the default. the following code, if included in example.com/index.html, at the root of a site, would only apply to resources under example.com/product. if ('serviceworker' in navigator) { // declaring scope manually navigator.serviceworker.register('/sw.js', {scope: '/product/'}).then(function(registration) { console.log('service worker registration succeeded:', registration); }, /*catch*/ function(error) { ...
... specifications specification status comment service workersthe definition of 'serviceworkercontainer: register' in that specification. working draft initial definition. ...
Multi-touch interaction - Web APIs
ows how to use touch events for simple single and multi-touch interactions, the basics needed to build application-specific gestures. a live version of this application is available on github. the source code is available on github and pull requests and bug reports are welcome. example this example demonstrates using the touchstart, touchmove, touchcancel, and touchend) touch events for the following gestures: single touch, two (simultaneous) touches, more than two simultaneous touches, 1-finger swipe, and 2-finger move/pinch/swipe. define touch targets the application uses <div> elements to represent four touch areas. <style> div { margin: 0em; padding: 2em; } #target1 { background: white; border: 1px solid black; } #target2 { background: white; border...
..., hold or swipe me 3</div> <div id="target4"> tap, hold or swipe me 4</div> <!-- ui for logging/bebugging --> <button id="log" onclick="enablelog(event);">start/stop event logging</button> <button id="clearlog" onclick="clearlog(event);">clear the log</button> <p></p> <output></output> miscellaneous functions these functions support the application but aren't directly involved with the event flow. update background color the background color of the touch areas will change as follows: no touch is white; one touch is yellow; two simultaneous touches is pink, and three or more simultaneous touches is lightblue. see touch move for information about the background color changing when a 2-finger move/pinch/zoom is detected. function update_background(ev) { // change background color based o...
... follows: no touch is white; one touch is yellow; two simultaneous touches is pink, and three or more simultaneous touches is lightblue. see touch move for information about the background color changing when a 2-finger move/pinch/zoom is detected. ...
... color changing when a 2-finger move/pinch/zoom is detected. function update_background(ev) { // change background color based on the number simultaneous touches // in the event's targettouches list: // yellow - one tap (or hold) // pink - two taps // lightblue - more than two taps switch (ev.targettouches.length) { case 1: // single tap` ev.target.style.background = "yellow"; break; case 2: // two simultaneous touches ev.target.style.background = "pink"; break; default: // more than two simultaneous touches ev.target.style.background = "lightblue"; } } event logging the functions are used to log event activity to the application window, to support debugging and learning about the event flow. function enablelog(ev) { logeven...
Using Touch Events - Web APIs
y touch the surface and optionally move across the touch surface. the interaction ends when the fingers are removed from the surface. during this interaction, an application receives touch events during the start, move, and end phases. the application may apply its own semantics to the touch inputs. interfaces touch events consist of three interfaces (touch, touchevent and touchlist) and the following event types: touchstart - fired when a touch point is placed on the touch surface. touchmove - fired when a touch point is moved along the touch surface. touchend - fired when a touch point is removed from the touch surface. touchcancel - fired when a touch point has been disrupted in an implementation-specific manner (for example, too many touch points are created). the touch interfac...
...uchevent interface represents an event sent when the state of contacts with a touch-sensitive surface changes. the state changes are starting contact with a touch surface, moving a touch point while maintaining contact with the surface, releasing a touch point and canceling a touch event. this interface's attributes include the state of several modifier keys (for example the shift key) and the following touch lists: touches - a list of all of the touch points currently on the screen. targettouches - a list of the touch points on the target dom element. changedtouches - a list of the touch points whose items depends on the associated event type: for the touchstart event, it is a list of the touch points that became active with the current event. for the touchmove event, it is a l...
...ch points that became active with the current event. for the touchmove event, it is a list of the touch points that have changed since the last event. for the touchend event, it is a list of the touch points that have been removed from the surface (that is, the set of touch points corresponding to fingers no longer touching the surface). together, these interfaces define a relatively low-level set of features, yet they support many kinds of touch-based interaction, including the familiar multi-touch gestures such as multi-finger swipe, rotation, pinch and zoom. from interfaces to gestures an application may consider different factors when defining the semantics of a gesture. for instance, the distance a touch point traveled from its starting location to its location when the to...
...r represents input from any input device. additionally, the pointer event types are very similar to mouse event types (for example, pointerdown pointerup) thus code to handle pointer events closely matches mouse handling code. the implementation status of pointer events in browsers is relatively high with chrome, firefox, ie11 and edge having complete implementations. examples and demos the following documents describe how to use touch events and include example code: touch events overview implement custom gestures introduction to touch events in javascript add touch screen support to your website (the easy way) touch event demonstrations: paint program (by rick byers) touch/pointer tests and demos (by patrick h. lauke) community touch events community group mail list w3...
URL - Web APIs
Web › API › URL
you normally create a new url object by specifying the url as a string when calling its constructor, or by providing a relative url and a base url. you can then easily read the parsed components of the url or make changes to the url. if a browser doesn't yet support the url() constructor, you can access a url object using the window interface's window.url property. be sure to check to see if any of your target browsers require this to be prefixed. note: this feature is available in web workers. ...
... the window interface's window.url property. be sure to check to see if any of your target browsers require this to be prefixed. note: this feature is available in web workers. constructor new url() creates and returns a url object referencing the url specified using an absolute url string, or a relative url string and a base url string. properties hash a usvstring containing a '#' followed by the fragment identifier of the url. host a usvstring containing the domain (that is the hostname) followed by (if a port was specified) a ':' and the port of the url. hostname a usvstring containing the domain of the url. href a stringifier that returns a usvstring containing the whole url. origin read only returns a usvstring containing the origin of the url, that is its scheme, it...
...e port of the url. hostname a usvstring containing the domain of the url. href a stringifier that returns a usvstring containing the whole url. origin read only returns a usvstring containing the origin of the url, that is its scheme, its domain and its port. password a usvstring containing the password specified before the domain name. pathname a usvstring containing an initial '/' followed by the path of the url. port a usvstring containing the port number of the url. protocol a usvstring containing the protocol scheme of the url, including the final ':'. search a usvstring indicating the url's parameter string; if any parameters are provided, this string includes all of them, beginning with the leading ? character. searchparams read only a urlsearchparams object which c...
...he domain name. methods tostring() returns a usvstring containing the whole url. it is a synonym for url.href, though it can't be used to modify the value. tojson() returns a usvstring containing the whole url. it returns the same string as the href property. static methods createobjecturl() returns a domstring containing a unique blob url, that is a url with blob: as its scheme, followed by an opaque string uniquely identifying the object in the browser. revokeobjecturl() revokes an object url previously created using url.createobjecturl(). usage notes the constructor takes a url parameter, and an optional base parameter to use as a base if the url parameter is a relative url: const url = new url('../cats', 'http://www.example.com/dogs'); console.log(url.hostname); // "ww...
URLSearchParams - Web APIs
the urlsearchparams interface defines utility methods to work with the query string of a url. an object implementing urlsearchparams can directly be used in a for...of structure, for example the following two lines are equivalent: for (const [key, value] of mysearchparams) {} for (const [key, value] of mysearchparams.entries()) {} note: this feature is available in web workers. constructor urlsearchparams() returns a urlsearchparams object instance. methods urlsearchparams.append() appends a specified key/value pair as a new search parameter. ...
...this feature is available in web workers. constructor urlsearchparams() returns a urlsearchparams object instance. methods urlsearchparams.append() appends a specified key/value pair as a new search parameter. urlsearchparams.delete() deletes the given search parameter, and its associated value, from the list of all search parameters. urlsearchparams.entries() returns an iterator allowing iteration through all key/value pairs contained in this object. urlsearchparams.foreach() allows iteration through all values contained in this object via a callback function. urlsearchparams.get() returns the first value associated with the given search parameter. urlsearchparams.getall() returns all the values associated with a given search parameter. urlsearchparams.has() returns a ...
...ws iteration through all values contained in this object via a callback function. urlsearchparams.get() returns the first value associated with the given search parameter. urlsearchparams.getall() returns all the values associated with a given search parameter. urlsearchparams.has() returns a boolean indicating if such a given parameter exists. urlsearchparams.keys() returns an iterator allowing iteration through all keys of the key/value pairs contained in this object. urlsearchparams.set() sets the value associated with a given search parameter to the given value. if there are several values, the others are deleted. urlsearchparams.sort() sorts all key/value pairs, if any, by their keys. urlsearchparams.tostring() returns a string containing a query string suitable for use in ...
...ntained in this object. urlsearchparams.set() sets the value associated with a given search parameter to the given value. if there are several values, the others are deleted. urlsearchparams.sort() sorts all key/value pairs, if any, by their keys. urlsearchparams.tostring() returns a string containing a query string suitable for use in a url. urlsearchparams.values() returns an iterator allowing iteration through all values of the key/value pairs contained in this object. examples var paramsstring = "q=urlutils.searchparams&topic=api"; var searchparams = new urlsearchparams(paramsstring); //iterate the search parameters. for (let p of searchparams) { console.log(p); } searchparams.has("topic") === true; // true searchparams.get("topic") === "api"; // true searchparams.getall("t...
URLUtilsReadOnly.origin - Web APIs
for url using file: scheme, the value is browser dependant. this version of origin is implemented by workerlocation for use on workers. ...
...for url using file: scheme, the value is browser dependant. this version of origin is implemented by workerlocation for use on workers. ...
...for url using file: scheme, the value is browser dependant. this version of origin is implemented by workerlocation for use on workers. ...
...for url using file: scheme, the value is browser dependant. this version of origin is implemented by workerlocation for use on workers. ...
WaveShaperNode.curve - Web APIs
the curve property of the waveshapernode interface is a float32array of numbers describing the distortion to apply. the mid-element of the array is applied to any signal value of 0, the first one to signal values of -1, and the last to signal values of 1; values lower than -1 or greater than 1 are treated like -1 or 1 respectively. if necessary, intermediate values of the distortion curve are linearly interpolated. note: the array can be a null value: in that case, no distortion is applied to the input signal. ...
...ively. if necessary, intermediate values of the distortion curve are linearly interpolated. note: the array can be a null value: in that case, no distortion is applied to the input signal. syntax var audioctx = new audiocontext(); var distortion = audioctx.createwaveshaper(); distortion.curve = mycurvedataarray; // mycurvedataarray is a float32array value a float32array. ...
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ... ...
...hows basic usage of an audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; cur...
WaveShaperNode.oversample - Web APIs
oversample property of the waveshapernode interface is an enumerated value indicating if oversampling must be used. oversampling is a technique for creating more samples (up-sampling) before applying a distortion effect to the audio signal. once applied, the number of samples is reduced to its initial numbers. this leads to better results by avoiding some aliasing, but comes at the expense of a lower precision shaping curve. the possible oversample values are: value effect 'none' do not perform any oversampling. '2x' double the amount of samples before applying the shaping curve. '4x' multiply by 4 the amount of samples before applying the shaping curve. syntax distortion.oversample = enumeratedvalue; values distortion is a ...
...effect 'none' do not perform any oversampling. '2x' double the amount of samples before applying the shaping curve. '4x' multiply by 4 the amount of samples before applying the shaping curve. syntax distortion.oversample = enumeratedvalue; values distortion is a waveshapernode. enumeratedvalue is one of 'none', '2x', or '4x'. ...
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ... ...
...hows basic usage of an audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; cur...
WebGLRenderingContext.texSubImage2D() - Web APIs
ure. gl.texture_cube_map_negative_y: negative y face for a cube-mapped texture. gl.texture_cube_map_positive_z: positive z face for a cube-mapped texture. gl.texture_cube_map_negative_z: negative z face for a cube-mapped texture. level a glint specifying the level of detail. level 0 is the base image level and level n is the nth mipmap reduction level. xoffset a glint specifying the lower left texel x coordinate of a width-wide by height-wide rectangular subregion of the texture array. yoffset a glint specifying the lower left texel y coordinate of a width-wide by height-wide rectangular subregion of the texture array.. width a glsizei specifying the width of the texture in texels. height a glsizei specifying the height of the texture in texels. format a glenum specifyin...
...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_integer type a glenum specifying the data type of the texel data. possible values: gl.unsigned_byte: 8 bits per channel for gl.rgba gl.unsigned_short_5_6_5: 5 red bits, 6 green bits, 5 blue bits. gl.unsigned_short_4_4_4_4: 4 red bits, 4 green bits...
...6_5: 5 red bits, 6 green bits, 5 blue bits. gl.unsigned_short_4_4_4_4: 4 red bits, 4 green bits, 4 blue bits, 4 alpha bits. gl.unsigned_short_5_5_5_1: 5 red bits, 5 green bits, 5 blue bits, 1 alpha bit. ...
... a uint16array must be used if type is either gl.unsigned_short_5_6_5, gl.unsigned_short_4_4_4_4, gl.unsigned_short_5_5_5_1, or ext.half_float_oes. a float32array must be used if type is gl.float. ...
Color masking - Web APIs
colors by applying color masking to limit the range of displayed colors to specific shades. masking random colors this example modifies the random color animation by applying color masking with colormask(). you can think of the color masking operation as if looking at the colored canvas through some tinted glass or color filter. so, by masking off the blue and green channels, you are only allowing the red component of pixels to be updated, and therefore it is as if you were looking through a red tinted glass. color masking allows us to demonstrate some basics of color theory. by masking off some channel(s), we are in fact biasing the displayed colors towards the complementary color. so, clearly masking both blue and red, would give us shades of green. masking only the blue channel woul...
...similarly, masking only green would give us shades of magenta (also purples, crimsons, and so on), and masking only red would give shades of cyan (also sea greens, blues, and so on). ...
...similarly, masking only green would give us shades of magenta (also purples, crimsons, and so on), and masking only red would give shades of cyan (also sea greens, blues, and so on). note that the calls to colormask() only occur when the user clicks on one of the toggle buttons. ...
... red would give shades of cyan (also sea greens, blues, and so on). note that the calls to colormask() only occur when the user clicks on one of the toggle buttons. but rendering is done every second, using the timer. the color mask state of webgl is preserved, so we do not need to call colormask() every frame to set up the color mask. this is an important aspect of the webgl state machine. it allows us to setup webgl in a single initialization phase, and then just execute drawing commands for each frame. color masking gives you fine control of updating pixel values on the screen. by limiting the color channels that are written by each drawing command, you can use each channel, for example, to store a different grayscale image. alternatively, you may use the rgb components for color, but th...
Using shaders to apply color in WebGL - Web APIs
of white to each pixel, the entire square was rendered as solid white. let's say we want to render a gradient in which each corner of the square is a different color: red, blue, green, and white. the first thing to do is to establish these colors for the four vertices. to do this, we first need to create an array of vertex colors, then store it into a webgl buffer. we'll do that by adding the following code to our initbuffers() function: function initbuffers(){ ... const colors = [ 1.0, 1.0, 1.0, 1.0, // white 1.0, 0.0, 0.0, 1.0, // red 0.0, 1.0, 0.0, 1.0, // green 0.0, 0.0, 1.0, 1.0, // blue ]; const colorbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, colorbuffer); gl.bufferdata(gl.array_buffer, new float32array(colors), gl.s...
... buffer is allocated to store these colors, and the array is converted into floats and stored into the buffer. to use these colors, the vertex shader needs to be updated to pull the appropriate color from the color buffer: const vssource = ` attribute vec4 avertexposition; attribute vec4 avertexcolor; uniform mat4 umodelviewmatrix; uniform mat4 uprojectionmatrix; varying lowp vec4 vcolor; void main(void) { gl_position = uprojectionmatrix * umodelviewmatrix * avertexposition; vcolor = avertexcolor; } `; the key difference here is that for each vertex, we pass its color using a varying to the fragment shader. coloring the fragments as a refresher, here's what our fragment shader looked like previously: const fssource = ` void main() { ...
...or using a varying to the fragment shader. coloring the fragments as a refresher, here's what our fragment shader looked like previously: const fssource = ` void main() { gl_fragcolor = vec4(1.0, 1.0, 1.0, 1.0); } `; in order to pick up the interpolated color for each pixel, we need to change this to fetch the value from the vcolor varying: const fssource = ` 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 = { progra...
...t'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 // into the vertexcolor attribute. { const numcomponents = 4; const type = gl.float; const normalize = false; const stride = 0; const offset = 0; gl.bindbuffer(gl.array_buffer, buffers.color); gl.vertexattribpointer( pro...
WebRTC connectivity - Web APIs
ebrtc can’t create connections without some sort of server in the middle. we call this the signal channel or signaling service. it’s any sort of channel of communication to exchange information before setting up a connection, whether by email, post card or a carrier pigeon... it’s up to you. the information we need to exchange is the offer and answer which just contains the sdp mentioned below. peer a who will be the initiator of the connection, will create an offer. they will then send this offer to peer b using the chosen signal channel. peer b will receive the offer from the signal channel and create an answer. they will then send this back to peer a along the signal channel. session descriptions the configuration of an endpoint on a webrtc connection is called a session descript...
... as its local description. the recipient now knows the configuration of both ends of the connection. the recipient uses the signaling server to send the answer to the caller. the caller receives the answer. the caller calls rtcpeerconnection.setremotedescription() to set the answer as the remote description for its end of the call. it now knows the configuration of both peers. media begins to flow as configured. pending and current descriptions taking one step deeper into the process, we find that localdescription and remotedescription, the properties which return these two descriptions, aren't as simple as they look. because during renegotiation, an offer might be rejected because it proposes an incompatible format, it's necessary that each endpoint have the ability to propose a new fo...
...and rtcpeerconnection.currentremotedescription properties) represents the description currently in actual use by the connection. this is the most recent connection that both sides have fully agreed to use. the pending description (returned by rtcpeerconnection.pendinglocaldescription and rtcpeerconnection.pendingremotedescription) indicates a description which is currently under consideration following a call to setlocaldescription() or setremotedescription(), respectively. when reading the description (returned by rtcpeerconnection.localdescription and rtcpeerconnection.remotedescription), the returned value is the value of pendinglocaldescription/pendingremotedescription if there's a pending description (that is, the pending description isn't null); otherwise, the current description (cu...
... as an ice candidate and details the available methods the peer is able to communicate (directly or through a turn server). typically, each peer will propose its best candidates first, 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...
Introduction to WebRTC protocols - Web APIs
this article introduces the protocols on top of which the webrtc api is built. ice interactive connectivity establishment (ice) is a framework to allow your web browser to connect with peers. there are many reasons why a straight up connection from peer a to peer b simply won’t work. it needs to bypass firewalls that would prevent opening connections, give 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 ...
... the content and not the media content itself. technically, then, sdp is not truly a protocol, but a data format used to describe connection that shares media between devices. documenting sdp is well outside the scope of this documentation; however, there are a few things worth noting here. ...
...tent itself. technically, then, sdp is not truly a protocol, but a data format used to describe connection that shares media between devices. documenting sdp is well outside the scope of this documentation; however, there are a few things worth noting here. ...
...pe, followed by an equals sign ("="), followed by structured text comprising a value or description, whose format depends on the type. the lines of text that begin with a given letter are generally referred to as "letter-lines". ...
Using DTMF with WebRTC - Web APIs
let dialbutton = null; let logelement = null; these are, in order: dialstring the dtmf string the caller will send when the "dial" button is clicked. callerpc and receiverpc the rtcpeerconnection objects representing the caller and the receiver, respectively. these will be initialized when the call starts up, in our connectanddial() function, as shown in starting 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 ...
... an rtcofferoptions object providing options to specify when calling rtcpeerconnection.createoffer(). in this case, we state that we want to receive audio but not video. dialbutton and logelement these variables will be used to store references to the dial button and the <div> into which logging information will be written. they'll get set up when the page is first loaded. see initialization below. initialization when the page loads, we do some basic setup: we fetch references to the dial button and the log output box elements, and we use addeventlistener() to add an event listener to the dial button so that clicking it calls the connectanddial() function to begin the connection process. window.addeventlistener("load", function() { logelement = document.queryselector(".log"); dialb...
...ed event is delivered to the caller, letting it know that it's time to start negotiating the connection with the receiver. as previously mentioned, our example is simplified somewhat because we control both the caller and the receiver, so handlecallernegotiationneeded() is able to quickly construct the connection by chaining the required calls together for both the caller and receiver, as shown below. function handlecallernegotiationneeded() { log("negotiating..."); callerpc.createoffer(offeroptions) .then(function(offer) { log("setting caller's local description: " + offer.sdp); return callerpc.setlocaldescription(offer); }) .then(function() { log("setting receiver's remote description to the same as caller's local"); return receiverpc.setremotedescription(callerpc...
... begins to receive media, an event is delivered to the receiver's rtcpeerconnection, receiverpc. as explained in starting the connection process, the current webrtc specification uses the track event for this, but some browsers haven't been updated to support this yet, so we also need to handle the addstream event. the handlereceivertrackevent() and handlereceiveraddstreamevent() methods, shown below, handle these. function handlereceivertrackevent(event) { audio.srcobject = event.streams[0]; } function handlereceiveraddstreamevent(event) { audio.srcobject = event.stream; } the track event includes a streams property containing an array of the streams the track is a member of (one track can be part of many streams). we take the first stream and attach it to the <audio> element. the a...
WebRTC API - Web APIs
eived. dictionaries rtcconfiguration used to provide configuration options for an rtcpeerconnection. rtciceserver defines how to connect to a single ice server (such as a stun or turn server). rtcrtpcontributingsource contains information about a given contributing source (csrc) including the most recent time a packet that the source contributed was played out. events bufferedamountlow the amount of data currently buffered by the data channel—as indicated by its bufferedamount property—has decreased to be at or below the channel's minimum buffered data size, as specified by bufferedamountlowthreshold. close the data channel has completed the closing process and is now in the closed state. its underlying data transport is completely closed at this point. you can be notifi...
...ompletes by watching for the closing event instead. closing the rtcdatachannel has transitioned to the closing state, indicating that it will be closed soon. you can detect the completion of the closing process by watching for the close event. connectionstatechange the connection's state, which can be accessed in connectionstate, has changed. datachannel a new rtcdatachannel is available following the remote peer opening a new data channel. this event's type is rtcdatachannelevent. error an rtcerrorevent indicating that an error occurred on the data channel. error an rtcerrorevent indicating that an error occurred on the rtcdtlstransport. this error will be either dtls-failure or fingerprint-failure. gatheringstatechange the rtcicetransport's gathering state has changed. icecandi...
...in the iceconnectionstate property—changes. icegatheringstatechange sent to an rtcpeerconnection when its ice gathering state—found in the icegatheringstate property—changes. message a message has been received on the data channel. the event is of type messageevent. negotiationneeded informs the rtcpeerconnection that it needs to perform session negotiation by calling createoffer() followed by setlocaldescription(). open the underlying data transport for the rtcdatachannel has been successfully opened or re-opened. selectedcandidatepairchange the currently-selected pair of ice candidates has changed for the rtcicetransport on which the event is fired. track the track event, of type rtctrackevent is sent to an rtcpeerconnection when a new track is added to the connection foll...
... audio, or video—or any combination thereof—into a browser application. in this article, we'll look at the lifetime of a webrtc session, from establishing the connection all the way through closing the connection when it's no longer needed. establishing a connection: the perfect negotiation pattern perfect negotiation is a design pattern which is recommended for your signaling process to follow, which provides transparency in negotiation while allowing both sides to be either the offerer or the answerer, without significant coding needed to differentiate the two. signaling and two-way video calling a tutorial and example which turns a websocket-based chat system created for a previous example and adds support for opening video calls among participants. the chat server's websocket conn...
Using bounded reference spaces - Web APIs
it is always good practice to handle this yourself, watching for collisions between the user's position and the boundary of the world, and providing guidance to move back toward the origin point, or at least to stay inside the safe zone. xr hardware that does not have an inherent boundary defined may or may not support the bounded reference space. if it does, it likely has a system in place to allow the user to specify or select the boundaries to apply if a bounded space is to be used. however, it's entirely possible that the device will simply decline to support bounded spaces at all, so you should be prepared to fall back to some other type of reference space. understanding boundaries as mentioned previously, the boundary is defined as an array of points located at floor level, each defi...
...that the device will simply decline to support bounded spaces at all, so you should be prepared to fall back to some other type of reference space. understanding boundaries as mentioned previously, the boundary is defined as an array of points located at floor level, each defining a corner of the boundary area, going around the origin in a clockwise manner. this is demonstrated in the diagram below. this diagram defines the boundaries of room with the origin in the center, as required, and a set of 12 points representing the vertices of the available physical space. there are two cut-out areas in the room, possibly representing a couch, sofa, or bench behind the user and a stand or table on which the computer or other hardware is located. as this suggests, the safe area is not required t...
...d 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-preferred space before actually attempting to create a bounded reference space, you need to create a session that supports them. since not all hardware supports bound...
...ed to create a session that supports them. since not all hardware supports bounded reference spaces, you should made sure to support bounded reference spaces as an option rather than as a required feature unless you have special knowledge of the environment in which your code will run. ...
Lighting a WebXR setting - Web APIs
reflectance of the surface at the pixel's location. the color and intensity of every pixel in the scene is affected exactly the same way, regardless of where it is in the scene or the direction it's facing. ambient light is commonly present simply to prevent shadowed areas from becoming too dark, although it affects the entire scene; however, the amount of ambient light in a scene should be very low. because the bouncing and scattering of light can be expensive to compute in real time, especially if multiple light sources are involved, it's common to use ambient lighting to simulate the scattered light caused by all the other light sources in the scene, instead of actually calculating the true effect of light scattering. care needs to be taken to try to match the ambient light to what would...
...ht caused by all the other light sources in the scene, instead of actually calculating the true effect of light scattering. care needs to be taken to try to match the ambient light to what would really be the effect of the scene's lighting when doing this, however. ambient light can also be used to apply a color tint to a scene; for example, in a game in which the player has a special pair of yellow-tinted glasses, you can add a yellow ambient light. saturn's fifth-largest moon, tethys, bathed in sunlight, coming from the lower left. diffuse light diffuse light is light which is evenly and directionally emitted from or reflected off a surface. this is the majority of the light we usually see. diffuse light comes from a particular position or direction and casts shadows. due to its...
...st by directional lights are very sharp, with an essentially instant transition between lighted and shadowed. the most common example of a directional light is the sun. while the sun is in actuality a single (large) object, it's very far away, so the rays of light coming from it are essentially parallel. while sunlight does actually fall off in intensity with distance, the rate of change is very low and is only noticed over vast distances, so the rate of intensity change of sunlight doesn't typically matter for rendering a 3d scene. point light sources a point light source is a light source located at a specific location, radiating outward equally in every direction. light bulbs, candles, and the like are examples of point light sources. the closer an object is to a point light source, the...
...ly all scenes will have at least one light source and may have a great many of them. each light source substantially increases the amount of calculation needed to determine the final color and brightness of each displayed pixel. performing the shading for each of these light source types is more computationally demanding than the one before it; so ambient light is the least expensive to apply, followed by directional light sources, point lights, and finally spotlights. additionally, the more accurate the lighting is designed to be, the more computationally expensive it becomes. increased shadow detail, volumetric light (that is, lighting that you can see in the air, such as sunbeams or the beams of spotlights in the sky), and other lighting effects can add realism and beauty to your scene, b...
WebXR permissions and security - Web APIs
there are things to be aware of when setting up an ar session, as well. immersive presentation of vr first, any requests to activate the immersive-vr mode are rejected if the domain issuing the request does not have permission to enable an immersive session. this permission comes from the xr-spatial-tracking feature policy. ...
...aware of when setting up an ar session, as well. immersive presentation of vr first, any requests to activate the immersive-vr mode are rejected if the domain issuing the request does not have permission to enable an immersive session. this permission comes from the xr-spatial-tracking feature policy. once that check is passed, the request to enter immersive-vr mode is allowed if all of the following are true: the requestsession() call was issued by code executing within the handler for a user event, or the from the startup code for a user-launched web application. the document is considered trustworthy, in that it is responsible and is both currently active and has focus. the user's intent to enter immersive vr mode is well understood; see user intent below for details. if all of t...
...omise returned by requestsession() is resolved, and the new xrsession object is passed into the fulfillment handler. otherwise, an appropriate exception is thrown, such as securityerror 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 doc...
...r or not an action being performed by code is being performed because of something the user intends to do or not. there are two kinds of user intent: implicit and explicit. explicit user intent (explicit user consent) is granted when the user has specifically and expressly been asked for permission to perform an action. implicit user intent (implicit user consent) is assumed if either of the following scenarios is the case: the user has interacted with the document in some way which has in turn caused your request to occur. for example, if you have an "enter xr mode" button, and the user clicks it, calling requestsession() from the button's click event handler will permitted. if your code is executing during the launch of a web application, the runtime may consider the act of launching ...
Keyframe Formats - Web APIs
syntax there are two different ways to format keyframes: an array of objects (keyframes) consisting of properties and values to iterate over. this is the canonical format returned by the getkeyframes() method. ...
...} ], 2000); note: offset values, if provided, must be between 0.0 and 1.0 (inclusive) and arranged in ascending order. it is not necessary to specify an offset for every keyframe. keyframes without a specified offset will be evenly spaced between adjacent keyframes. the easing to apply between keyframes can be specified by providing an easing value as illustrated below. element.animate([ { opacity: 1, easing: 'ease-out' }, { opacity: 0.1, easing: 'ease-in' }, { opacity: 0 } ], 2000); in this example, the specified easing only applies from the keyframe where it is specified until the next keyframe. any easing value specified on the options argument, however, applies across a single iteration of the anima...
...imate and an array of values to iterate over. element.animate({ opacity: [ 0, 1 ], // [ from, to ] color: [ "#fff", "#000" ] // [ from, to ] }, 2000); using this format, the number of elements in each array does not need to be equal. the provided values will be spaced out independently. element.animate({ opacity: [ 0, 1 ], // offset: 0, 1 backgroundcolor: [ "red", "yellow", "green" ], // offset: 0, 0.5, 1 }, 2000); the special keys offset, easing, and composite (described below) may be specified alongside the property values. element.animate({ opacity: [ 0, 0.9, 1 ], offset: [ 0, 0.8 ], // shorthand for [ 0, 0.8, 1 ] easing: [ 'ease-in', 'ease-out' ], }, 2000); after generating a suitable set of keyframes from the property value lists, each suppli...
...rthand values such as margin are also permitted. two exceptional css properties are: float, which must be written as cssfloat since "float" is a reserved word in javascript. it's just for reference here, this will have no effect on animation since "float" is not an animatable css property. offset, which must be written as cssoffset since "offset" represents the keyframe offset as 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 use...
Web Locks API - Web APIs
the web locks api allows scripts running in one tab or worker to asynchronously acquire a lock, hold it while work is performed, then release it. while held, no other script executing in the same origin can acquire the same lock, which allows a web app running in multiple tabs or workers to coordinate work and the use of resources. web locks concepts and usage a lock is an abstract concept representing some potentially shared resource, identified by a name chosen by the web app. ...
...e a lock is an abstract concept representing some potentially shared resource, identified by a name chosen by the web app. for example, if a web app running in multiple tabs wants to ensure that only one tab is syncing data between the network and indexed db, each tab could try to acquire a "my_net_db_sync" lock, but only one tab will succeed (the leader election pattern.) the api is used as follows: the lock is requested. work is done while holding the lock in an asynchronous task. the lock is automatically released when the task completes. navigator.locks.request('my_resource', async lock => { // the lock has been acquired. await do_something(); await do_something_else(); // now the lock will be released. }); while a lock is held, requests for the same lock from this exec...
...the lock is granted. the lock is automatically released when the callback returns, so usually the callback is an async function, which causes the lock to be released only when the async function has completely finished. the request() method itself returns a promise which resolves once the lock has been released; within an async function, a script can await the call to make the asynchronous code flow linear. for example: await do_something_without_lock(); // request the lock. await navigator.locks.request('my_resource', async lock => { // the lock has been acquired. await do_something_with_lock(); await do_something_else_with_lock(); // now the lock will be released. }); // the lock has been released. await do_something_else_without_lock(); options several options can be passed ...
...d. await do_something_else_without_lock(); options several options can be passed when requesting a lock: mode: the default mode is "exclusive", but "shared" can be specified. there can be only one "exclusive" holder of a lock, but multiple "shared" requests can be granted at the same time. this can be used to implement the readers-writer pattern. signal: an abortsignal can be passed in, allowing a lock request to be aborted. this can be used to implement a timeout on requests. ifavailable: if specified, the lock request will fail if the lock cannot be granted immediately without waiting. the callback is invoked with null. monitoring the navigator.locks.query() method can be used by scripts to introspect the state of the lock manager for the origin. this can be useful when debuggin...
Web Workers API - Web APIs
web workers concepts and usage a worker is an object created using a constructor (e.g. ...
... web workers concepts and usage a worker is an object created using a constructor (e.g. ...
...r more details. serviceworkers essentially act as proxy servers that sit between web applications, the browser, and the network (when available). they are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. they will also allow access to push notifications and background sync apis. chrome workers are a firefox-only type of worker that you can use if you are developing add-ons and want to use workers in extensions and have access to js-ctypes in your worker. see chromeworker for more details. audio workers provide the ability for direct scripted audio processing to be done inside a web worker context. note: as per ...
...ity for direct scripted audio processing to be done inside a web worker context. note: as per the web workers spec, worker error events should not bubble (see bug 1188141. this has been implemented in firefox 42. web worker interfaces abstractworker abstracts properties and methods common to all kind of workers (i.e. worker or sharedworker). worker represents a running worker thread, allowing you to pass messages to the running worker code. workerlocation defines the absolute location of the script executed by the worker. sharedworker represents a specific kind of worker that can be accessed from several browsing contexts, being several windows, iframes or even workers. workerglobalscope represents the generic scope of any worker (doing the same job as window does for normal ...
Window.print() - Web APIs
Web › API › Window › print
meedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internetprintchrome full support 1notes full support 1notes notes starting with chrome 46, this method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.edge full support 12firefox full support 1ie full support 5opera full support 6notes full support 6notes notes starting with opera 33, this method is blocked inside a...
... 12firefox full support 1ie full support 5opera full support 6notes full support 6notes notes starting with opera 33, this method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.safari full support 1.1webview android full support 1notes full support 1notes notes starting with webview 46, this method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.chrome android full support ...
...tes notes starting with webview 46, this method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.chrome android full support 18notes full support 18notes notes starting with chrome 46, this method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.firefox android no support nonotes no support nonotes notes see bug 1247609.opera android full support 10.1notes full support 10.1notes notes starting with opera 33, this method is blocked inside an <iframe> un...
...support nonotes no support nonotes notes see bug 1247609.opera android full support 10.1notes full support 10.1notes notes starting with opera 33, this method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.safari ios full support 1samsung internet android full support 1.0notes full support 1.0notes notes starting with samsung internet 5.0, this method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.legend ...
Synchronous and asynchronous requests - Web APIs
ction xhrsuccess. line 15 specifies true for its third parameter to indicate that the request should be handled asynchronously. line 16 actually initiates the request. example: using a timeout you can use a timeout to prevent your code from hanging while waiting for a read to finish. ...
... gecko 30.0 (firefox 30.0 / thunderbird 30.0 / seamonkey 2.27), blink 39.0, and edge 13, synchronous requests on the main thread have been deprecated due to their negative impact on the user experience. synchronous xhr requests often cause hangs on the web. but developers typically don't notice the problem because the hang only manifests with poor network conditions or when the remote server is slow to respond. synchronous xhr is now in deprecation state. the recommendation is that developers move away from the synchronous api and instead use asynchronous requests. all new xhr features such as timeout or abort are not allowed for synchronous xhr. doing so will raise an invalidaccesserror. example: http synchronous request this example demonstrates how to make a simple synchronous request.
... api there are some cases in which the synchronous usage of xmlhttprequest is not replaceable, like during the unload, beforeunload, and pagehide events. you should consider using the fetch() api with the keepalive flag. when fetch with keepalive isn't available, you can consider using the navigator.sendbeacon() api, which can support these use cases while typically delivering a good ux. the following example shows theoretical analytics code that attempts to submit data to a server by using a synchronous xmlhttprequest in an unload handler. this results in the unloading of the page to be delayed. window.addeventlistener('unload', logdata, false); function logdata() { var client = new xmlhttprequest(); client.open("post", "/log", false); // third parameter indicates sync xhr. :( ...
...log", false); // third parameter indicates sync xhr. :( client.setrequestheader("content-type", "text/plain;charset=utf-8"); client.send(analyticsdata); } using the sendbeacon() method, the data will be transmitted asynchronously to the web server when the user agent has had an opportunity to do so, without delaying the unload or affecting the performance of the next navigation. the following example shows a theoretical analytics code pattern that submits data to a server by using the sendbeacon() method. window.addeventlistener('unload', logdata, false); function logdata() { navigator.sendbeacon("/log", analyticsdata); } ...
XRSession.requestAnimationFrame() - Web APIs
this can be done from within the callback itself. ...
...bal requestanimationframe() function provided by the window interface, you must not treat these as interchangeable. there is no guarantee that the latter will work at all while an immersive xr session is underway. syntax requestid = xrsession.requestanimationframe(animationframecallback); parameters animationframecallback a function which is called before the next repaint in order to allow you to update and render the xr scene based on elapsed time, animation, user input changes, and so forth. the callback receives as input two parameters: time a domhighrestimestamp indicating the time offset at which the updated viewer state was received from the webxr device. xrframe an xrframe object describing the state of the objects being tracked by the session. this can be used to...
...state of the objects being tracked by the session. this can be used to obtain the poses of the viewer and the scene itself, as well as other information needed to render a frame of an ar or vr scene. return value an integer value which serves as a unique, non-zero id or handle you may pass to cancelanimationframe() if you need to remove the pending animation frame request. example the following example requests xrsession with "inline" mode so that it can be displayed in an html element (without the need for a separate ar or vr device). note: a real application should check that the device and the user agent support webxr api at all and then that they both support the desired session type via xr.issessionsupported(). // obtain xr object const xr = navigator.xr // request a new xr...
...ime, xrframe) => { let viewer = xrframe.getviewerpose(xrreferencespace) gl.bindframebuffer(xrwebgllayer.framebuffer) for (xrview of viewer.views) { let xrviewport = xrwebgllayer.getviewport(xrview) gl.viewport(xrviewport.x, xrviewport.y, xrviewport.width, xrviewport.height) // webgl draw calls will now be rendered into the appropriate viewport. } }) }) the following example was taken directly from the spec draft. this example demonstrates a design pattern that ensures seamless transition between non-immersive animations created via window.requestanimationframe and immersive xr animations. let xrsession = null function onwindowanimationframe(time) { window.requestanimationframe(onwindowanimationframe) // this may be called while an immersive session...
ARIA Screen Reader Implementors Guide - Accessibility
live regions this is just a guide. live region markup is a complex area which is somewhat open to interpretation. the following is intended to provide implementation guidance that respects screen readers developers' need to try different things. the intention is to strike a balance between providing useful guidance on how to use the markup's intended meaning while supporting live regions as an area for screen readers to innovate and compete. interpreting wai-aria live region markup live changes are hints: in general live region markup is provided by the author as hints, and the assistive technology may allow for global, site or even region-specific settings, as well as heuristics to help with live changes on pages that have no wai-aria hints. optionally, create a second, additional...
...the channels could be user configured for presenting live regions based on role or politeness. busy regions: any changes in a region marked with aria-busy="true" should not be added to the queue until that attribute is cleared. ...
... order to avoid presenting the region twice for two changes that occur quickly one after the other. include labels when presenting changes: if the change occurs in something with a semantic label of some kind, speak the label. this is particularly important for changes in data cells, where the column and row headers provide important contextual information. ...
...the most complete implementation of live regions currently is in firefox 3. ...
Using the group role - Accessibility
d by the context in which it is provided. if an author believes a section is significant enough to warrant inclusion in the page's table of contents, they should assign the section a role of region or a standard landmark role. possible effects on user agents and assistive technology when the group role is added to an element, or such an element becomes visible, the user agent should do the following: expose the element as having a group role in the operating system's accessibility api. fire an accessible group event using the operating system's accessibility api if it supports it. assistive technology products should listen for such an event and notify the user accordingly: screen readers should announce the group when focus first lands on a control inside it, and if aria-descri...
...he operating system's accessibility api. fire an accessible group event using the operating system's accessibility api if it supports it. assistive technology products should listen for such an event and notify the user accordingly: screen readers should announce the group when focus first lands on a control inside it, and if aria-describedby has been set, the description may be spoken. ...
...scribedby has been set, the description may be spoken. following this the focused control may be announced. screen magnifiers may enlarge the group. note: opinons 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: using the group role with a html tree view the snippet below shows how the group role is added directly into the html source code. <div id="tree1" role="tree" tabindex="-1"> <div id="animals" class="groupheader" role="presentation" aria-owns="animalgroup" aria-expanded="true"> <img role="presentation" tabindex="-1" src="images/treeexpanded.gif" /> <span role="treeitem" tabindex="0">animals</span> </div> <div id="animalgroup" role="group"> ...
... <div role="menu"> <ul role="group"> <li role="menuitem">inbox</li> <li role="menuitem">archive</li> <li role="menuitem">trash</li> </ul> <ul role="group"> <li role="menuitem">custom folder 1</li> <li role="menuitem">custom folder 2</li> <li role="menuitem">custom folder 3</li> </ul> <ul role=...
ARIA: Comment role - Accessibility
the comment landmark role semantically denotes a comment/reaction to some content on the page, or to a previous comment. examples in the following example we have a document section that has been commented. the commented section is marked up using <span role="mark">. the related comment is marked up using an html structure wrapped with a <div> containing role="comment". ...
...landmark role semantically denotes a comment/reaction to some content on the page, or to a previous comment. examples in the following example we have a document section that has been commented. the commented section is marked up using <span role="mark">. the related comment is marked up using an html structure wrapped with a <div> containing role="comment". ...
...9, 19:29</time></p> </div> to associate the comment with the text being commented, we need to wrap the commented text with an element containing the aria-details attribute, the value of which should be the id of the comment. ...
...comment" id="thread-1" data-author="chris"> <h3>chris said</h3> <p class="comment-text">i really think this moment could use more cowbell.</p> <p><time datetime="2019-03-30t19:29">march 30 2019, 19:29</time></p> </div> <div role="comment" id="thread-2" data-author="chris"> <h3>marcus said</h3> <p class="comment-text">the guitar solo could do with a touch more chorus, and a slightly lower volume.</p> <p><time datetime="2019-03-29t15:35">march 29 2019, 15:35</time></p> </div> nested comments nested comments are also possible with aria annotations — simply nest the comments inside one another, like so: <div role="comment" id="thread-1" data-author="chris"> <h3>chris said</h3> <p class="comment-text">i really think this moment could use more cowbell.</p> <p><time datet...
ARIA: feed role - Accessibility
users can read articles, jump forward and backward by article, and reliably trigger new articles to load while in reading mode. examples include an rss feed, news feeds, social media feeds like facebook, instagram or twitter, or even a list of related products on an ecommerce page. these streams can be limited or infinite, loading more content as the user scrolls. implementing the feed pattern allows a screen reader to reliably read and trigger the loading of feed content while in reading mode. a feed is a container element whose children are <article>s or have role article. each article within a feed should be focusable, with tabindex of 0 or -1. an article should be scrolled into view when it, or a descendant element, receives focus. if the addition of articles occupies the main browser t...
...make sure to set it back to false when processing ends, or the user may not see the updates. to ensure good user experience, avoid inserting or removing articles in the middle of a feed, load new articles before the user has reached the end of the feed, and provide keyboard commands for moving focus among articles so that keyboard users can navigate through your feed. see keyboard interactions below. if the number of articles is known, set aria-setsize on the articles themselves. however, if the total number is extremely large, indefinite, or changes often, set aria-setsize="-1" to indicate that the size of the feed is not known. another feature of the feed pattern is skim reading: articles within a feed can contain both an accessible name with the aria-label and a description with an aria...
...k after the label when navigating by article. by identifying the elements inside of an article that provide the title and the primary content, assistive technologies can provide functions that enable users to jump from article to article and efficiently discern which articles they want to read. the feed pattern enables reliable assistive technology reading mode interaction by establishing the following interoperability agreement between the web page and assistive technologies: in the context of a feed, the web page code is responsible for: appropriate visual scrolling of the content based on which article contains dom focus. loading or removing feed articles based on which article contains dom focus. in the context of a feed, assistive technologies with a reading mode are r...
...nsible for: indicating which article contains the reading cursor by ensuring the article element or one of its descendants has dom focus. providing reading mode keys that move dom focus to the next and previous articles. providing reading mode keys for moving the reading cursor and dom focus past the end and before the start of the feed. keyboard interaction supporting the following, or a similar, interface is recommended when focus is inside the feed: page down: move focus to next article. page up: move focus to previous article. control + end: move focus to the first focusable element after the feed. control + home: move focus to the first focusable element before the feed. if a feed is nested within a feed, such as a comments feed within a feed of blog posts, t...
ARIA: dialog role - Accessibility
esc">you can change your details at any time in the user account section.</p> <button>close</button> </div> description marking up a dialog element with the dialog role helps assistive technology identify the dialog's content as being grouped and separated from the rest of the page content. however, adding role="dialog" alone is not sufficient to make a dialog accessible. additionally, the following needs to be done: the dialog must be properly labeled keyboard focus must be managed correctly the sections below describe how these two requirements can be met. labeling even though it is not required for the dialog itself to be able to receive focus, it still needs to be labeled. the label given to the dialog will provide contextual information for the interactive controls inside th...
...ible title bar, the text inside that bar can be used to label the dialog itself. the best way to achieve this is by using the aria-labelledby attribute to the role="dialog" element. additionally, if the dialog contains additional descriptive text besides the dialog title, this text can be associated with the dialog using the aria-describedby attribute. ...
...e to interact with any page content outside the dialog. in other words, the main application ui or page content is considered to be temporarily disabled as long as the modal dialog is showing. for non-modal dialogs it is still possible to interact with content outside of the dialog while the dialog is showing. note that for non-modal dialogs there will have to be a global keyboard shortcut that allows focus to be moved between opened dialogs and the main page. for more information see the managing modal and non modal dialogs guide. associated aria roles, states, and properties aria-labelledby use this attribute to label the dialog. often, the value of the aria-labelledby attribute will be the id of the element used to title the dialog. aria-describedby use this attribute to describe t...
...ia roles, states, and properties aria-labelledby use this attribute to label the dialog. often, the value of the aria-labelledby attribute will be the id of the element used to title the dialog. aria-describedby use this attribute to describe the contents of the dialog. possible effects on user agents and assistive technology when the dialog role is used, the user agent should do the following: expose the element as a dialog in the operating system's accessibility api. when the dialog is correctly labeled and focus is moved to an element (often an interactive element, such as a button) inside the dialog, screen readers should announce the dialog's accessible role, name and optionally description, along with announcing the focused element. note: opinions may differ on how assi...
ARIA: listbox role - Accessibility
t non-contiguous items. it is recommended that a checkbox, link or other method be used to select all items, and ctrl+a could be used as a shortcut key for this. when the listbox role is added to an element, or such an element becomes visible, screen readers announce the label and role of the listbox when it gets focus. if an option or item is focused within the list, it gets announced next, followed by an indication of the item's position with the list if the screen reader supports this. as focus moves within the list, the screen reader announces the relevant items. associated aria roles, states, and properties associated roles option one or more nested options are required. all selected options have aria-selected set to true. all options that are not selected have aria-selected set ...
...hift + end (optional): selects the focused option and all options down to the last option. optionally, moves focus to the last option. control + a (optional): selects all options in the list. optionally, if all options are selected, it may also unselect all options. required javascript features selecting an option in a single select listbox when the user selects an option, the following must occur: deselect the previously selected option, setting the aria-selected to false, or removing the attribute altogether, changing the appearance of the newly unselected option to appear not selected. select the newly selected option, setting aria-selected="true" on the option and changing the appearance of the newly selected option to appear selected. update the aria-activedescendan...
...ce of the newly selected option to appear selected. update the aria-activedescendant value on the listbox to the id of the newly selected option visually handle the blur, focus, and selected states of the option toggling the state of an option in a multi select listbox when the user clicks on an option, hits space when focused on an option, or otherwise toggles the state of an option, the following must occur: toggle the aria-selected state of the currently focused option, changing the state of the aria-selected to true if it was false or false if it was true. change the appearance of the option to reflect it's selected state update the aria-activedescendant value on the listbox to the id of the option the user just interacted with, even if they toggled the option to be unselected. ...
... you can use a native feature with the semantics and behavior you require already built in, instead of re-purposing an element and adding an aria role, state or property to make it accessible, then do so. the <select> element with descendant <option> elements handles all the needed interactions natively. examples example 1: a single select listbox that uses aria-activedescendant the snippet below shows how the listbox role is added directly into the html source code. <p id="listbox1label" role="label">select a color:</p> <div role="listbox" tabindex="0" id="listbox1" aria-labelledby="listbox1label" onclick="return listitemclick(event);" onkeydown="return listitemkeyevent(event);" onkeypress="return listitemkeyevent(event);" aria-activedescendant="listbox1-1"> <div role="opti...
ARIA: textbox role - Accessibility
whenever possible, rather than using this role, use an <input> element with type="text", for single-line input, or a <textarea> element for multi-line input. description when an element has the textbox role, the browser sends an accessible textbox event to assistive technologies, which can then notify the user about it. the default is a single line input, in which return or enter submits the form; in this case, it is preferable to use an html <input> with type="text". to create a multi-line text box which supports line breaks, as in an html <textarea>, set aria-multiline="true". ...
...remain on the textbox while the value of aria-activedescendant on the textbox element refers to a descendant of a popup listbox that is controlled by the textbox.this attribute must be updated programmatically as the focus changes. aria-autocomplete attribute indicates whether and how the user's input into the field could trigger display of a prediction of the intended value. it supports the following values: inline: predicted text is inserted after the caret. list: predicted text is presented as a collection of values. both: predicted text is presented as a collection of values, with the text needed to complete one value inserted after the caret. none (default): predicted text is not offered. if list or both is set, the aria-controls and aria-haspopup attributes should also b...
...tter practice to use an <input> element with type="text", or a <textarea> element instead of the aria textbox role. when using either semantic element, the aria textbox role is not necessary. see notes on using aria in html. possible effects on user agents and assistive technology when the textbox role is added to an element, or such an element becomes visible, the user agent should do the following: expose the element as having a textbox role in the operating system's accessibility api. fire an accessible textbox event using the operating system's accessibility api if it supports it. assistive technology products should listen for such an event and notify the user accordingly: screen readers should announce its label and role when focus first lands on a textbox. if it also conta...
... a textbox. if it also contains content, this should be announced as with a regular textbox. screen magnifiers may enlarge the textbox. 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: adding the role in the html code for single line input the snippet below shows how the textbox role is added directly into the html source code. <div role="textbox" contenteditable="true"></div> example 2: adding the role in the html code for multi-line input the snippet below shows how the textbox role is added directly into the html source code. <div role="textbox" contenteditable="true" aria-multiline="true"></div> best practices be sure to add the contente...
Basic form hints - Accessibility
enting forms using traditional html form-related elements, it is important to provide labels for controls, and explicitly associate a label with its control. when a screen reader user navigates a page, the screen reader will describe form controls. without a direct association between the control and its label, the screen reader has no way of knowing which label is the correct one. the example below shows a simple form with labels. note that each <input> element has an id, and each <label> element has a for attribute, indicating the id of the associated <input>. <form> <ul> <li> <input id="wine-1" type="checkbox" value="riesling"/> <label for="wine-1">berg rottland riesling</label> </li> <li> <input id="wine-2" type="checkbox" value="pinot-blanc"/> <lab...
...label> </li> </ul> </form> labeling with aria the html <label> element is appropriate for form-related elements, but many form controls are implemented as a dynamic javascript widget, using <div>s or <span>s. wai-aria, the accessible rich internet applications specification from the w3c's web accessibility initiative, provides the aria-labelledby attribute for these cases. the example below shows a radio button group implemented using an unordered list. note that on line 3, the <ul> element sets the aria-labelledby attribute to rg1_label, the id of the <h3> element on line 1, which is the label for the radio group. <h3 id="rg1_label">lunch options</h3> <ul class="radiogroup" id="rg1" role="radiogroup" aria-labelledby="rg1_label"> <li id="r1" tabindex="-1" role="radio" aria-che...
....gif" /> subway </li> <li id="r3" tabindex="0" role="radio" aria-checked="true"> <img role="presentation" src="radio-checked.gif" /> radio maria </li> </ul> describing with aria form controls sometimes have a description associated with them, in addition to the label. aria provides the aria-describedby attribute to directly associate the description with the control. the example below shows a <button> element that is described by a sentence in a separate <div> element. the aria-describedby attribute on the <button> references the id of the <div>. <button aria-describedby="descriptionrevert">revert</button> <div id="descriptionrevert">reverting will undo any changes that have been made since the last save.</div> note: the aria-describedby attribut...
... aria provides attributes for indicating that form controls are required or invalid: the aria-required property can be applied to a form element, to indicate to an at that it is required to complete the form. the aria-invalid state can be programmatically applied, to indicate to an at which data fields have incorrect data, so that the user knows they have entered invalid data. the example below shows a simple form with three fields. on lines 4 and 12, the aria-required attributes are set to true (in addition to the asterisks next to the labels), indicating that the name and email fields are required. the second part of the example, a snippet of javascript validates the email format, and sets the aria-invalid attribute of the email field (line 12 of the html) according to the result (in ...
Alerts - Accessibility
“@” symbol, and if the name entry contains at least 1 character. if the above criteria is not met, the field’s aria-invalid attribute will be given a value of “true”. if the criteria was not met, the user will be notified via an alert. instead of using the javascript ‘alert’ function, we’ll use a simple wai-aria widget for notification. ...
...iven a value of “true”. if the criteria was not met, the user will be notified via an alert. instead of using the javascript ‘alert’ function, we’ll use a simple wai-aria widget for notification. this notifies the user of the error, but allows for them continue modifying the form without losing focus (caused by the “onblur” handler in javascript's default ‘alert’ function). ...
...when tabbing, you’ll hear an alert that tells you you’ve entered an invalid name. you can then shift-tab back and correct the error. enter an e-mail address without the “@” symbol. when tabbing out of this field, you should hear a warning that says you didn’t enter a valid e-mail address. in both cases, when returning focus to the field ...
...ave q. why did you put both “(required)” in the label text and the aria-required attribute on some of the inputs? a. if this were a real live form, and the site was being visited by a browser that does not yet support aria, we’d still want to give an indication that this is a required field. q. why don’t you set focus back to the invalid field automatically? a. because this is not allowed by the windows api specs, and possibly others. also, letting the focus jump around without real user interaction too often is not a nice thing to do in general. tbd: let's rethink this -- personally, i think setting focus might be good if done without causing a keyboard trap. ...
An overview of accessible web applications and widgets - Accessibility
ue"] { display: none; } the javascript to update the aria-hidden property has the form shown in example 2c. note that the script only updates the aria-hidden attribute (line 2); it does not need to also add or remove a custom classname. example 2c. javascript to update the aria-checked attribute var showtip = function(el) { el.setattribute('aria-hidden', 'false'); } role changes aria allows developers to declare a semantic role for an element that otherwise offers incorrect or no semantics. the role of an element should not change. instead, remove the original element and replace it with an element with the new role. for example, consider an "inline edit" widget: a component that allows users to edit a piece of text in place, without switching contexts. this component has a "view"...
... <input> element. asynchronous content changes under construction. see also live regions keyboard navigation often times developers overlook support for the keyboard when they create custom widgets. to be accessible to a variety of users, all features of a web application or widget should also be controllable with the keyboard, without requiring a mouse. in practice, this usually involves following the conventions supported by similar widgets on the desktop, taking full advantage of the tab, enter, spacebar, and arrow keys. traditionally, keyboard navigation on the web has been limited to the tab key. a user presses tab to focus each link, button, or form on the page in a linear order, using shift-tab to navigate backwards. it's a one-dimensional form of navigation—forward and back, o...
...ion. implementing desktop-style keyboard conventions on the web has the potential to significantly speed up navigation for many users. here's a summary of how keyboard navigation should work in an aria-enabled web application: the tab key should provide focus to the widget as a whole. for example, tabbing to a menu bar should not put focus on the menu's first element. the arrow keys should allow for selection or navigation within the widget. for example, using the left and right arrow keys should move focus to the previous and next menu items. when the widget is not inside a form, both the enter and spacebar keys should select or activate the control. within a form, the spacebar key should select or activate the control, while the enter key should submit the form's default action. if ...
...he control, while the enter key should submit the form's default action. if in doubt, mimic the standard desktop behavior of the control you are creating. so, for the tabs widget example above, the user should be able to navigate into and out of the widget's container (the <ol> in our markup) using the tab and shift-tab keys. once keyboard focus is inside the container, the arrow keys should allow the user to navigate between each tab (the <li> elements). from here, conventions vary from platform to platform. on windows, the next tab should automatically be activated when the user presses the arrow keys. on mac os x, the user can press either enter or the spacebar to activate the next tab. an in-depth tutorial for creating keyboard-navigable javascript widgets describes how to implement th...
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...
...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 site benefits all your users, but it is particularly beneficial to users with certain types of color blindness and other similar conditions, who experience low contrast, and have trouble differentiating between similar colors. this is because they don't see bright and dark areas as readily as those without such conditions, and therefore have trouble seeing edges, borders, and other details. it is good to have a cool design on your website, but the design is worthless if your users can't read your content. examples let's have a look at some simple htm...
...ont-weight: bold; width: 250px; padding: 30px; border-radius: 20px; box-shadow: 1px 1px 1px black; } .bad { background-color: #400064; } solution when choosing a color scheme for your website, choose foreground and background colors that have good contrast. make the color contrast as good as it can be within your design constraints — ideally go for the aaa rating (see 1.4.6 below), but at least meet the aa rating (see 1.4.3 below). if you are including non-text content such as video or animation, you should follow 1.4.11 (again, see below). 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 i...
...ss 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, 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. ...
Custom properties (--*): CSS variables - CSS: Cascading Style Sheets
Web › CSS › --*
ation decided by the cascading algorithm. ...
...okens, so long as the sequence does not contain an unallowed token. it represents the entirety of what a valid declaration can have as its value. note: custom property names are case sensitive — --my-color will be treated as a separate custom property to --my-color. ...
... represents the entirety of what a valid declaration can have as its value. note: custom property names are case sensitive — --my-color will be treated as a separate custom property to --my-color. ...
...y-color will be treated as a separate custom property to --my-color. ...
::first-letter (:first-letter) - CSS: Cascading Style Sheets
the ::first-letter css pseudo-element applies styles to the first letter of the first line of a block-level element, but only when not preceded by other content (such as images or inline tables). /* selects the first letter of a <p> */ p::first-letter { font-size: 130%; } the first letter of an element is not always trivial to identify: punctuation that precedes or immediately follows the first letter is included in the match. punctuation includes any unicode character defined in the open (ps), close (pe), initial quote (pi), final quote (pf), and other punctuation (po) classes. some languages have digraphs that are always capitalized together, like the ij in dutch. in these cases, both letters of the digraph should be matched by the ::first-letter pseudo-element. (this is poorly sup...
...ny unicode character defined in the open (ps), close (pe), initial quote (pi), final quote (pf), and other punctuation (po) classes. some languages have digraphs that are always capitalized together, like the ij in dutch. in these cases, both letters of the digraph should be matched by the ::first-letter pseudo-element. ...
...table below.) a combination of the ::before pseudo-element and the content property may inject some text at the beginning of the element. in that case, ::first-letter will match the first letter of this generated content. css3 introduced the ::first-letter notation (with two colons) to distinguish pseudo-classes from pseudo-elements. browsers also accept :first-letter, introduced in css2. ...
...「特殊的汉字标点符号开头。</p> <p>《特殊的汉字标点符号开头。</p> <p>“特殊的汉字标点符号开头。</p> css p::first-letter { color: red; font-size: 150%; } result specifications specification status comment css pseudo-elements level 4the definition of '::first-letter' in that specification. working draft generalizes allowed properties to typesetting, text decoration, inline layout properties, opacity, and box-shadow. css text decoration module level 3the definition of 'text-shadow with ::first-letter' in that specification. candidate recommendation allows the use of text-shadow with ::first-letter. selectors level 3the definition of '::first-letter' in that specification. recommendation ...
range - CSS: Cascading Style Sheets
nity. for additive systems, the range is 0 to positive infinity. for extends systems, the range is whatever auto would produce for the extended system; if extending a complex predefined style (§7 complex predefined counter styles), the range is the style’s defined range. [ [ | infinite ]{2} ]# defines a comma-separated list of ranges. ...
...o would produce for the extended system; if extending a complex predefined style (§7 complex predefined counter styles), the range is the style’s defined range. [ [ | infinite ]{2} ]# defines a comma-separated list of ranges. for each individual range, the first value is the lower bound and the second value is the upper bound. a range is inclusive, that means it always contains both, the lower and upper bound numbers. if infinite is used as the first value in a range, it represents negative infinity; if it is used as the second value, it represents positive infinity. the range of the counter style is the union of all the ranges defined in the list. if the lower bound of any range is higher than the upper bound, the entire descriptor is invalid and will be ignored. description the...
... if value is auto, then for cyclic, numeric, and fixed system, the range will be from negative infinity to positive infinity. ...
...one □. two ■. three □. four 5. five 6. six ■. seven □. eight ■. nine 10. ten specifications specification status comment css counter styles level 3the definition of 'range' in that specification. candidate recommendation initial definition ...
system - CSS: Cascading Style Sheets
riptor called additive-symbols must be specified with at least one additive tuple, or else the counter style rule will not be valid. an additive tuple is similar to a composite counter symbol, which is made up of two parts: a normal counter symbol and a non-negative integer weight. the additive tuples must be specified in the descending order of their weights or the system is invalid. extends allows authors to use the algorithm of another counter style, but alter its other aspects. if a counter style rule is using the extends system, any unspecified descriptors, and their values will be taken from the extended counter style specified. if the specified counter style name in extends, is not a currently defined counter style name, it will instead extend from the decimal counter style. it mu...
...the first symbol provided in the symbols descriptor is interpreted as 0 here. css <ul> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> <li>six</li> <li>seven</li> <li>eight</li> </ul> @counter-style abc { system: numeric; symbols: a b c; suffix: ". "; } ul { list-style: abc; } result numeric counter with numeric symbols as shown in the following example, if digits from 0 to 9 are specified as symbols, this counter style will render symbols same as the decimal counter style. css <ul class="list"> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> <li>six</li> <li>seven</li> <li>eight</li> <li>nine</li> <li>ten</li> </ul> @counter-style numbers { system: numeric; symbols: 0 1 2 3 4 5 6 7 8 ...
...ce that a range is specified. this is because the representation will produce correct roman numerals only until the counter value of 3999. once outside of the range, the rest of the counter representations will be based on the decimal style, which is the fall back. if you need to represent counter values as roman numerals, you could use either one of the predefined counter styles, upper-roman or lower-roman, rather than recreating the rule yourself. html <ul class="list"> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> </ul> css @counter-style upper-roman { system: additive; range: 1 3999; additive-symbols: 1000 m, 900 cm, 500 d, 400 cd, 100 c, 90 xc, 50 l, 40 xl, 10 x, 9 ix, 5 v, 4 iv, 1 i; } ul { list-style: upper-roman; } result extends exa...
...li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> </ul> css @counter-style upper-roman { system: additive; range: 1 3999; additive-symbols: 1000 m, 900 cm, 500 d, 400 cd, 100 c, 90 xc, 50 l, 40 xl, 10 x, 9 ix, 5 v, 4 iv, 1 i; } ul { list-style: upper-roman; } result extends example this example will use the algorithm, symbols, and other properties of the lower-alpha counter style, but will remove the period ('.') after the counter representation, and enclose the characters in paranthesis; like (a), (b), etc. html <ul class="list"> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> </ul> css @counter-style alpha-modified { system: extends lower-alpha; prefix: "("; suffix: ") "; } ul { list-style: alpha-modifie...
@font-feature-values - CSS: Cascading Style Sheets
tivated differently in opentype. this can help simplify your css when using multiple fonts. the @font-feature-values at-rule may be used either at the top level of your css or inside any css conditional-group at-rule. syntax feature value blocks @swash specifies a feature name that will work with the swash() functional notation of font-variant-alternates. a swash feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. @annotation specifies a feature name that will work with the annotation() functional notation of font-variant-alternates. an annotation feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. @ornaments specifies a feature name that will work with the ornaments() functional notation of font-variant-...
...4 isn't. @annotation specifies a feature name that will work with the annotation() functional notation of font-variant-alternates. an annotation feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. @ornaments specifies a feature name that will work with the ornaments() functional notation of font-variant-alternates. an ornaments feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. @stylistic specifies a feature name that will work with the stylistic() functional notation of font-variant-alternates. a stylistic feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. @styleset specifies a feature name that will work with the styleset() functional notation of font-variant-altern...
...dent2: 2 4 isn't. @stylistic specifies a feature name that will work with the stylistic() functional notation of font-variant-alternates. a stylistic feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. @styleset specifies a feature name that will work with the styleset() functional notation of font-variant-alternates. a stylset feature value definition allows an unlimited number of values: ident1: 2 4 12 1 maps to the opentype values ss02, ss04, ss12, and ss01. note that values higher than 99 are valid, but don't map to any opentype values and are ignored. ...
...nition allows an unlimited number of values: ident1: 2 4 12 1 maps to the opentype values ss02, ss04, ss12, and ss01. note that values higher than 99 are valid, but don't map to any opentype values and are ignored. @character-variant specifies a feature name that will work with the character-variant() functional notation of font-variant-alternates. a character-variant feature value definition allows either one or two values: ident1: 3 maps to cv03=1, and ident2: 2 4 maps to cv02=4, but ident2: 2 4 5 is invalid. formal syntax @font-feature-values <family-name># { <feature-value-block-list> }where <family-name> = <string> | <custom-ident>+<feature-value-block-list> = <feature-value-block>+where <feature-value-block> = <feature-type> '{' <feature-value-declaration-list> '}'where <feature-...
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. ...
... 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. ...
... 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. ...
... 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. ...
CSS Containment - CSS: Cascading Style Sheets
the aim of the css containment specification is to improve performance of web pages by allowing developers to isolate a subtree of the page from the rest of the page. if the browser knows that a part of the page is independent, rendering can be optimized and performance improved. the specification defines a single css property contain. this document describes the basic aims of the specification. basic example many webpages contain a number of sections which are independent of each other. for example a listing of article headlines and content, as in the mark-up below. <h1>my blog</h1> <article> <h2>heading of a nice article</h2> <p>content here.</p> </article> <article> <h2>another heading of another article</h2> <p>more content here.</p> </article> each article has the c...
...n the browser may need to account for its size changing). we have told it by way of the contain property that each article is independent. the content value is shorthand for contain: layout paint. it tells the browser that the internal layout of the element is totally separate from the rest of the page, and that everything about the element is painted inside its bounds. nothing can visibly overflow. this information 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 concep...
...y. margins won't collapse across a layout containment boundary the layout container will be a containing block for absolute/fixed position descendants. the containing box creates a stacking context, therefore z-index can be used. paint containment article { contain: paint; } paint containment essentially clips the box to the padding edge of the principal box. there can be no visible overflow. the same things are true for paint containment as layout containment (see above). another advantage is that if the containing box is offscreen, the browser does not need to paint its contained elements — these must also be offscreen as they are contained completely by that box. size containment article { contain: size; } size containment does not offer much in the way of performance opti...
...nt turns on layout and paint containment. the specification describes this value as being "reasonably safe to apply widely". ...
Line-based placement with CSS Grid - CSS: Cascading Style Sheets
* {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 100px); } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; ...
...class="box4">four</div> </div> .box1 { grid-column: 1 ; grid-row: 1 / 4; } .box2 { grid-column: 3 ; grid-row: 1 / 3; } .box3 { grid-column: 2 ; grid-row: 1 ; } .box4 { grid-column: 2 / 4; grid-row: 3 ; } the grid-area property we can take things a step further and define each area with a single property – grid-area. the order of the values for grid-area are as follows. grid-row-start grid-column-start grid-row-end grid-column-end * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 100px); } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color:...
.../div> </div> .box1 { grid-area: 1 / 1 / 4 / 2; } .box2 { grid-area: 1 / 3 / 3 / 4; } .box3 { grid-area: 1 / 2 / 2 / 3; } .box4 { grid-area: 3 / 2 / 4 / 4; } this order of values for grid-area can seem a little strange, it is the opposite of the direction in which we specify margins and padding as a shorthand for example. it may help to realize that this is due to grid using the flow-relative directions defined in the css writing modes specification. we will explore how grids work with writing modes in a later article however we have the concept of four flow-relative directions: block-start block-end inline-start inline-end we are working in english, a left-to-right language. our block-start is the top row line of the grid container, block-end the final row line of th...
...x3">three</div> <div class="box4">four</div> </div> .box1 { grid-column: 1; grid-row: 1 / span 3; } .box2 { grid-column: 3; grid-row: 1 / span 2; } .box3 { grid-column: 2; grid-row: 1; } .box4 { grid-column: 2 / span 2; grid-row: 3; } you can also use the span keyword in the value of grid-row-start/grid-row-end and grid-column-start/grid-column-end. the following two examples will create the same grid area. in the first we set the start row line, then the end line we explain that we want to span 3 lines. the area will start at line 1 and span 3 lines to line 4. .box1 { grid-column-start: 1; grid-row-start: 1; grid-row-end: span 3; } in the second example, we specify the end row line we want the item to finish at and then set the start li...
Logical properties for sizing - CSS: Cascading Style Sheets
in this guide we will explain the flow-relative mappings between physical dimension properties and logical properties used for sizing elements on our pages. when specifying the size of an item, the logical properties and values specification gives you the ability to indicate sizing as it relates to the flow of text (inline and block) rather than physical sizing which relates to the physical dimensions of horizontal and vertical (e.g. left and right). while these flow relative mappings may well become the default for many of us, in a design you may well use both physical and logical sizing. you might want some features to always relate to the physical dimensions whatever the writing mode. mappings for dimensions the table below provides mappings between logical and physical properties. the...
...x-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 and height with block-size will give the 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 ...
......
...mple finally you can use max-inline-size and max-block-size as logical replacements for max-width and max-height. try playing with the below example in the same way as before. logical keywords for resize the resize property sets whether or not an item can be resized and has physical values of horizontal and vertical. the resize property also has logical keyword values. using resize: inline allows resizing in the inline dimension and resize: block allow resizing in the block dimension. the keyword value of both for the resize property works whether you are thinking physically or logically. it sets both dimensions at once. try playing with the below example. note that currently the logical values for resize are only supported by firefox. ...
Inline formatting context - CSS: Cascading Style Sheets
ng context core concepts the inline formatting context is part of the visual rendering of a web page. inline boxes are laid out one after the other, in the direction sentences run in the writing mode in use: in a horizontal writing mode, boxes are laid out horizontally, starting 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...
...f inline line boxes, stacked in the block direction. when an inline box is split, margins, borders, and padding have no visual effect where the split occurs. in the next example there is a (<span>) element wrapping a set of words wrapping onto two lines. the border on the <span> breaks at the wrapping point. margins, borders, and padding in the inline direction are respected. in the example below you can see how the margin, border, and padding on the inline <span> element are added. note: i am using the logical, flow-relative properties — padding-inline-start rather than padding-left — so that they work in the inline dimension whether the text is horizontal or vertical. read more about these properties in logical properties and values. alignment in the block direction inline bo...
...they work in the inline dimension whether the text is horizontal or vertical. read more about these properties in logical properties and values. alignment in the block direction inline boxes may be aligned in the block direction in different ways, using the vertical-align property, which will align on the block axis in vertical writing modes (therefore not vertically at all!). in the example below the large text is making the line box of the first sentence larger, therefore the vertical-align property can be used to align the inline boxes either side of it. i have used the value top, try changing it to middle, bottom, or baseline. alignment in the inline direction if there is additional space in the inline direction, the text-align property can be used to align the inline boxes within ...
...tence larger, therefore the vertical-align property can be used to align the inline boxes either side of it. i have used the value top, try changing it to middle, bottom, or baseline. alignment in the inline direction if there is additional space in the inline direction, the text-align property can be used to align the inline boxes within their line box. try changing the value of text-align below to end. effect of floats line boxes usually have the same size in the inline direction, therefore the same width if working in a horizontal writing mode, or height if working in a vertical writing mode. if there is a float within the same block formatting context however, the float will cause the line boxes that wrap the float to become shorter. ...
appearance (-moz-appearance, -webkit-appearance) - CSS: Cascading Style Sheets
menulist-button; -webkit-appearance: menulist-button; } <div>lorem</div> firefox chrome safari edge the element is styled as a button that would indicate a menulist can be opened. textfield div { color: black; -moz-appearance: textfield; -webkit-appearance: textfield; } <div>lorem</div> firefox chrome safari edge the following values are treated as equivalent to auto: button div { color: black; -moz-appearance: button; -webkit-appearance: button; } <div>lorem</div> firefox chrome safari edge the element is drawn like a button. checkbox div { color: black; -moz-appearance: checkbox; -webkit-appearance: checkbox; } <div>lorem</div> ...
... value demo browser description attachment div{ color: black; -moz-appearance: attachment; -webkit-appearance: attachment; } <div>lorem</div> safari borderless-attachment div{ color: black; -m...
...earance: textfield-multiline; -webkit-appearance: textfield-multiline; } <div>lorem</div> firefox use textarea instead. -apple-pay-button div{ color: black; -webkit-appearance: -apple-pay-button; } <div>lorem</div> safari ios and macos only. available on the web starting in ios 10.1 and macos 10.12.1 obsolete values the following values were at some point implemented for a prefixed property, but are no longer supported. value browser description button-arrow-down firefox removed in firefox 64 button-arrow-next firefox removed in firefox 64 button-arrow-previous firefox removed in firefox 64 button-arrow-up firefox removed in...
...d in firefox 64. formal definition initial valueautoapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | auto | button | textfield | menulist-button | <compat-auto>where <compat-auto> = searchfield | textarea | push-button | slider-horizontal | checkbox | radio | square-button | menulist | listbox | meter | progress-bar examples the following would make an element look like a menulist button: .exampleone { appearance: menulist-button; } see also this jsfiddle for an example showing how you might use appearance: none to apply custom styling to radio buttons and checkboxes. specifications specification status comment css basic user interface module level 4the definition of 'appearance' in that speci...
background-size - CSS: Cascading Style Sheets
using a width value only, in which case the height defaults to auto. using both a width and a height value, in which case the first sets the width and the second sets the height. each value can be a <length>, a <percentage>, or auto. to specify the size of multiple background images, separate the value for each one with a comma. values ...
...e without stretching the image. if the proportions of the image differ from the element, it is cropped either vertically or horizontally so that no empty space remains. auto scales 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. ...
... a vector image (such as svg) does not necessarily have intrinsic dimensions. ...
...g area. note: in gecko, background images created using the element() function are currently treated as images with the dimensions of the element, or of the background positioning area if the element is svg, with the corresponding intrinsic proportion. this is non-standard behavior. based on the intrinsic dimensions and proportions, the rendered size of the background image is computed as follows: if both components of background-size are specified and are not auto: the background image is rendered at the specified size. if the background-size is contain or cover: while preserving its intrinsic proportions, the image is rendered at the largest size contained within, or covering, the background positioning area. if the image has no intrinsic proportions, then it's rendered at the si...
border-radius - CSS: Cascading Style Sheets
the border-radius property does not apply to table elements when border-collapse is collapse. note: as with any shorthand property, individual sub-properties cannot inherit, such as in border-radius:0 0 inherit inherit, which would partially override existing definitions. instead, the individual longhand properties have to be used. ...
...such as in border-radius:0 0 inherit inherit, which would partially override existing definitions. instead, the individual longhand properties have to be used. ...
...the first radius allows one to four values */ /* radius is set for all 4 sides */ border-radius: 10px; /* top-left-and-bottom-right | top-right-and-bottom-left */ border-radius: 10px 5%; /* top-left | top-right-and-bottom-left | bottom-right */ border-radius: 2px 4px 2px; /* top-left | top-right | bottom-right | bottom-left */ border-radius: 1px 0 3px 4px; /* the syntax of the second radius allows one to four values */ /* (first radius values) / radius */ border-radius: 10px / 20px; /* (first radius values) / top-left-and-bottom-right | top-right-and-bottom-left */ border-radius: 10px 5% / 20px 30px; /* (first radius values) / top-left | top-right-and-bottom-left | bottom-right */ border-radius: 10px 5px 2em / 20px 25px 30%; /* (first radius values) / top-left | top-right | bottom-righ...
... / 20px 25px 30%; /* (first radius values) / top-left | top-right | bottom-right | bottom-left */ border-radius: 10px 5% / 20px 25em 30px 35em; /* global values */ border-radius: inherit; border-radius: initial; border-radius: unset; the border-radius property is specified as: one, two, three, or four <length> or <percentage> values. this is used to set a single radius for the corners. followed optionally by "/" and one, two, three, or four <length> or <percentage> values. this is used to set an additional radius, so you can have elliptical corners. values radius is a <length> or a <percentage> denoting a radius to use for the border in each corner of the border. it is used only in the one-value syntax. top-left-and-bottom-right is a <length> or a <p...
box-lines - CSS: Cascading Style Sheets
Web › CSS › box-lines
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 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...
...ts 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 that line and overflow out of the box. the later lines are placed below the earlier lines in normal direction boxes and above in reverse direction boxes. the height of a line is the height of the largest child in that line. no additional space appears between the lines 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 treat...
...ecessary 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 the box-lines property is specified as one of the keyword values listed below. ...
...this was only supported in webkit-based browsers, with a prefix. div { display: box; box-orient: horizontal; box-lines: multiple; } the modern flexbox equivalent is flex-wrap. ...
box-shadow - CSS: Cascading Style Sheets
send us a pull request. the box-shadow property enables you to cast a drop shadow from the frame of almost any element. if a border-radius is specified on the element with a box shadow, the box shadow takes on the same rounded corners. the z-ordering of multiple box shadows is the same as multiple text shadows (the first specified shadow is on top). box-shadow generator is an interactive tool allowing you to generate a box-shadow. syntax /* keyword values */ box-shadow: none; /* offset-x | offset-y | color */ box-shadow: 60px -16px teal; /* offset-x | offset-y | blur-radius | color */ box-shadow: 10px 5px 5px black; /* offset-x | offset-y | blur-radius | spread-radius | color */ box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2); /* inset | offset-x | offset-y | color */ box-shadow: inset...
...rovide a comma-separated list of shadows. values inset if not specified (default), the shadow is assumed to be a drop shadow (as if the box were raised above the content). the presence of the inset keyword changes the shadow to one inside the frame (as if the content was depressed inside the box). inset shadows are drawn inside the border (even transparent ones), above the background, but below content. <offset-x> <offset-y> these are two <length> values to set the shadow offset. <offset-x> specifies the horizontal distance. negative values place the shadow to the left of the element. <offset-y> specifies the vertical distance. negative values place the shadow above the element. see <length> for possible units. if both values are 0, the shadow is placed behind the element (and may ge...
... distance. negative values place the shadow above the element. see <length> for possible units. if both values are 0, the shadow is placed behind the element (and may generate a blur effect if <blur-radius> and/or <spread-radius> is set). <blur-radius> this is a third <length> value. the larger this value, the bigger the blur, so the shadow becomes bigger and lighter. ...
...adius> and/or <spread-radius> is set). <blur-radius> this is a third <length> value. the larger this value, the bigger the blur, so the shadow becomes bigger and lighter. negative values are not allowed. if not specified, it will be 0 (the shadow's edge is sharp). the specification does not include an exact algorithm for how the blur radius should be calculated, however, it does elaborate as follows: …for a long, straight shadow edge, this should create a color transition the length of the blur distance that is perpendicular to and centered on the shadow’s edge, and that ranges from the full shadow color at the radius endpoint inside the shadow to fully transparent at the endpoint outside it. <spread-radius> this is a fourth <length> value. positive values will cause the shadow t...
break-after - CSS: Cascading Style Sheets
; break-after: region; /* global values */ break-after: inherit; break-after: initial; break-after: unset; each possible break point (in other words, each element boundary) is affected by three properties: the break-after value of the previous element, the break-before value of the next element, and the break-inside value of the containing element. to determine if a break must be done, the following rules are applied: if any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. if more than one of them are such a break, the one of the element that appears the latest in the flow is taken (i.e., the break-before value has precedence over the break-after value, which itself has precedence over the break-inside value). if ...
...f any of the three concerned values is an avoid break value (avoid, avoid-page, avoid-region, or avoid-column), no such break will be applied at that point. once forced breaks have been applied, soft breaks may be added if needed, but not on element boundaries that resolve in a corresponding avoid value. syntax the break-after property is specified as one of the keyword values from the list below. values generic break values auto allows, but does not force, any break (page, column, or region) to be inserted right after the principal box. avoid avoids any break (page, column, or region) from being inserted right after the principal box. always forces a page break right after the principal box. the type of this break is that of the immediately-containing fragmentation context. i...
... avoid-region avoids any region break right after the principal box. region forces a region break right after the principal box. page break aliases for compatibility reasons, the legacy page-break-after property should be treated by browsers as an alias of break-after. this ensures that sites using page-break-after continue to work as designed. a subset of values should be aliased as follows: page-break-after break-after auto auto left left right right avoid avoid always page the always value of page-break-* was implemented by browsers as a page break, and not as a column break. therefore the aliasing is to page, rather than the always value in the level 4 spec. formal definition initial valueaut...
...fore the aliasing is to page, rather than the always value in the level 4 spec. formal definition initial valueautoapplies toblock-level elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | avoid | always | all | avoid-page | page | left | right | recto | verso | avoid-column | column | avoid-region | region examples breaking into neat columns in the following example we have a container that contains an <h1> spanning all columns (achieved using column-span: all) and a series of <h2>s and paragraphs laid out in multiple columns using column-width: 200px. by default, the subheadings and paragraphs were laid out rather messily because the headings were not in a uniform place. however, we used break-after: column on the <p> elements to force a column ...
break-before - CSS: Cascading Style Sheets
eak-before: region; /* global values */ break-before: inherit; break-before: initial; break-before: unset; each possible break point (in other words, each element boundary) is affected by three properties: the break-after value of the previous element, the break-before value of the next element, and the break-inside value of the containing element. to determine if a break must be done, the following rules are applied: if any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. if more than one of them are such a break, the one of the element that appears the latest in the flow is taken (i.e., the break-before value has precedence over the break-after value, which itself has precedence over the break-inside value). if ...
... any of the three concerned values is an avoid break value (avoid, avoid-page, avoid-region, or avoid-column), no such break will be applied at that point. once forced breaks have been applied, soft breaks may be added if needed, but not on element boundaries that resolve in a corresponding avoid value. syntax the break-before property is specified as one of the keyword values from the list below. values generic break values auto allows, but does not force, any break (page, column, or region) to be inserted right before the principal box. avoid avoids any break (page, column, or region) from being inserted right before the principal box. always forces a page break right after the principal box. the type of this break is that of the immediately-containing fragmentation context.
...d-region avoids any region break right before the principal box. region forces a region break right before the principal box. page break aliases for compatibility reasons, the legacy page-break-before property should be treated by browsers as an alias of break-before. this ensures that sites using page-break-before continue to work as designed. a subset of values should be aliased as follows: page-break-before break-before auto auto left left right right avoid avoid always page the always value of page-break-* was implemented by browsers as a page break, and not as a column break. therefore the aliasing is to page, rather than the always value in the level 4 spec. formal definition initial valuea...
...fore the aliasing is to page, rather than the always value in the level 4 spec. formal definition initial valueautoapplies toblock-level elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | avoid | always | all | avoid-page | page | left | right | recto | verso | avoid-column | column | avoid-region | region examples breaking into neat columns in the following example we have a container that contains an <h1> spanning all columns (achieved using column-span: all) and a series of <h2>s and paragraphs laid out in multiple columns using column-width: 200px. by default, the subheadings and paragraphs were laid out rather messily because the headings were not in a uniform place. however, we used break-before: column on the <h2> elements to force a colum...
break-inside - CSS: Cascading Style Sheets
side: avoid-region; /* global values */ break-inside: inherit; break-inside: initial; break-inside: unset; each possible break point (in other words, each element boundary) is affected by three properties: the break-after value of the previous element, the break-before value of the next element, and the break-inside value of the containing element. to determine if a break must be done, the following rules are applied: if any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. if more than one of them are such a break, the value of the element that appears the latest in the flow is used. thus, the break-before value has precedence over the break-after value, which in turn has precedence over the break-inside value. if...
... any of the three concerned values is an avoid break value (avoid, avoid-page, avoid-region, or avoid-column), no such break will be applied at that point. once forced breaks have been applied, soft breaks may be added if needed, but not on element boundaries that resolve in a corresponding avoid value. syntax the break-inside property is specified as one of the keyword values from the list below. values auto allows, but does not force, any break (page, column, or region) to be be inserted within the principal box. avoid avoids any break (page, column, or region) from being inserted within the principal box. avoid-page avoids any page break within the principal box. avoid-column avoids any column break within the principal box. avoid-region avoids any region break within th...
... avoid-column avoids any column break within the principal box. avoid-region avoids any region break within the principal box. page break aliases for compatibility reasons, the legacy page-break-inside property should be treated by browsers as an alias of break-inside. this ensures that sites using page-break-inside continue to work as designed. ...
...we also have a <figure> containing an image and a caption. ...
caption-side - CSS: Cascading Style Sheets
send us a pull request. syntax /* directional values */ caption-side: top; caption-side: bottom; /* warning: non-standard values */ caption-side: left; caption-side: right; caption-side: top-outside; caption-side: bottom-outside; /* global values */ caption-side: inherit; caption-side: initial; caption-side: unset; the caption-side property is specified as one of the keyword values listed below. values top the caption box should be positioned above the table. bottom the caption box should be positioned below the table. left the caption box should be positioned on the left side of the table. this value was proposed for css 2, but removed from the final css 2.1 specification. it is non-standard. right the caption box should be positioned on the right side of the table.
...de the caption box should be positioned above the table, while the width and horizontal alignment behavior are not bound to the table's horizontal layout. the css 2.1 specification notes that the css 2 specification described a different behavior for the top value, which will be reintroduced by this value in a future specification. bottom-outside the caption box should be positioned below the table, while the width and horizontal alignment behavior are not bound to the table's horizontal layout. the css 2.1 specification notes that the css 2 specification described a different behavior for the bottom value, which will be reintroduced by this value in a future specification. formal definition initial valuetopapplies totable-caption elementsinheritedyescomputed valueas speci...
...the css 2 specification described a different behavior for the bottom value, which will be reintroduced by this value in a future specification. ...
...ption elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax top | bottom | block-start | block-end | inline-start | inline-end examples setting captions above and below html <table class="top"> <caption>caption above the table</caption> <tr> <td>some data</td> <td>some more data</td> </tr> </table> <br> <table class="bottom"> <caption>caption below the table</caption> <tr> <td>some data</td> <td>some more data</td> </tr> </table> css .top caption { caption-side: top; } .bottom caption { caption-side: bottom; } table { border: 1px solid red; } td { border: 1px solid blue; } result specifications specification status comment css logical properties and values level 1the definition of ...
clip-path - CSS: Cascading Style Sheets
Web › CSS › clip-path
0% 0%, 100% 50%, 50% 100%, 0% 50%); clip-path: path('m0.5,1 c0.5,1,0,0.7,0,0.3 a0.25,0.25,1,1,1,0.5,0.3 a0.25,0.25,1,1,1,1,0.3 c1,0.7,0.5,1,0.5,1 z'); /* box and shape values combined */ clip-path: padding-box circle(50px at 0 100px); /* global values */ clip-path: inherit; clip-path: initial; clip-path: unset; the clip-path property is specified as one or a combination of the values listed below. values <clip-source> a <url> referencing an svg <clippath> element. <basic-shape> a shape whose size and position is defined by the <geometry-box> value. if no geometry box is specified, the border-box will be used as the reference box. <geometry-box> if specified in combination with a <basic-shape>, this value defines the reference box for the basic shape. if specified by itself, it ca...
...value. if no geometry box is specified, the border-box will be used as the reference box. <geometry-box> if specified in combination with a <basic-shape>, this value defines the reference box for the basic shape. if specified by itself, it causes the edges of the specified box, including any corner shaping (such as a border-radius), to be the clipping path. the geometry box can be one of the following values: margin-box uses the margin box as the reference box. border-box uses the border box as the reference box. padding-box uses the padding box as the reference box. content-box uses the content box as the reference box. fill-box uses the object bounding box as the reference box. stroke-box uses the stroke bounding box as the reference box. view-box uses the ...
... viewbox"> <svg viewbox="0 0 192 192"> <g class="none"> <rect x="24" y="24" width="144" height="144" /> <text x="96" y="91">i love</text> <text x="96" y="109" class="em">clipping</text> </g> </svg> </div> </div> </div> <div class="note">clip-path: url(#mypath)<br><br> assuming the following clippath definition: <pre> &lt;svg&gt; &lt;clippath id="mypath" clippathunits="objectboundingbox"&gt; &lt;path d="m0.5,1 c 0.5,1,0,0.7,0,0.3 a 0.25,0.25,1,1,1,0.5,0.3 a 0.25,0.25,1,1,1,1,0.3 c 1,0.7,0.5,1,0.5,1 z" /&gt; &lt;/clippath&gt; &lt;/svg&gt;</pre> </div> <div class="row"> <div class="cell"> <span>html</span> <div class="conta...
... </div> </div> </div> </div> </div> html,body { height: 100%; box-sizing: border-box; background: #eee; } .grid { width: 100%; height: 100%; display: flex; font: 1em monospace; } .row { display: flex; flex: 1 auto; flex-direction: row; flex-wrap: wrap; } .col { flex: 1 auto; } .cell { margin: .5em; padding: .5em; background-color: #fff; overflow: hidden; text-align: center; flex: 1; } .note { background: #fff3d4; padding: 1em; margin: .5em .5em 0; font: .8em sans-serif; text-align: left; white-space: nowrap; } .note + .row .cell { margin-top: 0; } .container { display: inline-block; border: 1px dotted grey; position:relative; } .container:before { content: 'margin'; position: absolute; top: 2px; left: ...
contain - CSS: Cascading Style Sheets
Web › CSS › contain
this property is useful on pages that contain a lot of widgets that are all independent, as it can be used to prevent each widget's internals from having side effects outside of the widget's bounding-box. note: if applied (with value: paint, strict or content), this property creates: a new containing block (for the descendants whose position property is absolute or fixed). a new stacking context. ...
...cking context. a new block formatting context. syntax /* keyword values */ contain: none; contain: strict; contain: content; contain: size; contain: layout; contain: style; contain: paint; /* multiple keywords */ contain: size paint; contain: size layout paint; /* global values */ contain: inherit; contain: initial; contain: unset; the contain property is specified as either one of the following: using a single none, strict, or content keyword. using one or more of the size, layout, style, and paint keywords in any order. values none indicates the element 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 containme...
...ape the containing element. note that this value is marked "at-risk" in the spec and may not be supported everywhere. paint indicates that descendants of the element don't display outside its bounds. if the containing box is offscreen, the browser does not need to paint its contained elements — these must also be offscreen as they are contained completely by that box. ...
... completely by that box. and if a descendant overflows the containing element's bounds, then that descendant will be clipped to the containing element's border-box. ...
cross-fade() - CSS: Cascading Style Sheets
included percentages are added together and subtracted from 100%. the result, if greater than 0, is then divided equally between all images with omitted percentages. in the last example, the sum of both percentages is not 100%, and therefore both images include their respective opacities. if no percentages are declared and three images are included, each image will be 33.33% opaque. ...
...result, if greater than 0, is then divided equally between all images with omitted percentages. in the last example, the sum of both percentages is not 100%, and therefore both images include their respective opacities. if no percentages are declared and three images are included, each image will be 33.33% opaque. the two following are lines (almost) identical: cross-fade( url(red.png), url(yellow.png), url(blue.png)); /* all three will be 33.3333% opaque */ cross-fade( url(red.png) 33.33%, url(yellow.png) 33.33%, url(blue.png) 33.33%); older, implemented syntax cross-fade( <image, <image>, <percentage> ) the specification for the cross-fade() function allows for multiple images and for each image to have transparency values independent of the other values. this was not always the case.
...the original syntax is supported in safari and supported with the -webkit- prefix in chrome, opera, and other blink-based browsers. ...
.../* fully black */ cross-fade(url(white.png), url(black.png), 25%); /* 25% white, 75% black */ cross-fade(url(white.png), url(black.png), 50%); /* 50% white, 50% black */ cross-fade(url(white.png), url(black.png), 75%); /* 75% white, 25% black */ cross-fade(url(white.png), url(black.png), 100%); /* fully white */ in the implemented syntax, the two comma-separated images are declared first, followed by a comma and required percent value. omitting the comma or percent invalidates the value. the percent is the opacity of the first declared image. the included percentage is subtracted from 100%, with the difference being the opacity of the second image. the green/red example (with the percentages totalling 150%) and the yellow/red/blue example (with three images) from the specification synta...
cursor - CSS: Cascading Style Sheets
Web › CSS › cursor
these will set ...
...these will set the cursor's hotspot, relative to the top-left corner of the image. ...
...t can be selected. typically the shape of a sideways i-beam. drag & drop alias an alias or shortcut is to be created. copy something is to be copied. move something is to be moved. no-drop an item may not be dropped at the current location. bug 275173: on windows and mac os x, no-drop is the same as not-allowed. not-allowed the requested action will not be carried out. grab something can be grabbed (dragged to be moved). grabbing something is being grabbed (dragged to be moved). resizing & scrolling all-scroll something can be scrolled in any direction (panned). bug 275174: on windows, all-scroll is the same a...
...table for any notes on cursor size limits. ...
<display-outside> - CSS: Cascading Style Sheets
the <display-outside> keywords specify the element’s outer display type, which is essentially its role in flow layout. 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-inside> keywords. syntax valid <display-outside> values: block the element generates a block element box, generating line breaks both before and after the element when in the normal flow. inline the element generates one or more inline element boxes that do not generate line breaks before or after themselves. in normal flow, the next element will be on the same line if there is space run-in the element generates a run-in box. if the adjacent sibling of the element defin...
...line the element generates one or more inline element boxes that do not generate line breaks before or after themselves. in normal flow, the next element will be on the same line if there is space run-in the element generates a run-in box. if the adjacent sibling of the element defined as display: run-in box is a block box, the run-in box becomes the first inline box of the block box that follows it. run-in elements act like inlines or blocks, depending on the surrounding elements. that is: if the run-in box contains a block box, same as block. if a block box follows the run-in box, the run-in box becomes the first inline box of the block box. if an inline box follows, the run-in box becomes a block box. note: browsers that support the two value syntax, on finding the outer value ...
...t is: if the run-in box contains a block box, same as block. if a block box follows the run-in box, the run-in box becomes the first inline box of the block box. if an inline box follows, the run-in box becomes a block box. note: browsers that support the two value syntax, on finding the outer value only, such as when display: block or display: inline is specified, will set 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. ...
... note: browsers that support the two value syntax, on finding the outer value only, such as when display: block or display: inline is specified, will set 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. examples in the following example, span elements (normally displayed as inline elements) are set to display: block and so break onto new lines and expand to fill their container in the inline dimension. html <span>span 1</span> <span>span 2</span> css span { display: block; border: 1px solid rebeccapurple; } result specifications specification status css display module level 3t...
<easing-function> - CSS: Cascading Style Sheets
ending on the specific function used, the calculated output can sometimes grow to be greater than 1.0 or smaller than 0.0 during the course of an animation. this causes the animation to go farther than the final state, and then return. for some properties, such as left or right, this creates a kind of "bouncing" effect. however, certain properties will restrict the output if it goes outside an allowable range. for example, a color component greater than 255 or smaller than 0 will be clipped to the closest allowed value (255 and 0, respectively). some cubic-bezier() curves exhibit this property. syntax there are three types of easing function: linear, cubic bézier curves, and staircase functions. the value of an <easing-function> type describes the easing function using one of those three ...
...ypes of easing function: linear, cubic bézier curves, and staircase functions. the value of an <easing-function> type describes the easing function using one of those three types. easing functions css supports three kinds of easing functions: linear, the subset of the cubic bézier curves that are functions, and staircase functions. the most useful of these functions are given a keyword that allows them to be easily referenced. the linear class of easing functions linear the animation moves from beginning to end at a constant rate. this keyword represents the easing function cubic-bezier(0.0, 0.0, 1.0, 1.0). the cubic-bezier() class of easing functions the cubic-bezier() functional notation defines a cubic bézier curve. as these curves are continuous, they are often used to smoot...
...cify an invalid cubic-bezier curve, css ignores the whole property. syntax cubic-bezier(x1, y1, x2, y2) where: x1, y1, x2, y2 are <number> values representing the abscissas, and ordinates of the p1 and p2 points defining the cubic bézier curve. x1 and x2 must be in the range [0, 1] or the value is invalid. keywords for common cubic-bezier easing functions ease the animation starts slowly, accelerates sharply, and then slows gradually towards the end. this keyword represents the easing function cubic-bezier(0.25, 0.1, 0.25, 1.0). it is similar to ease-in-out, though it accelerates more sharply at the beginning. ease-in the animation starts slowly, and then progressively speeds up until the end, at which point it stops abruptly. this keyword represents the easing function cub...
...s keyword represents the easing function cubic-bezier(0.25, 0.1, 0.25, 1.0). it is similar to ease-in-out, though it accelerates more sharply at the beginning. ease-in the animation starts slowly, and then progressively speeds up until the end, at which point it stops abruptly. this keyword represents the easing function cubic-bezier(0.42, 0.0, 1.0, 1.0). ease-in-out the animation starts slowly, speeds up, and then slows down towards the end. this keyword represents the easing function cubic-bezier(0.42, 0.0, 0.58, 1.0). at the beginning, it behaves like the ease-in function; at the end, it is like the ease-out function. ease-out the animation starts abruptly, and then progressively slows down towards the end. this keyword represents the easing function cubic-bezier(0.0, 0.0, 0.58...
float - CSS: Cascading Style Sheets
Web › CSS › float
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 floating element is one where the computed value of float is not none. ...
...loat" is a reserved word in javascript, as seen in the need to escape "class" as "classname" and escape <label>'s "for" as "htmlfor"). syntax /* keyword values */ float: left; float: right; float: none; float: inline-start; float: inline-end; /* global values */ float: inherit; float: initial; float: unset; the float property is specified as a single keyword, chosen from the list of values below. values left the element must float on the left side of its containing block. right the element must float on the right side of its containing block. none the element must not float. inline-start the element must float on the start side of its containing block. that is the left side with ltr scripts, and the right side with rtl scripts. inline-end the element must float on the end si...
..., and the left side with rtl scripts. formal definition initial valuenoneapplies toall elements, but has no effect if the value of display is none.inheritednocomputed valueas specifiedanimation typediscrete formal syntax left | right | none | inline-start | inline-end examples how floated elements are positioned as mentioned above, when an element is floated, it is taken out of the normal flow of the document (though still remaining part of it). it is shifted to the left, or right, until it touches the edge of its containing box, or another floated element. in this example, there are three colored squares. two are floated left, and one is floated right. note that the second "left" square is placed to the right of the first. additional squares would continue to stack to the right, unti...
...liquet tincidunt vel in massa. phasellus feugiat est vel leo finibus congue.</p> </section> css section { border: 1px solid blue; width: 100%; float: left; } div { margin: 5px; width: 50px; height: 150px; } .left { float: left; background: pink; } .right { float: right; background: cyan; } result clearing floats sometimes you may want to force an item to move below any floated elements. for instance, you may want paragraphs to remain adjacent to floats, but force headings to be on their own line. see clear for examples. specifications specification status comment css logical properties and values level 1the definition of 'float and clear' in that specification. editor's draft adds the values inline-start and inline-end. ...
font-style - CSS: Cascading Style Sheets
blique faces are simulated by artificially sloping the glyphs of the regular face (use font-synthesis to control this behavior). syntax font-style: normal; font-style: italic; font-style: oblique; font-style: oblique 10deg; /* global values */ font-style: inherit; font-style: initial; font-style: unset; the font-style property is specified as a single keyword chosen from the list of values below, which can optionally include an angle if the keyword is oblique. values normal selects a font that is classified as normal within a font-family. italic selects a font that is classified as italic. if no italic version of the face is available, one classified as oblique is used instead. if neither is available, the style is artificially simulated. oblique selects a font that is classifie...
...onts can offer a fine control over the degree to which an oblique face is slanted. you can select this using the <angle> modifier for the oblique keyword. for truetype or opentype variable fonts, 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>. html <header> <input type="range" id="slant" name="slant" min="-90" max="90" /> <label for="slant">slant</label> </header> <div class="container"> <p class="sample">...it would not be wonderful to meet a megalosaurus, forty feet long or so, waddling like a...
...que can accept an <angle>. ...
...ed by david berlow (https://github.com/typenetwork/amstelvar) and is used here under the terms of its license: https://github.com/typenetwork/amstelvar/blob/master/ofl.txt */ @font-face { src: url('https://mdn.mozillademos.org/files/16044/amstelvaralpha-vf.ttf'); font-family:'amstelvaralpha'; font-style: normal; } label { font: 1rem monospace; } .container { max-height: 150px; overflow: scroll; } .sample { font: 2rem 'amstelvaralpha', sans-serif; } html, body { max-height: 100vh; max-width: 100vw; overflow: hidden; } body { display: flex; flex-direction: column; } header { margin-bottom: 1.5rem; } .container { flex-grow: 1; } .container > p { margin-top: 0; margin-bottom: 0; } javascript let slantlabel = document.queryselector('label[for="slant"...
font - CSS: Cascading Style Sheets
Web › CSS › font
pull request. as with any shorthand property, any individual value that is not specified is set to its corresponding initial value (possibly overriding values previously set using non-shorthand properties). though not directly settable by font, the longhands font-size-adjust and font-kerning are also reset to their initial values. constituent properties this property is a shorthand for the following css properties: font-family font-size font-stretch font-style font-variant font-weight line-height syntax the font property may be specified as either a single keyword, which will select a system font, or as a shorthand for various font-related properties. if font is specified as a system keyword, it must be one of: caption, icon, menu, message-box, small-caption, status-bar. if ...
...ize> <font-family> it may optionally include values for: <font-style> <font-variant> <font-weight> <font-stretch> <line-height> font-style, font-variant and font-weight must precede font-size font-variant may only specify the values defined in css 2.1, that is normal and small-caps font-stretch may only be a single keyword value. line-height must immediately follow font-size, preceded by "/", like this: "16px/3" font-family must be the last value specified. values <'font-style'> see the font-style css property. <'font-variant'> see the font-variant css property. <'font-weight'> see the font-weight css property. <'font-stretch'> see the font-stretch css property. <'font-size'> see the font-size css property. <'line-height'> see the line-heig...
...ue (if no parent element present). set the font family to sans-serif */ p { font: 80% sans-serif } /* set the font weight to bold, the font-style to italic, the font size to large, and the font family to serif. */ p { font: bold italic large serif } /* use the same font as the status bar of the window */ p { font: status-bar } live sample html <p> change the radio buttons below to see the generated shorthand and it's effect. </p> <form action="createshorthand()"> <div class="cf"> <div class="setpropcont"> font-style<br/> <input type="radio" id="font-style-none" name="font_style" checked="" value="" onchange="setcss()"> <label for="font-style-none">none</label><br/> <input type="radio" id="font-style-normal" name="font_styl...
...ight <br/> optional </div> <div class="propinputcont"> <input type="text" class="curcss mandatory" id="input_font_family"> <br/> font-family <br/> mandatory </div> </div> </form> <div class="fontshorthand"> this is some sample text. ...
justify-items - CSS: Cascading Style Sheets
justify-items: flex-end; /* equivalent to 'end'. note that justify-items is ignored in flexbox layouts. ...
...: unset; this property can take one of four different forms: basic keywords: one of the keyword values normal, auto, or stretch. baseline alignment: the baseline keyword, plus optionally one of first or last. positional alignment: one of: center, start, end, flex-start, flex-end, self-start, self-end, left, or right. plus optionally safe or unsafe. legacy alignment: the legacy keyword, followed by one of left or right. values auto the value used is the value of the justify-items property of the parents box, unless the box has no parent, or is absolutely positioned, in these cases, auto represents normal. normal the effect of this keyword is dependent of the layout mode we are in: in block-level layouts, the keyword is a synonym of start. in absolutely-positioned layouts,...
...for last baseline is end. stretch if the combined size of the items is less than the size of the alignment container, any auto-sized items have their size increased equally (not proportionally), while still respecting the constraints imposed by max-height/max-width (or equivalent functionality), so that the combined size exactly fills the alignment container. safe if the size of the item overflows the alignment container, the item is instead aligned 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. legacy makes the value inherited by the box descendants. note that if a descendant has a justify-self: auto value, the legacy keyword is not considered by the descend, only the left, right,...
...kes the value inherited by the box descendants. note that if a descendant has a justify-self: auto value, the legacy keyword is not considered by the descend, only the left, right, or center value associated to it. formal definition initial valuelegacyapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax normal | stretch | <baseline-position> | <overflow-position>? [ <self-position> | left | right ] | legacy | legacy && [ left | right | center ]where <baseline-position> = [ first | last ]? baseline<overflow-position> = unsafe | safe<self-position> = center | start | end | self-start | self-end | flex-start | flex-end examples simple demonstration in the following example we have a simple 2 x 2 grid layout. initially the grid container is given...
<length> - CSS: Cascading Style Sheets
Web › CSS › length
value. lengths can be used in numerous css properties, such as width, height, margin, padding, border-width, font-size, and text-shadow. note: although <percentage> values are also css dimensions, and are usable in some of the same properties that accept <length> values, they are not themselves <length> values. see <length-percentage>. syntax the <length> data type consists of a <number> followed by one of the units listed below. as with all css dimensions, there is no space between the unit literal and the number. the length unit is optional after the number 0. note: some properties allow negative <length>s, while others do not. units relative length units relative lengths represent a measurement in terms of some other distance. depending on the unit, this can be the size of a sp...
...here 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 element. if used on the font-size property itself, it represents the inherited font-size of the element. ex represents the x-height of the element's font. on fonts with the "x" letter, this is generally the height of lowercase letters in the font; 1ex ≈ 0.5em in many fonts. ic equal to the used advance measure of the "水" (cjk water ideograph, u+6c34) glyph found in the font used to render it. lh equal to the computed value of the line-height property of the element on which it is used, converted to an absolute length. rem represents the font-size of the root element (typically <html>). when used wit...
... axis. vmin equal to the smaller of vw and vh. vmax equal to the larger of vw and vh. absolute length units absolute length units represent a physical measurement when the physical properties of the output medium are known, such as for print layout. this is done by anchoring one of the units to a physical unit, and then defining the others relative to it. the anchor is done differently for low-resolution devices, such as screens, versus high-resolution devices, such as printers. for low-dpi devices, the unit px represents the physical reference pixel; other units are defined relative to it. thus, 1in is defined as 96px, which equals 72pt. the consequence of this definition is that on such devices, dimensions described in inches (in), centimeters (cm), or millimeters (mm) don't necessa...
.... 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"> <div class="input-container"> <label>enter width:</label> <input type="text" id="length"> ...
line-height - CSS: Cascading Style Sheets
nd us a pull request. syntax /* keyword value */ line-height: normal; /* unitless values: use this number multiplied by the element's font size */ line-height: 3.5; /* <length> values */ line-height: 3em; /* <percentage> values */ line-height: 34%; /* global values */ line-height: inherit; line-height: initial; line-height: unset; the line-height property is specified as any one of the following: a <number> a <length> a <percentage> the keyword normal. values normal depends on the user agent. desktop browsers (including firefox) use a default value of roughly 1.2, depending on the element's font-family. <number> (unitless) the used value is this unitless <number> multiplied by the element's own font size. the computed value is the same as the specified <number>. in most ...
...d value is this unitless <number> multiplied by the element's own font size. the computed value is the same as the specified <number>. in most cases, this is the preferred way to set line-height and avoid unexpected results due to inheritance. <length> the specified <length> is used in the calculation of the line box height. values given in em units may 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...
...if the page is zoomed to increase the text size, using a unitless value ensures that the line height will scale proportionately. ...
...inition initial valuenormalapplies toall elements. ...
opacity - CSS: Cascading Style Sheets
Web › CSS › opacity
aces the element in a new stacking context. if you do not want to apply opacity to child elements, 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...
...tsinheritednocomputed valuethe specified value, clipped in the range [0,1]animation typea number formal syntax <alpha-value>where <alpha-value> = <number> | <percentage> examples setting background opacity html <div class="light">you can barely see this.</div> <div class="medium">this is easier to see.</div> <div class="heavy">this is very easy to see.</div> css div { background-color: yellow; } .light { opacity: 0.2; /* barely see the text over the background */ } .medium { opacity: 0.5; /* see the text more clearly over the background */ } .heavy { opacity: 0.9; /* see the text very clearly over the background */ } result setting opacity on hover html <img src="//developer.mozilla.org/static/img/opengraph-logo.png" alt="mdn logo" width="128" height="146" class="opac...
... working draft defines percentage opacity values. css color module level 3the defi...
... working draft defines percentage opacity values. css color module level 3the definition of 'opacity' in that specification. recommenda...
overscroll-behavior-block - CSS: Cascading Style Sheets
or for a full explanation. /* keyword values */ overscroll-behavior-block: auto; /* default */ overscroll-behavior-block: contain; overscroll-behavior-block: none; /* global values */ overscroll-behavior-block: inherit; overscroll-behavior-block: initial; overscroll-behavior-block: unset; syntax the overscroll-behavior-block property is specified as a keyword chosen from the list of values below. values auto the default scroll overflow behavior occurs as normal. contain default scroll overflow behavior is observed inside the element this value is set on (e.g. "bounce" effects or refreshes), but no scroll chaining occurs to neighbouring scrolling areas, e.g. underlying elements will not scroll. none no scroll chaining occurs to neighbouring scrolling areas, and default scroll ove...
... formal definition initial valueautoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax contain | none | auto examples preventing block overscrolling in this demo we have two block-level boxes, one inside the other. ...
... when the inner box is scrolled and a scroll boundary is reached, the whole page will begin to scroll, which is probably not what we want. to avoid this happening in the block direction, we've set overscroll-behavior-block: contain on the inner box. ...
...ke it so that when the scroll boundaries of the yellow inner box are reached, the whole page does not begin to scroll.</p> </div> </div> </main> css main { height: 3000px; width: 500px; background-color: white; background-image: repeating-linear-gradient(to bottom, rgba(0,0,0,0) 0px, rgba(0,0,0,0) 19px, rgba(0,0,0,0.5) 20px); } main > div { height: 300px; width: 400px; overflow: auto; position: relative; top: 50px; left: 50px; overscroll-behavior-block: contain; } div > div { height: 1500px; width: 100%; background-color: yellow; background-image: repeating-linear-gradient(to bottom, rgba(0,0,0,0) 0px, rgba(0,0,0,0) 19px, rgba(0,0,0,0.5) 20px); } p { padding: 10px; background-color: rgba(255,0,0,0.5); margin: 0; width: 340px; position: relati...
overscroll-behavior-inline - CSS: Cascading Style Sheets
a full explanation. /* keyword values */ overscroll-behavior-inline: auto; /* default */ overscroll-behavior-inline: contain; overscroll-behavior-inline: none; /* global values */ overscroll-behavior-inline: inherit; overscroll-behavior-inline: initial; overscroll-behavior-inline: unset; syntax the overscroll-behavior-inline property is specified as a keyword chosen from the list of values below. values auto the default scroll overflow behavior occurs as normal. contain default scroll overflow behavior is observed inside the element this value is set on (e.g. "bounce" effects or refreshes), but no scroll chaining occurs to neighbouring scrolling areas, e.g. underlying elements will not scroll. none no scroll chaining occurs to neighbouring scrolling areas, and default scroll ove...
... formal definition initial valueautoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax contain | none | auto examples preventing inline overscrolling in this demo we have two block-level boxes, one inside the other. ...
...en the inner box is scrolled and a scroll boundary is reached, the whole page will begin to scroll, which is probably not what we want. to avoid this happening in the inline direction, we've set overscroll-behavior-inline: contain on the inner box. ...
...ake it so that when the scroll boundaries of the yellow inner box are reached, the whole page does not begin to scroll.</p> </div> </div> </main> css main { height: 400px; width: 3000px; background-color: white; background-image: repeating-linear-gradient(to right, rgba(0,0,0,0) 0px, rgba(0,0,0,0) 19px, rgba(0,0,0,0.5) 20px); } main > div { height: 300px; width: 400px; overflow: auto; position: relative; top: 50px; left: 50px; overscroll-behavior-inline: contain; } div > div { height: 100%; width: 1500px; background-color: yellow; background-image: repeating-linear-gradient(to right, rgba(0,0,0,0) 0px, rgba(0,0,0,0) 19px, rgba(0,0,0,0.5) 20px); } p { padding: 10px; background-color: rgba(255,0,0,0.5); margin: 0; width: 360px; position: relati...
place-self - CSS: Cascading Style Sheets
the place-self css shorthand property allows you to align an individual item in both the block and inline directions at once (i.e. the align-self and justify-self properties) in a relevant layout system such as grid or flexbox. if the second value is not present, the first value is also used for it. 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. ...
...ut system such as grid or flexbox. if the second value is not present, the first value is also used for it. 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. ...
... end side in the cross axis. flex-start the cross-start margin edge of the flex item is flushed with the cross-start edge of the line. flex-end the cross-end margin edge of the flex item is flushed with the cross-end edge of the line. center the flex item's margin box is centered within the line on the cross-axis. if the cross-size of the item is larger than the flex container, it will overflow equally in both directions. baseline first baseline last baseline specifies participation in first- or last-baseline alignment: aligns the alignment baseline of the box’s first or last baseline set with the corresponding baseline in the shared first or last baseline set of all the boxes in its baseline-sharing group. the fallback alignment for first baseline is start, the one for last base...
...itioned 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 container has justify-items and align-items values of stretch — the defaults — which causes the grid items to stretch across the entire width of their cells. the second, third, and fourth grid items are then given different values of place-self, to show how these override the default placements. these values cause the grid ite...
scroll-margin-inline - CSS: Cascading Style Sheets
the scroll-margin-inline shorthand property sets the scroll margins of an element in the inline dimension. constituent properties this property is a shorthand for the following css properties: scroll-margin-inline-end scroll-margin-inline-start syntax /* <length> values */ scroll-margin-inline: 10px; scroll-margin-inline: 1em .5em ; /* global values */ scroll-margin-inline: inherit; scroll-margin-inline: initial; scroll-margin-inline: unset; values <length> an outset from the corresponding edge of the scroll container. 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-align...
...blocks, the second and third of which snap into place, near but not quite at the right of each block. html the html that represents the blocks is very simple: <div class="scroller"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> </div> css let's walk through the css. ...
...roller"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> </div> css let's walk through the css. ...
... border: 1px solid #000; scroll-snap-type: x mandatory; } the main parts relevant to the scroll snapping are overflow-x: scroll, which makes sure the contents will scroll and not be hidden, and scroll-snap-type: x mandatory, which dictates that scroll snapping must occur along the horizontal axis, and the scrolling will always come to rest on a snap point. ...
scroll-margin - CSS: Cascading Style Sheets
rgins of an element at once, assigning values much like the margin property does for margins of an 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. constituent properties this property is a shorthand for the following css properties: scroll-margin-bottom scroll-margin-left scroll-margin-right scroll-margin-top syntax /* <length> values */ scroll-margin: 10px; scroll-margin: 1em .5em 1em 1em; /* global values */ scroll-margin: inherit; scroll-margin: initial; scroll-margin: unset; values <length> an outset from the corresponding edge of the scroll container. description you can see the eff...
... blocks, the second and third of which snap into place, near but not quite at the left of each block. html the html that represents the blocks is very simple: <div class="scroller"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> </div> css let's walk through the css. ...
...roller"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> </div> css let's walk through the css. ...
... border: 1px solid #000; scroll-snap-type: x mandatory; } the main parts relevant to the scroll snapping are overflow-x: scroll, which makes sure the contents will scroll and not be hidden, and scroll-snap-type: x mandatory, which dictates that scroll snapping must occur along the horizontal axis, and the scrolling will always come to rest on a snap point. ...
scrollbar-width - CSS: Cascading Style Sheets
thin a thin scrollbar width variant on platforms that provide that option, or a thinner scrollbar than the default platform scrollbar width. ...
...tial valueautoapplies toscrolling boxesinheritednocomputed valueas specifiedanimation typediscrete syntax /* keyword values */ scrollbar-width: auto; scrollbar-width: thin; scrollbar-width: none; /* global values */ scrollbar-width: inherit; scrollbar-width: initial; scrollbar-width: unset; values <scrollbar-width> defines the width of the scrollbar as a keyword. it must be one of the following values: auto the default scrollbar width for the platform. thin a thin scrollbar width variant on platforms that provide that option, or a thinner scrollbar than the default platform scrollbar width. none no scrollbar shown, however the element will still be scrollable. note: user agents must apply any scrollbar-width value set on t...
...gumbo beet greens corn soko endive gumbo gourd. parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandel...
...gumbo beet greens corn soko endive gumbo gourd. parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. dandelion cucumber earthnut pea peanut soko zucch...
<time-percentage> - CSS: Cascading Style Sheets
the <time-percentage> css data type represents a value that can be either a <time> or a <percentage>. syntax refer to the documentation for <time> and <percentage> for details of the individual syntaxes allowed by this type. examples use in calc() where a <time-percentage> is specified as an allowable type, this means that the percentage resolves to a time and therefore can be used in a calc() expression. ...
...allowed by this type. examples use in calc() where a <time-percentage> is specified as an allowable type, this means that the percentage resolves to a time and therefore can be used in a calc() expression. valid percentages 50% +50% optional plus sign -50% negative percentages are not valid for all properties that accept percentages invalid percentages 50 % space not allowed between the space and the percentage sign valid times 12s positive integer -456ms negative integer 4.3ms non-integer 14ms the unit is case-insensitive, although capital letters are not recommended. ...
... specifications specification status comment css values and units module level 4the definition of '<time-percentage>' in that specification. ...
... non-integer 14ms the unit is case-insensitive, although capital letters are not recommended. +0s zero with a leading + and a unit -0ms zero with a leading - and a unit invalid times 0 although unitless zero is allowed for <length>s, it's invalid for <time>s. 12.0 this is a <number>, not a <time>, because it's missing a unit. 7 ms no space is allowed between the number and the unit. specifications specification status comment css values and units module level 4the definition of '<time-percentage>' in that specification. editor's draft css values and units module level 3the definition of '<time-percentage>' in that specification. candidate recommendation defines <time-percentage>. adds cal...
matrix3d() - CSS: Cascading Style Sheets
...
...s an animated combined translate and scale. html <div class="foo"> lorem ipsum dolor sit amet, consectetur adipisicing elit. ...
...foo { width: 50%; padding: 1em; color: white; background: #ff8c66; border: 2px dashed black; text-align: center; font-family: system-ui, sans-serif; font-size: 14px; /* setting up animation for better demonstration */ animation: motionscale 2s alternate linear infinite; } @keyframes motionscale { from { /* identity matrix is used as basis here. ...
...ng: 1em; color: white; background: #ff8c66; border: 2px dashed black; text-align: center; font-family: system-ui, sans-serif; font-size: 14px; /* setting up animation for better demonstration */ animation: motionscale 2s alternate linear infinite; } @keyframes motionscale { from { /* identity matrix is used as basis here. ...
transition-delay - CSS: Cascading Style Sheets
ze 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: 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; t...
...t-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 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; tran...
...t-size left top color; -webkit-transition-duration:2s; -webkit-transition-delay:2s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:2s; 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:2s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; tran...
...t top color; -webkit-transition-duration:2s; -webkit-transition-delay:4s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:4s; transition-timing-function: ease-in-out; } .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:4s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top color; transition-duration:2s; ...
transition-duration - CSS: Cascading Style Sheets
: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: 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; t...
...it-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; position:absolute; -webkit-transition-property: width height background-color font-size left top -webkit-transform transform color; -webkit-transition-duration:1s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; tran...
...tion:2s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration:2s; 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; position:absolute; -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration:2s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; tran...
...tion:4s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration:4s; 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; position:absolute; -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration:4s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; tran...
vertical-align - CSS: Cascading Style Sheets
cal-align: text-top; vertical-align: text-bottom; vertical-align: middle; vertical-align: top; vertical-align: bottom; /* <length> values */ vertical-align: 10em; vertical-align: 4px; /* <percentage> values */ vertical-align: 20%; /* global values */ vertical-align: inherit; vertical-align: initial; vertical-align: unset; the vertical-align property is specified as one of the values listed below. values for inline elements parent-relative values these values vertically align the element relative to its parent element: baseline aligns the baseline of the element with the baseline of its parent. the baseline of some replaced elements, like <textarea>, is not specified by the html specification, meaning that their behavior with this keyword may vary between browsers. sub aligns the...
...t. text-top aligns the top of the element with the top of the parent element's font. text-bottom aligns the bottom of the element with the bottom of the parent element's font. middle aligns the middle of the element with the baseline plus half the x-height of the parent. <length> aligns the baseline of the element to the given length above the baseline of its parent. a negative value is allowed. <percentage> aligns the baseline of the element to the given percentage above the baseline of its parent, with the value being a percentage of the line-height property. a negative value is allowed. line-relative values the following values vertically align the element relative to the entire line: top aligns the top of the element and its descendants with the top of the entire line. b...
...per, text-top, text-bottom, <length>, and <percentage>) aligns the baseline of the cell with the baseline of all other cells in the row that are baseline-aligned. top aligns the top padding edge of the cell with the top of the row. middle centers the padding box of the cell within the row. bottom aligns the bottom padding edge of the cell with the bottom of the row. negative values are allowed. formal definition initial valuebaselineapplies toinline-level and table-cell elements. it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the line-height of the element itselfcomputed valuefor percentage and length values, the absolute length, otherwise the keyword as specifiedanimation typea length formal syntax baseline | sub | super | text-top | text-botto...
... css level 1the definition of 'vertical-align' in that specification. recommendation initial definition. ...
will-change - CSS: Cascading Style Sheets
inherit; will-change: initial; will-change: unset; proper usage of this property can be a bit tricky: don't apply will-change to too many elements. the browser already tries as hard as it can to optimize everything. some of the stronger optimizations that are likely to be tied to will-change end up using a lot of a machine’s resources, and when overused like this can cause the page to slow down or consume a lot of resources. use sparingly. the normal behavior for optimizations that the browser make is to remove the optimizations as soon as it can and revert back to normal. but adding will-change directly in 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 ...
...ay actually influence the visual appearance of elements, when used with property values, that create a stacking context (e.g. will-change: opacity), as the stacking context is created up front. syntax values auto this keyword expresses no particular intent; the user agent should apply whatever heuristics and optimizations it normally does. the <animateable-feature> can be one of the following values: scroll-position indicates that the author expects to animate or change the scroll position of the element in the near future. contents indicates that the author expects to animate or change something about the element’s contents in the near future. <custom-ident> indicates that the author expects to animate or change the property with the given name on the element in the near...
... indicates that the author expects to animate or change something about the element’s contents in the near future. <custom-ident> indicates that the author expects to animate or change the property with the given name on the element in the near future. if the property given is a shorthand, it indicates the expectation for all the longhands the shorthand expands to. it cannot be one of the following values: unset, initial, inherit, will-change, auto, scroll-position, or contents. the spec doesn't define the behavior of particular value, but it is common for transform to be a compositing layer hint. chrome currently takes two actions, given particular css property idents: establish a new compositing layer or a new stacking context. via stylesheet it may be appropriate to include will-ch...
...es two actions, given particular css property idents: establish a new compositing layer or a new stacking context. via stylesheet it may be appropriate to include will-change in your style sheet for an application that does page flips on key presses like an album or a slide deck presentation where the pages are large and complex. this will let browser prepare the transition ahead of time and allow for snappy transitions between the pages as soon as the key is pressed. but use caution with the will-change property directly in stylesheets. it may cause the browser to keep the optimization in memory for much longer than it is needed. .slide { will-change: transform; } formal definition initial valueautoapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete for...
WAI ARIA Live Regions/API Support - Developer guides
le object about to go away) object shown or inserted children_changed::add (fired on the parent, with event data pointing to the child index of the inserted accessible object) event_object_show* (fired on the actual new accessible object) object replaced with different object (this happens especially if an object's interfaces or role changes) children_changed::remove followed immediately by children_change::add event_object_hide followed immediately by event_object_show text removed text_changed::delete ia2_event_text_removed (use iaccessibletext::get_oldtext to retrieve the offsets and removed text) text inserted text_changed::insert ia2_event_text_inserted (use iaccessibletext::get_newtext to retrieve the offsets and inserted text)...
...ect_hide followed immediately by event_object_show text removed text_changed::delete ia2_event_text_removed (use iaccessibletext::get_oldtext to retrieve the offsets and removed text) text inserted text_changed::insert ia2_event_text_inserted (use iaccessibletext::get_newtext to retrieve the offsets and inserted text) text replaced text_changed::delete followed immediately by text_changed::insert ia2_event_text_removed followed immediately by ia2_event_text_inserted * we do not use msaa's create/destroy at the request of screen reader vendors, who avoid those events because they cause crashes on some important system -- show/hide are the equivalent of those events. retrieving author-supplied aria live region semantics from an event for any mu...
...t_text_removed followed immediately by ia2_event_text_inserted * we do not use msaa's create/destroy at the request of screen reader vendors, who avoid those events because they cause crashes on some important system -- show/hide are the equivalent of those events. ...
...f container-atomic=true, points to an ancestor accessible object (thus it is actually an accessible relation, not object attribute) not in atomic region if not provided points to the root of the atomic container that this object is in. this will always be an ancestor of the current object. aria-atomic on ancestor element event-from-input "true" | "false" (described more below) browser could not calculate this was the root cause of this event explicit user input? does not require author's cooperation. the "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...
Setting up adaptive streaming media sources - Developer guides
let's say you want to set up an adaptive streaming media source on a server, to be consumed inside an html5 media element. how would you do that? this article explains how, looking at two of the most common formats: mpeg-dash and hls (http live streaming.) choosing formats in terms of adaptive streaming formats, there are many to choose from; we decided to choose the following two as between them we can support most modern browsers. mpeg-dash hls (http live streaming) in order to adaptively stream media we need to split the media up into chunks. we are required to provide several different quality files split up over several time points. the more qualities and time points there are, the more 'adaptive' your stream will be, but we will usually want to find a pragmatic balance...
...aming, the live profile is a requirement. the stream switching capabilities are identical between the profiles. ...
... dash and other forms of delivery (such as microsoft smooth streaming) as a transition strategy you can use the same media files for both live transmission and vod at a later stage *sidx or segmentindexbox is a structure describing a segment by giving its earliest presentation time and other meta-data and can often make up a large portion of the mpd file. ondemand profile this profile will allow switching between streams 'on demand' - that is to say that you only need provide a set of contiguous files and specify the bandwidth for each one and the appropriate file will be chosen automatically. here's a simple example that provides an audio track representation and four separate video representations. <?xml version="1.0" encoding="utf-8"?> <mpd xmlns:xsi="http://www.w3.org/2001/xmlschem...
...tream segmenter. note: you can find more details about these tools at using http live streaming. index files (playlists) the hls index file (much like mpeg-dash's .mpd file) contains the information on where all the media segments reside, as well as other meta data such as bandwidth application. apple uses the .m3u8 format (an extension of its .m3u playlist format) for index files — see below for an example: #ext-x-version:3 #extm3u #ext-x-targetduration:10 #ext-x-media-sequence:1 # old-style integer duration; avoid for newer clients. #extinf:10, http://media.example.com/segment0.ts # new-style floating-point duration; use for modern clients. #extinf:10.0, http://media.example.com/segment1.ts #extinf:9.5, http://media.example.com/segment2.ts #ext-x-endlist note: comprehensive inf...
HTML5 Parser - Developer guides
Web › Guide › HTML › HTML5 › HTML5 Parser
if you previously tested your code in ie and opera, then you probably don't have any tags like this. if you tested your site only with gecko 1.x or webkit (for example, 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, ...
... comment was not closed, it would look for the first '>'. this behavior created a security vulnerability. if an attacker could force a premature end-of-file, the parser might change which parts of the document it considered to be executable scripts. in addition, supporting reparsing led to unnecessarily complex parsing code. with html5, parsers no longer reparse documents. this change has the following consequences for web developers: if you omit the closing tag for <title>, <style>, <textarea>, or <xmp>, the page will fail to be parsed. ie already fails to parse documents with a missing </title> tag, so if you test with ie, you probably don't have that problem. if you forget to close a comment, the page will most likely fail to be parsed. however, unclosed comments often already break i...
...the same document.write() call, as long as they are within the same <script> tag. please note that you shouldn't use end tags for void elements that don't have end tags: <area>, <base>, <br>, <col>, <command>, <embed>, <hr>, <img>, <input>, <keygen>, <link>, <meta>, <param>, <source> and <wbr>. ...
...gs: <area>, <base>, <br>, <col>, <command>, <embed>, <hr>, <img>, <input>, <keygen>, <link>, <meta>, <param>, <source> and <wbr>. (there are also some element whose end tags can be omitted in some cases, such as <p> in the example below, but it's simpler to always use end tags for those elements than to make sure that the end tags are only omitted when they aren't necessary.) for example, the following code writes a balanced sub-tree: <script> document.write("<div>"); document.write("<p>some content goes here.</p>"); document.write("</div>"); </script> <!-- non-script html goes here. --> in contrast, the following code contains two scripts with unbalanced sub-trees, which causes speculative parsing to fail and therefore the time to parse the document is longer. <script>document.wri...
Writing forward-compatible websites - Developer guides
this page explains how to write websites that do not break when new browser versions are released. this is especially important for intranets and other non-public websites; if we can't see your code, we can't see that it broke. it's not always possible to follow all of these, but following as many of them as possible will help future-proof your website. javascript prefix all global variable access in onfoo attributes with “window.” when an event handler content attribute (onclick, onmouseover, and so forth) is used on html element, all name lookup in the attribute first happens on the element itself, then on the element's form if the element is a form control, then on the document, and then on the window (where the global variables you have defined are). for example, if you ...
...onclick="window.localname()">clicking me should show an alert<div> don't concatenate scripts you don't control the "use strict;" directive in ecmascript, when used on the file level, applies to everything in the file. so appending a script that depends on non-strict-mode behavior to a strict-mode script will cause things to break. ask the authors of any javascript libraries you use to also follow these guidelines suggest to the developers of your favorite libraries that they follow these guidelines too. if they don't, you can't rely on that library not breaking in the future. unfortunately, libraries are common transgressors of these guidelines. sniffing sniff for specific features if you plan to use some feature, use object-detection to sniff for that exact feature, if possible. as ...
... detection or ua sniffing if one of the codepaths involved actually works in all browsers. there is a good chance of browsers changing behavior to converge with each other and hence breaking the site for those you've sent down one or more of the alternative paths. testing test with all major engines test your code at least in firefox, chrome, safari, opera, and internet explorer. if you are following the advice given above so that you have a single code path for all current and unknown browsers, testing that this single code path works in all the major engines makes it extremely probable that your code won't break in the future. sometimes browsers implement a given feature slightly differently. if you have a single code path that works in all the top engines, it means that you are either ...
...if no browser actually supports it. you can't assume that the syntax of the final version will be the same as the syntax of any of the prefixed versions. code hygiene avoid missing > passing a validator is one way to ensure this, but even if your website doesn't validate entirely you should make sure all your > characters are present. missing those can lead to unexpected situations due to a following tag name being treated as an attribute on a previous tag. this can work for a bit, then break if a specification attaches a meaning to that attribute. here's an example that works in browsers without html5 support but breaks in a browser supporting html5: <form action="http://www.example.com"> <input type="submit" value="submit the form" </form> due to the missing > on the input tag. don...
HTML attribute: max - HTML: Hypertext Markup Language
Web › HTML › Attributes › max
ceptable 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. ...
...he maximum allowed by the max attribute, constraint validation will prevent form submission. valid for the numeric input types, including the date, month, week, time, datetime-local, number and range types, and both the <progress> and <meter> elements, the max attribute is a number that specifies the most positive value a form control to be considered valid. if the value exceeds the max value allowed, the validitystate.rangeoverflow will be true, and the the control will be matched by the :out-of-range and :invalid pseudo-classes. syntax syntax for max values by input type input 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-...
... 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. this must be greater than the minimum value (min attribute), if speci...
...d of the measured range. ...
<applet>: The Embed Java Applet element - HTML: Hypertext Markup Language
Web › HTML › Element › applet
plet> element was removed in gecko 56 and chrome 47. removal is being considered in webkit and edge. the obsolete html applet element (<applet>) embeds a java applet into the document; this element has been deprecated in favor of <object>. use of java applets on the web is deprecated; most browsers no longer support use of plug-ins, including the java plug-in. content categories flow content, phrasing content, embedded content, interactive content, palpable content. permitted content zero or more <param> elements, then transparent. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts embedded content. dom interface htmlappletelement attributes align this attribu...
...ntent. permitted content zero or more <param> elements, then transparent. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts embedded content. dom interface htmlappletelement attributes align this attribute is used to position the applet on the page relative to content that might flow around it. the html 4.01 specification defines values of bottom, left, middle, right, and top, whereas microsoft and netscape also might support absbottom, absmiddle, baseline, center, and texttop. alt this attribute causes a descriptive text alternate to be displayed on browsers that do not support java. page designers should also remember that content enclosed within the <applet> element may ...
...r 4. it indicates the id of the data source object that supplies the data that is bound to the <param> elements associated with the applet. height this attribute specifies the height, in pixels, that the applet needs. hspace this attribute specifies additional horizontal space, in pixels, to be reserved on either side of the applet. mayscript in the netscape implementation, this attribute allows access to an applet by programs in a scripting language embedded in the document. name this attribute assigns a name to the applet so that it can be identified by other resources; particularly scripts. object this attribute specifies the url of a serialized representation of an applet. src as defined for internet explorer 4 and higher, this attribute specifies a url for an associated file ...
...s; particularly scripts. object this attribute specifies the url of a serialized representation of an applet. src as defined for internet explorer 4 and higher, this attribute specifies a url for an associated file for the applet. the meaning and use is unclear and not part of the html standard. vspace this attribute specifies additional vertical space, in pixels, to be reserved above and below the applet. width this attribute specifies in pixels the width that the applet needs. example html <applet code="game.class" align="left" archive="game.zip" height="250" width="350"> <param name="difficulty" value="easy"> <b>sorry, you need java to play this game.</b> </applet> specifications specification status comment html 5.2the definition of '<apple...
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
Web › HTML › Element › canvas
permitted content transparent but with no interactive content descendants except for <a> elements, <button> elements, <input> elements whose type attribute is checkbox, radio, or button. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. ...
...ing to fit the styled size, which can make the final graphics rendering end up being distorted. it is better to specify your canvas dimensions by setting the width and height attributes directly on the <canvas> elements, either directly in the html or by using javascript. maximum canvas size the maximum size of a <canvas> element is very large, but the exact size depends on the browser. ...
...rted. it is better to specify your canvas dimensions by setting the width and height attributes directly on the <canvas> elements, either directly in the html or by using javascript. maximum canvas size the maximum size of a <canvas> element is very large, but the exact size depends on the browser. the following is some data we've collected from various tests and other sources (e.g. ...
...anvas.getcontext('2d'); ctx.fillstyle = 'green'; ctx.fillrect(10, 10, 100, 100); result accessibility concerns alternative content the <canvas> element on its own is just a bitmap and does not provide information about any drawn objects. canvas content is not exposed to accessibility tools as semantic html is. in general, you should avoid using canvas in an accessible website or app. the following guides can help to make it more accessible. mdn hit regions and accessability canvas accessibility use cases canvas element accessibility issues html5 canvas accessibility in firefox 13 – by steve faulkner best practices for interactive canvas elements specifications specification status comment html living standardthe definition of '<canvas>' in that sp...
<dfn>: The Definition element - HTML: Hypertext Markup Language
Web › HTML › Element › dfn
the <dt>/<dd> pairing, or the <section> element which is the nearest ancestor of the <dfn> is considered to be the definition of the term. 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, but no <dfn> element must be a descendant. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. implicit aria role term permitted aria roles any dom interface htmlelement ...
... tag omission none, both the starting and ending tag are mandatory. permitted parents 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 a...
...ing <abbr>) or another form of the term. if the <dfn> contains a single child element and does not have any text content of its own, and the child element is an <abbr> element with a title attribute itself, then the exact value of the <abbr> element's title is the term being defined. otherwise, the text content of the <dfn> element is the term being defined. this is shown in the first example below. if the <dfn> element has a title attribute, it must contain the term being defined and no other text. links to <dfn> elements if you include an id attribute on the <dfn> element, you can then link to it using <a> elements. such links should be uses of the term, with the intent being that the reader can quickly navigate to the term's definition if they're not already aware of it, by clickin...
...efined and no other text. links to <dfn> elements if you include an id attribute on the <dfn> element, you can then link to it using <a> elements. such links should be uses of the term, with the intent being that the reader can quickly navigate to the term's definition if they're not already aware of it, by clicking on the term's link. this is shown in the example under links to definitions below. examples let's take a look at some examples of various usage scenarios. basic identification of a term this example simply uses a plain <dfn> element to identify the location of a term within the definition. html <p>the <strong>html definition element</strong> (<strong><dfn>&lt;dfn&gt;</dfn></strong>) is used to indicate the term being defined within the context of a definition phrase or s...
<hgroup> - HTML: Hypertext Markup Language
Web › HTML › Element › hgroup
the html <hgroup> element represents a multi-level heading for a section of a document. it groups a set of <h1>–<h6> elements. 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, heading content, palpable content. permitted content one or more <h1>, <h2>, <h3>, <h4>, <h5>, and/or <h6>. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement ...
...o affect how headings are displayed by the outline algorithm defined in the html specification—but the html outline algorithm is not implemented in any browsers—then the <hgroup> semantics are in practice only theoretical. so the html5 (w3c) specification provides advice on how to mark up subheadings, subtitles, alternative titles and taglines without using <hgroup>. the <hgroup> element allows the primary heading for a document section to be grouped with any secondary headings—such as subheadings or alternative titles—to form a multi-level heading. in other words, the <hgroup> element prevents any of its secondary <h1>–<h6> children from creating separate sections of their own in the outline—as those <h1>–<h6> elements otherwise normally would if they were not children of a...
...might be shown in a rendered outline; for example: an <hgroup> might be shown in a rendered outline in with a colon character and space (“: ”) or other such punctuation after the primary heading and before the first secondary heading (and with the same or similar punctuation before any other secondary headings an <hgroup> might be shown in a rendered outline in with the primary heading followed by parentheses around the secondary heading(s) consider the following html document: <!doctype html> <title>html standard</title> <body> <hgroup id="document-title"> <h1>html</h1> <h2>living standard — last updated 12 august 2016</h2> </hgroup> <p>some intro to the document.</p> <h2>table of contents</h2> <ol id=toc>...</ol> <h2>first section</h2> <p>some intro to the...
... <!doctype html> <title>html standard</title> <body> <hgroup id="document-title"> <h1>html</h1> <h2>living standard — last updated 12 august 2016</h2> </hgroup> <p>some intro to the document.</p> <h2>table of contents</h2> <ol id=toc>...</ol> <h2>first section</h2> <p>some intro to the first section.</p> </body> a rendered outline for that document might look like the following: that is, the rendered outline might show the primary title, html, followed by a colon and space, followed by the secondary title, living standard — last updated 12 august 2016. or, the rendered outline for that document might instead look like the following: that is, the rendered outline might show the primary title, html, followed by the secondary title shown in parentheses: (living...
<input type="button"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › button
have no default behavior (their cousins, <input type="submit"> and <input type="reset"> are used to submit and reset forms, respectively). to make buttons do anything, you have to write javascript code to do the work. ...
...eout(function() { button.disabled = false; button.value = 'enabled'; }, 2000); } if the disabled attribute isn't specified, the button inherits its disabled state from its parent element. this makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a <fieldset> element, and then setting disabled on the container. the example below shows this in action. this is very similar to the previous example, except that the disabled attribute is set on the <fieldset> when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed. hidden code 2 <fieldset> <legend>button group</legend> <input type="button" value="button 1"> <input type="button" value="button 2"> <inp...
...led = true; window.settimeout(function() { fieldset.disabled = false; }, 2000); } note: firefox will, unlike other browsers, by default, persist the dynamic disabled state of a <button> across page loads. use the autocomplete attribute to control this feature. validation buttons don't participate in constraint validation; they have no real value to be constrained. examples the below example shows a very simple drawing app created using a <canvas> element and some simple css and javascript (we'll hide the css for brevity). 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. <div class="toolbar"> <input type="color" aria-label="select pen color"> <input type="range" min="2" ma...
...kes a function that clears the canvas. ...
<input type="hidden"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › hidden
<input> elements of type hidden let web developers include data that cannot be seen or modified by users when a form is submitted. for example, the id of the content that is currently being ordered or edited, or a unique security token. hidden inputs are completely invisible in the rendered page, and there is no way to make it visible in the page's content. note: there is a live example below the following line of code — if it is working correctly, you should see nothing! <input id="prodid" name="prodid" type="hidden" value="xm234jq"> value a domstring representing the value of the hidden data you want to pass back to the server. events none. supported common attributes autocomplete idl attributes value methods none. ...
...could edit the value via browser developer tools. important: while the value isn't displayed to the user in the page's content, it is visible—and can be edited—using any browser's developer tools or "view source" functionality. do not rely on hidden inputs as a form of security. additional attributes in addition to the attributes common to all <input> elements, hidden inputs offer the following attributes: attribute description name like all input types, the name of the input to report when submitting the form; the special value _charset_ causes the hidden input's value to be reported as the character encoding used to submit the form name this is actually one of the common attributes, but it has a special meaning available for hidden inputs. norma...
...as mentioned above, hidden inputs can be used anywhere that you want to include data the user can't see or edit along with the form when it's submitted to the server. let's look at some examples that illustrate its use. tracking edited content one of the most common uses for hidden inputs is to keep track of what database record needs to be updated when an edit form is submitted. a typical workflow looks like this: user decides to edit some content they have control over, such as a blog post, or a product entry. they get started by pressing the edit button. the content to be edited is taken from the database and loaded into an html form to allow the user to make changes. after editing, the user submits the form, and the updated data is sent back to the server to be updated in the datab...
...here is that during step 2, the id of the record being updated is kept in a hidden input. when the form is submitted in step 3, the id is automatically sent back to the server with the record content. the id lets the site's server-side component know exactly which record needs to be updated with the submitted data. you can see a full example of what this might look like in the examples section below. improving website security hidden inputs are also used to store and submit security tokens or secrets, for the purposes of improving website security. the basic idea is that if a user is filling in a sensitive form, such as a form on their banking website to transfer some money to another account, the secret they would be provided with would prove that they are who they say they are, and that ...
<input type="radio"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › radio
ighted when selected. 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. they are called radio buttons because they look and operate in a similar manner to the push buttons on old-fashioned radios, such as the one shown below. note: checkboxes are similar to radio buttons, but with an important distinction: radio buttons are designed for selecting one value out of a set, whereas checkboxes let you turn individual 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 represen...
...enario, if the user clicked on the "phone" option and submitted the form, the resulting form data would be contact=on, which isn't helpful. so don't forget to set your value attributes! note: if no radio button is selected when the form is submitted, the 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 preferre...
...data(form); var output = ""; for (const entry of data) { output = output + entry[0] + "=" + entry[1] + "\r"; }; log.innertext = output; event.preventdefault(); }, false); try this example out and see how there's never more than one result for the contact group. ...
...lly useful feature of html form labels that makes it easier for users to click the option they want, especially on small-screen devices like smartphones. beyond accessibility, this is another good reason to properly set up <label> elements on your forms. validation radio buttons don't participate in constraint validation; they have no real value to be constrained. styling radio inputs the following example shows a slightly more thorough version of the example we've seen throughout the article, with some additional styling, and with better semantics established through use of specialized elements. the html looks like this: <form> <fieldset> <legend>please select your preferred contact method:</legend> <div> <input type="radio" id="contactchoice1" name="contact" val...
<keygen> - HTML: Hypertext Markup Language
Web › HTML › Element › keygen
on of key material, and submission of the public key as part of an html form. this mechanism is designed for use with web-based certificate management systems. it is expected that the <keygen> element will be used in an html form along with other information needed to construct a certificate request, and that the result of the process will be a signed certificate. content categories flow content, phrasing content, interactive content, listed, labelable, submittable, resettable form-associated element, palpable content. permitted content none, it is an empty element. tag omission must have a start tag and must not have an end tag. permitted parents any element that accepts phrasing content. permitted aria roles none dom inte...
...ame document. if this attribute is not specified, this element must be a descendant of a <form> element. this attribute enables you to place <keygen> elements anywhere within a document, not just as descendants of their form elements. keytype the type of key generated. the default value is rsa. name the name of the control, which is submitted with the form data. the element is written as follows: <keygen name="name" challenge="challenge string" keytype="type" keyparams="pqg-params"> the keytype parameter is used to specify what type of key is to be generated. valid values are "rsa", which is the default, "dsa" and "ec". the name and challenge attributes are required in all cases. the keytype attribute is optional for rsa key generation and required for dsa and ec key generatio...
...y strengths. currently, the user is given a choice between "high" strength (2048 bits) and "medium" strength (1024 bits). for dsa keys, the keyparams parameter specifies the dsa pqg parameters which are to be used in the keygen process. the value of the pqg parameter is the the base64 encoded, der encoded dss-parms as specified in ietf rfc 3279. the user may be given a choice of dsa key sizes, allowing the user to choose one of the sizes defined in the dsa standard. for ec keys, the keyparams parameter specifies the name of the elliptic curve on which the key will be generated. it is normally a string from the table in nskeygenhandler.cpp. (note that only a subset of the curves named there may actually be supported in any particular browser.) if the keyparams parameter string is not a recog...
...ams parameter specifies the name of the elliptic curve on which the key will be generated. it is normally a string from the table in nskeygenhandler.cpp. (note that only a subset of the curves named there may actually be supported in any particular browser.) if the keyparams parameter string is not a recognized curve name string, then a curve is chosen according to the user's chosen key strength (low, medium, high), using the curve named "secp384r1" for high, and the curve named "secp256r1" for medium keys. (note: choice of the number of key strengths, default values for each strength, and the ui by which the user is offered a choice, are outside of the scope of this specification.) the <keygen> element is only valid within an html form. it will cause some sort of selection to be presented t...
<li> - HTML: Hypertext Markup Language
Web › HTML › Element › li
d lists, they are usually displayed with an ascending counter on the left, such as a number or letter. 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 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 p...
...hen 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 indicates the current ordinal value of the list item as defined by the <ol> element. the only allowed value for this attribute is a number, even if the list is displayed with roman numerals or letters. list items that follow this one continue numbering from the value set. the value attribute has no meaning for unordered lists (<ul>) or for menus (<menu>). note: this attribute was deprecated in html4, but reintroduced in html5. type this character attribute indicates the numbering type: ...
... note: this attribute has been deprecated; use the css list-style-type property instead. ...
... note: this attribute has been deprecated; use the css list-style-type property instead. examples for more detailed examples, see the <ol> and <ul> pages. ...
<menu> - HTML: Hypertext Markup Language
Web › HTML › Element › menu
the html <menu> element represents a group of commands that a user can perform or activate. this includes both list menus, which might appear across the top of a screen, as well as context menus, such as those that might appear underneath a button after it has been clicked. content categories flow content. if the element's children include at least one <li> element: palpable content. permitted content if the element is in the list menu state: flow content, or alternatively, zero or more occurrences of <li>, <script>, and <template>. (list menu is the default state, unless the parent element is a <menu> in the context menu state.) if the element is in the context menu state: zero or more occurrences, in any order, of <menu> (context menu state onl...
...u is the default state, unless the parent element is a <menu> in the context menu state.) if the element is in the context menu state: zero or more occurrences, in any order, of <menu> (context menu state only), <menuitem>, <hr>, <script>, and <template>. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. implicit aria role list permitted aria roles directory, group, listbox, menu, menubar, none, presentation, radiogroup, tablist, toolbar or tree dom interface htmlmenuelement attributes this element includes the global attributes. label the name of the menu as shown to the user. used within nested menus, to provide a label through which th...
...context menu for an element with a contextmenu attribute. this value is the default if the attribute is missing and the parent element is also a <menu> element. toolbar: indicates the toolbar state, which represents a toolbar consisting of a series of commands for user interaction. this might be in the form of an unordered list of <li> elements, or, if the element has no <li> element children, flow content describing available commands. this value is the default if the attribute is missing. usage notes the <menu> and <ul> elements both represent an unordered list of items. the key difference is that <ul> primarily contains items for display, whilst <menu> is intended for interactive items, to act on. an html menu can be used to create context menus (typically activated by right-clic...
...om using either the associated element's contextmenu attribute or, for button-activated menus attached to <button> elements, the menu attribute. toolbar menus consist of a <menu> element whose content is described in one of two ways: either as an unordered list of items represented by <li> elements (each representing a command or option the user can utilize), or (if there are no <li> elements), flow content describing the available commands and options. this element was deprecated in html4, but reintroduced in html5.1 and the html living standard. this document describes the current firefox implementation. type 'list' is likely to change to 'toolbar' according to html5.1. examples context menu html <!-- a <div> element with a context menu --> <div contextmenu="popup-menu"> right-cl...
<ol>: The Ordered List element - HTML: Hypertext Markup Language
Web › HTML › Element › ol
the html <ol> element represents an ordered list of items — typically rendered as a numbered list. 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, and if the <ol> element's children include at least one <li> element, palpable content. permitted content zero or more <li>, <script> and <template> elements. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. implicit aria role list permitted aria roles directory, group, listbox, menu, menuba...
... implicit aria role list permitted aria roles directory, group, listbox, menu, menubar, none, presentation, radiogroup, tablist, toolbar, tree dom interface htmlolistelement attributes this element also accepts the global attributes. reversed this boolean attribute specifies that the list’s items are in reverse order. items will be numbered from high to low. ...
...fies that the list’s items are in reverse order. items will be numbered from high to low. start an integer to start counting from for the list items. always an arabic numeral (1, 2, 3, etc.), even when the numbering type is letters or roman numerals. for example, to start numbering elements from the letter "d" or the roman numeral "iv," use start="4". type sets the numbering type: a for lowercase letters a for uppercase letters i for lowercase roman numerals i for uppercase roman numerals 1 for numbers (default) the specified type is used for the entire list unless a different type attribute is used on an enclosed <li> element. note: unless the type of the list number matters (like legal or technical documents where items are referenced by their number/letter), use t...
...--> <ol> <li>second item first subitem</li> <li>second item second subitem</li> <li>second item third subitem</li> </ol> </li> <!-- here's the closing </li> tag --> <li>third item</li> </ol> the above htm...
<pre>: The Preformatted Text element - HTML: Hypertext Markup Language
Web › HTML › Element › pre
file. the text is typically rendered using a non-proportional ("monospace") font. whitespace inside this element is displayed as written. 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, palpable content. permitted content phrasing content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. implicit aria role no corresponding role permitted aria roles any dom interface htmlpreelement attributes this element only includes...
...ains the preferred count of characters that a line should have. it was a non-standard synonym of width. to achieve such an effect, use css width instead. width contains the preferred count of characters that a line should have. though technically still implemented, this attribute has no visual effect; to achieve such an effect, use css width instead. wrap is a hint indicating how the overflow must happen. in modern browser this hint is ignored and no visual effect results in its present; to achieve such an effect, use css white-space instead. example html <p>using css to change the font color is easy.</p> <pre> body { color: red; } </pre> result accessibility concerns it is important to provide an alternate description for any images or diagrams created using preformatted ...
..., use css white-space instead. example html <p>using css to change the font color is easy.</p> <pre> body { color: red; } </pre> result accessibility concerns it is important to provide an alternate description for any images or diagrams created using preformatted text. the alternate description should clearly and concisely describe the image or diagram's content. ...
... example <figure role="img" aria-labelledby="cow-caption"> <pre> ___________________________ < i'm an expert in my field. ...
<select>: The HTML Select element - HTML: Hypertext Markup Language
Web › HTML › Element › select
ions on a desktop computer, there are a number of ways to select multiple options in a <select> element with a multiple attribute: mouse users can hold the ctrl, command, or shift keys (depending on what makes sense for your operating system) and then click multiple options to select/deselect them. warning: the mechanism for selecting multiple non-contiguous items via the keyboard described below currently only seems to work in firefox. also note: on macos, the ctrl + up and ctrl + down shortcuts conflict with the os default shortcuts for mission control and application windows, so you'll have to turn these off before it will work. keyboard users can select multiple contiguous items by: focusing on the <select> element (e.g. using tab). selecting an item at the top or bottom of the...
...plex, and hard to control. if you want to get full control, you should consider using a library with good facilities for styling form widgets, or try rolling your own dropdown menu using non-semantic elements, javascript, and wai-aria to provide semantics. ...
...lect the following example creates a very simple dropdown menu, the second option of which is selected by default. ...
...can scroll to view all the options. we've included <optgroup> elements to divide the options up into different groups. this is a purely visual grouping, its visualization generally consists of the group name being bolded, and the options being indented. the "hamster" option includes a disabled attribute and therefore can't be selected at all. technical summary content categories flow content, phrasing content, interactive content, listed, labelable, resettable, and submittable form-associated element permitted content zero or more <option> or <optgroup> elements. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. implicit aria role combobox with no mult...
<style>: The Style Information element - HTML: Hypertext Markup Language
Web › HTML › Element › style
sheets and apply them using <link> elements. if you include multiple <style> and <link> elements in your document, they will be applied to the dom in the order they are included in the document — make sure you include them in the correct order, to avoid unexpected cascade issues. in the same manner as <link> elements, <style> elements can include media attributes that contain media queries, allowing you to selectively apply internal stylesheets to your document depending on media features such as viewport width. attributes this element includes the global attributes. type this attribute defines the styling language as a mime type (charset should not be specified). this attribute is optional and defaults to text/css if it is not specified; values other than the empty string or text/c...
...ute specifies alternative style sheet sets. deprecated attributes scoped this attribute specifies that the styles only apply to the elements of its parent(s) and children. this attribute may be re-introduced in the future per https://github.com/w3c/csswg-drafts/issues/3547. if you want to use the attribute now, you can use a polyfill. ...
...ncluded two <style> elements — notice how the conflicting declarations in the later <style> element override those in the earlier one, if they have equal specificity. <!doctype html> <html> <head> <style> p { color: white; background-color: blue; padding: 5px; border: 1px solid black; } </style> <style> p { color: blue; background-color: yellow; } </style> </head> <body> <p>this is my paragraph.</p> </body> </html> including a media query in this example we build on the previous one, including a media attribute on the second <style> element so it is only applied when the viewport is less than 500px in width. <!doctype html> <html> <head> <style> p { color: white; background-color: blue; padding: 5px;...
...s one, including a media attribute on the second <style> element so it is only applied when the viewport is less than 500px in width. <!doctype html> <html> <head> <style> p { color: white; background-color: blue; padding: 5px; border: 1px solid black; } </style> <style media="all and (max-width: 500px)"> p { color: blue; background-color: yellow; } </style> </head> <body> <p>this is my paragraph.</p> </body> </html> technical summary content categories metadata content, and if the scoped attribute is present: flow content. permitted content text content matching the type attribute, that is text/css. tag omission neither tag is omissible. permitted parents any element that accept...
<textarea> - HTML: Hypertext Markup Language
Web › HTML › Element › textarea
the html <textarea> element represents a multi-line plain-text editing control, useful when you want to allow users to enter a sizeable amount of free-form text, for example a comment on a review or feedback form. 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 amount of free-form text, for example a comment on a review or feedback form. 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 above example demonstrates a number of features of <textarea>: an id attribute to allow the <textarea> to be associated with a <label> element for accessibility purposes a name attribute to set the name of the associated data point submitted to the server when the form is submitted. rows and cols attributes to allow you to specify an exact size for the <textarea> to take. setting these is a good idea for consistency, as browser defaults can differ. default content entered between...
...f 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 columns and some default content. <textarea name="textarea" rows="10" cols="50">write something here</textarea> min and max length this example has a minimum and maximum number of characters — of 10 and 20 respectively. try it and see. <textarea name="textarea" rows="5" cols="30" minlength="10" maxlength="20">...
...ou just can't edit the contents. note: in browsers other than firefox, such as chrome, the disabled textarea content may be selectable and copyable. <textarea name="textarea" rows="5" cols="30" disabled>i am a disabled textarea</textarea> <textarea name="textarea" rows="5" cols="30" readonly>i am a readonly textarea</textarea> technical summary content categories flow content, phrasing content, interactive content, listed, labelable, resettable, and submittable form-associated element. permitted content text tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. implicit aria role textbox permitted aria roles no role permitted ...
<th> - HTML: Hypertext Markup Language
Web › HTML › Element › th
a group of table cells. the exact nature of this group is defined by the scope and headers attributes. 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 none. permitted content flow content, but with no header, footer, sectioning content, or heading content descendants. tag omission the start tag is mandatory. the end tag may be omitted, if it is immediately followed by a <th> or <td> element or if there are no more data in its parent element. permitted parents a <tr> element. implicit aria role columnheader or rowheader permi...
...tes for how many rows the cell extends. its default value is 1; if its value is set to 0, it extends until the end of the table section (<thead>, <tbody>, <tfoot>, even if implicitly defined), that the cell belongs to. values higher than 65534 are clipped down to 65534. scope this enumerated attribute defines the cells that the header (defined in the <th>) element relates to. it may have the following values: row: the header relates to all cells of the row it belongs to. col: the header relates to all cells of the column it belongs to. rowgroup: the header belongs to a rowgroup and relates to all of its cells. these cells can be placed to the right or the left of the header, depending on the value of the dir attribute in the <table> element. colgroup: the header belongs to a colgr...
... column. it consists of a 6-digit hexadecimal code as defined in srgb and is prefixed by '#'. ...
...s attribute as it is obsolete in the latest standard: use the css height property instead. valign obsolete since html5 this attribute specifies how a text is vertically aligned inside a cell. possible values for this attribute are: baseline: positions the text near the bottom of the cell and aligns it with the baseline of the characters instead of the bottom. if characters don't descend below the baseline, the baseline value achieves the same effect as bottom. bottom: positions the text near the bottom of the cell. middle: centers the text in the cell. and top: positions the text near the top of the cell. note: do not use this attribute as it is obsolete in the latest standard: use the css vertical-align property instead. width deprecated since html4, obsolete since html5...
HTML: Hypertext Markup Language
Web › HTML
<section>, <p>, <div>, <span>, <img>, <aside>, <audio>, <canvas>, <datalist>, <details>, <embed>, <nav>, <output>, <progress>, <video>, <ul>, <ol>, <li> and many others. an html element is set off from other text in a document by "tags", which consist of the element name surrounded by "<" and ">". the name of an element inside a tag is case insensitive. that is, it can be written in uppercase, lowercase, or a mixture. for example, the <title> tag can be written as <title>, <title>, or in any other way. the articles below can help you learn more about html. html introduction if you're new to web development, be sure to read our html basics article to learn what html is and how to use it. html tutorials for articles about how to use html, as well as tutorials and complete exampl...
...ide/front-end parts of forms. use html to solve common problems provides links to sections of content explaining how to use html to solve very common problems when creating a web page: dealing with titles, adding images or videos, emphasizing content, creating a basic form, etc. advanced topics cors enabled image the crossorigin attribute, in combination with an appropriate cors header, allows images defined by the <img> element to be loaded from foreign origins and used in a <canvas> element as if they were being loaded from the current origin. cors settings attributes some html elements that provide support for cors, such as <img> or <video>, have a crossorigin attribute (crossorigin property), which lets you configure the cors requests for the element's fetched data. preloading ...
...<canvas> element as if they were being loaded from the current origin. cors settings attributes some html elements that provide support for cors, such as <img> or <video>, have a crossorigin attribute (crossorigin property), which lets you configure the cors requests for the element's fetched data. preloading content with rel="preload" the preload value of the <link> element's rel attribute allows you to write declarative fetch requests in your html <head>, specifying resources that your pages will need very soon after loading, which you therefore want to start preloading early in the lifecycle of a page load, before the browser's main rendering machinery kicks in. this ensures that they are made available earlier and are less likely to block the page's first render, leading to performanc...
...ags that define it. a block-level element occupies the entire space of its parent element (container), thereby creating a "block." link types in html, various link types can be used to establish and define the relationship between two documents. link elements that types can be set on include <a>, <area> and <link>. guide to media types and formats on the web the <audio> and <video> elements allow you to play audio and video media natively within your content without the need for external software support. html content categories html is comprised of several kinds of content, each of which is allowed to be used in certain contexts and is disallowed in others. similarly, each has a set of other content categories they can contain and elements that can or can't be used in them. this is a g...
HTTP authentication - HTTP
ication. this page is an introduction to the http framework for authentication, and shows how to restrict access to your server using the http "basic" schema. the general http authentication framework rfc 7235 defines the http authentication framework, which can be used by a server to challenge a client request, and by a client to provide authentication information. the challenge and response flow works like this: the server responds to a client with a 401 (unauthorized) response status and provides information on how to authorize with a www-authenticate response header containing at least one challenge. a client that wants to authenticate itself with the server can then do so by including an authorization request header with the credentials. usually a client will present a password p...
...as described in bug 1419658. www-authenticate and proxy-authenticate headers the www-authenticate and proxy-authenticate response headers define the authentication method that should be used to gain access to a resource. they must specify which authentication scheme is used, so that the client that wishes to authorize knows how to provide the credentials. the syntax for these headers is the following: www-authenticate: <type> realm=<realm> proxy-authenticate: <type> realm=<realm> here, <type> is the authentication scheme ("basic" is the most common scheme and introduced below). the realm is used to describe the protected area or to indicate the scope of protection. this could be a message like "access to the staging site" or similar, so that the user knows to which space they are trying...
...or to indicate the scope of protection. this could be a message like "access to the staging site" or similar, so that the user knows to which space they are trying to get access to. authorization and proxy-authorization headers the authorization and proxy-authorization request headers contain the credentials to authenticate a user agent with a (proxy) server. here, the <type> is needed again followed by the credentials, which can be encoded or encrypted depending on which authentication scheme is used. authorization: <type> <credentials> proxy-authorization: <type> <credentials> authentication schemes the general http authentication framework is used by several authentication schemes. schemes can differ in security strength and in their availability in client or server software. the mo...
... authorization: <type> <credentials> proxy-authorization: <type> <credentials> authentication schemes the general http authentication framework is used by several authentication schemes. schemes can differ in security strength and in their availability in client or server software. the most common authentication scheme is the "basic" authentication scheme, which is introduced in more detail below. iana maintains a list of authentication schemes, but there are other schemes offered by host services, such as amazon aws. common authentication schemes include: basic see rfc 7617, base64-encoded credentials. more information below. bearer see rfc 6750, bearer tokens to access oauth 2.0-protected resources digest see rfc 7616, only md5 hashing is supported in firefox, see bug 472823 for...
Expect-CT - HTTP
the expect-ct header lets sites opt in to reporting and/or enforcement of certificate transparency requirements, to prevent the use of misissued certificates for that site from going unnoticed. ct requirements can be satisfied via any one of the following mechanisms: x.509v3 certificate extension to allow embedding of signed certificate timestamps issued by individual logs a tls extension of type signed_certificate_timestamp sent during the handshake supporting ocsp stapling (that is, the status_request tls extension) and providing a signedcertificatetimestamplist when a site enables the expect-ct header, they are requesting that the browser check that any certificate for that site appears in public ct logs. browsers ignore the expect-ct header over http; the header only has effe...
...es the expect-ct header, they are requesting that the browser check that any certificate for that site appears in public ct logs. browsers ignore the expect-ct header over http; the header only has effect on https connections. the expect-ct will likely become obsolete in june 2021. since may 2018 new certificates are expected to support scts by default. certificates before march 2018 were allowed to have a lifetime of 39 months, those will all be expired in june 2021. header type response header forbidden header name yes syntax expect-ct: report-uri="<uri>", enforce, max-age=<age> directives max-age the number of seconds after reception of the expect-ct header field during which the user agent should regard the host of the ...
... yes syntax expect-ct: report-uri="<uri>", enforce, max-age=<age> directives max-age the number of seconds after reception of the expect-ct header field during which the user agent should regard the host of the received message as a known expect-ct host. if a cache receives a value greater than it can represent, or if any of its subsequent calculations overflows, the cache will consider this value to be either 2,147,483,648 (231) or the greatest positive integer it can represent. report-uri="<uri>" optional the uri where the user agent should report expect-ct failures. when present with the enforce directive, the configuration is referred to as an "enforce-and-report" configuration, signalling to the user agent both that compliance to the certifi...
...ould refuse future connections that violate its certificate transparency policy. when both the enforce directive and the report-uri directive are present, the configuration is referred to as an "enforce-and-report" configuration, signalling to the user agent both that compliance to the certificate transparency policy should be enforced and that violations should be reported. example the following example specifies enforcement of certificate transparency for 24 hours and reports violations to foo.example. expect-ct: max-age=86400, enforce, report-uri="https://foo.example/report" notes root cas manually added to the trust store override and suppress expect-ct reports/enforcement. browsers will not remember an expect-ct policy, unless the site has 'proven' it can serve a certificate s...
Feature-Policy: autoplay - HTTP
the http feature-policy header autoplay directive controls whether the current document is allowed to autoplay media requested through the htmlmediaelement interface. when this policy is enabled and there were no user gestures, the promise returned by htmlmediaelement.play() will reject with a domexception. the autoplay attribute on <audio> and <video> elements will be ignored. for more details on autoplay and autoplay blocking, see the article autoplay guide for media and web audio apis. syntax feature-policy: autoplay <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self':...
...autoplay blocking, see the article autoplay guide for media and web audio apis. syntax feature-policy: autoplay <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. ...
...l be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. ...
...re is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. features are each defined to have a default allowlist, which is one of: *: the feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not allowed in cross-origin documents in nested browsing contexts. 'none': the feature is disabled in top-leve...
Feature-Policy: picture-in-picture - HTTP
the http feature-policy header picture-in-picture directive controls whether the current document is allowed to play a video in a picture-in-picture mode via the corresponding api. syntax feature-policy: picture-in-picture <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'n...
...l be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. ...
...re is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. features are each defined to have a default allowlist, which is one of: *: the feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not allowed in cross-origin documents in nested browsing contexts. 'none': the feature is disabled in top-leve...
...ng contexts (iframes). 'self': the feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not allowed in cross-origin documents in nested browsing contexts. 'none': the feature is disabled in top-level and nested browsing contexts. default policy as of june 2019, the spec draft and google chrome set default allow list to *. specifications specification status comment feature policy editor's draft initial definition. ...
Feature-Policy: sync-xhr - HTTP
the http feature-policy header sync-xhr directive controls whether the current document is allowed to make synchronous xmlhttprequest requests. syntax feature-policy: sync-xhr <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and ...
...l be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. ...
...re is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. features are each defined to have a default allowlist, which is one of: *: the feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not allowed in cross-origin documents in nested browsing contexts. 'none': the feature is disabled in top-leve...
... specification specification status comment feature policy editor's draft initial definition. ...
Feature-Policy: usb - HTTP
the http feature-policy header usb directive controls whether the current document is allowed to use the webusb api. syntax feature-policy: usb <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <orig...
...l be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. ...
...re is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. features are each defined to have a default allowlist, which is one of: *: the feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not allowed in cross-origin documents in nested browsing contexts. 'none': the feature is disabled in top-leve...
... ...
Proxy servers and tunneling - HTTP
yption or caching). forward proxies a forward proxy, or gateway, or just "proxy" provides proxy services to a client or a group of clients. there are likely hundreds of thousands of open forward proxies on the internet. they store and forward internet services (like the dns, or web pages) to reduce and control the bandwidth used by the group. forward proxies can also be anonymous proxies and allow users to hide their ip address while browsing the web or using other internet services. tor (the onion router), routes internet traffic through multiple proxies for anonymity. reverse proxies as the name implies, a reverse proxy does the opposite of what a forward proxy does: a forward proxy acts in behalf of clients (or requesting hosts), a reverse proxy acts in behalf of servers. forward prox...
... proxies can make requests appear as if they originated from the proxy's ip address. this can be useful if a proxy is used to provide client anonymity, but in other cases information from the original request is lost. the ip address of the original client is often used for debugging, statistics, or generating location-dependent content. a common way to disclose this information is by using the following http headers: the standardized header: forwarded contains information from the client-facing side of proxy servers that is altered or lost when a proxy is involved in the path of the request. or the de-facto standard versions: x-forwarded-for identifies the originating ip addresses of a client connecting to a web server through an http proxy or a load balancer. x-forwarded-host ...
...(not about the client connecting to it), the via header can be used. via added by proxies, both forward and reverse proxies, and can appear in the request headers and the response headers. http tunneling tunneling transmits private network data and protocol information through public network by encapsulating the data. http tunneling is using a protocol of higher level (http) to transport a lower level protocol (tcp). the http protocol specifies a request method called connect. it starts two-way communications with the requested 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 tunn...
... 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 findproxyforurl. the example below will work in an environment where the internal dns server is set up so that it can only resolve internal host names, and the goal is to use a proxy only for hosts that aren't resolvable: function findproxyforurl(url, host) { if (isresolvable(host)) return "direct"; else return "proxy proxy.mydomain.com:8080"; } see proxy auto-configuration (pac) for more examples. ...
Redirections in HTTP - HTTP
he resource. code text method handling typical use case 301 moved permanently get methods unchanged. others may or may not be changed to get.[1] reorganization of a web site. 308 permanent redirect method and body not changed. reorganization of a web site, with non-get links/operations. [1] the specification did not intend to allow method changes, but there are existing user agents that do change their method. 308 was created to remove the ambiguity of the behavior when using non-get methods. temporary redirections sometimes the requested resource can't be accessed from its canonical location, but it can be accessed from another place. in this case, a temporary redirect can be used. search engine robots and other crawler...
... others changed to get (body lost). used to redirect after a put or a post, so that refreshing the result page doesn't re-trigger the operation. 307 temporary redirect method and body not changed the web page is temporarily unavailable for unforeseen reasons. better than 302 when non-get operations are available on the site. [2] the specification did not intend to allow method changes, but there are existing user agents that do change their method. 307 was created to remove the ambiguity of the behavior when using non-get methods. special redirections 304 (not modified) redirects a page to the locally cached copy (that was stale), and 300 (multiple choice) is a manual redirection: the body, presented by the browser as a web page, lists the possible redirection...
...ressed, only that page is redisplayed, without replaying the unsafe requests. temporary responses to long requests some requests may need more time on the server, like delete requests that are scheduled for later processing. in this case, the response is a 303 (see other) redirect that links to a page indicating that the action has been scheduled, and eventually informs about its progress, or allows to cancel it. configuring redirects in common servers apache redirects can be set either in the server config file or in the .htaccess of each directory. the mod_alias module has redirect and redirectmatch directives that set up 302 redirects by default: <virtualhost *:443> servername example.com redirect / https://www.example.com </virtualhost> the url https://example.com/ will be redi...
.../www.example.com$request_uri; } to apply a redirect to a directory or only certain pages, use the rewrite directive: rewrite ^/images/(.*)$ https://images.example.com/$1 redirect; rewrite ^/images/(.*)$ https://images.example.com/$1 permanent; iis in iis, you use the <httpredirect> element to configure redirections. redirection loops redirection loops happen when additional redirections follow the one that has already been followed. in other words, there is a loop that will never be finished and no page will ever be found. most of the time this is a server problem, and if the server cannot detect it, it will send back a 500 internal server error. if you encounter such an error soon after modifying a server configuration, this is likely a redirection loop. sometimes, the server won't ...
Unicode property escapes - JavaScript
a character is described by several properties which are either binary ("boolean-like") or non-binary. for instance, unicode property escapes can be used to match emojis, punctuations, letters (even letters from specific languages or scripts), etc. note: for unicode property escapes to work, a regular expression must use the u flag which indicates a string must be considered as a series of unicode code points. see also regexp.prototype.unicode. ...
... work, a regular expression must use the u flag which indicates a string must be considered as a series of unicode code points. see also regexp.prototype.unicode. note: some unicode properties encompasses much more characters than some character classes (such as \w which matches only latin letters, a to z) but the latter is better supported among browsers (as of january 2020). syntax the following section is also duplicated on this cheatsheet. do not forget to edit it as well, thanks! // non-binary values \p{unicodepropertyvalue} \p{unicodepropertyname=unicodepropertyvalue} // binary and non-binary values \p{unicodebinarypropertyname} // negation: \p is negated \p \p{unicodepropertyvalue} \p{unicodebinarypropertyname} general_category (gc) script (sc) script_extensions (scx) ...
...gory (gc) script (sc) script_extensions (scx) see also propertyvaluealiases.txt unicodebinarypropertyname the name of a binary property. e.g.: ascii, alpha, math, diacritic, emoji, hex_digit, math, white_space, etc. see unicode data proplist.txt for more info. unicodepropertyname the name of a non-binary property: unicodepropertyvalue one of the tokens listed in the values section, below. many values have aliases or shorthand (e.g. the value decimal_number for the general_category property may be written nd, digit, or decimal_number). for most values, the unicodepropertyname part and equals sign may be omitted. if a unicodepropertyname is specified, the value must correspond to the property type given. note: as there are many properties and values available, we will not descri...
... subcategories using short aliases) story.match(/\p{lu}|\p{ll}|\p{lt}|\p{lm}|\p{lo}/gu); scripts and script extensions some languages use different scripts for their writing system. for instance, english and spanish are written using the latin script while arabic and russian are written with other scripts (respectively arabic and cyrillic). the script and script_extensions unicode properties allow regular expression to match characters according to the script they are mainly used with (script) or according to the set of scripts they belong to (script_extensions). for example, a belongs to the latin script and ε to the greek script. let mixedcharacters = "aεЛ"; // using the canonical "long" name of the script mixedcharacters.match(/\p{script=latin}/u); // a // using a short alias for...
Deprecated and obsolete features - JavaScript
s page lists features of javascript that are deprecated (that is, still available but planned for removal) and obsolete (that is, no longer usable). deprecated features these deprecated features can still be used, but should be used with caution because they are expected to be removed entirely sometime in the future. you should work to remove their use from your code. regexp properties the following properties are deprecated. this does not affect their use in replacement strings: property description $1-$9 parenthesized substring matches, if any. warning: using these properties can result in problems, since browser extensions can modify them. avoid them! $_ see input. $* see multiline. $& see lastmatch. $+...
... $+ see lastparen. $` see leftcontext. $' see rightcontext. input the string against which a regular expression is matched. lastmatch the last matched characters. lastparen the last parenthesized substring match, if any. leftcontext the substring preceding the most recent match. rightcontext the substring following the most recent match. the following are now properties of regexp instances, no longer of the regexp object: property description global whether or not to test the regular expression against all possible matches in a string, or only against the first. ignorecase whether or not to ignore case while attempting a match in a string. lastindex ...
... affected by the year-2000-problem and have been subsumed by getfullyear and setfullyear. you should use toisostring instead of the deprecated togmtstring method in new code. tolocaleformat is deprecated. functions expression closures are deprecated. use regular functions or arrow functions instead. proxy proxy.create and proxy.createfunction are deprecated. use proxy instead. the following traps are obsolete: hasown (bug 980565, firefox 33). getenumerablepropertykeys (bug 783829, firefox 37) getownpropertynames (bug 1007334, firefox 33) keys (bug 1007334, firefox 33) escape sequences octal escape sequences (\ followed by one, two, or three octal digits) are deprecated in string and regular expression literals. the escape and unescape functions are depre...
...roperties directly on a user-defined object. __parent__ points to an object's context. object.prototype.eval() evaluates a string of javascript code in the context of the specified object. object.observe() asynchronously observing the changes to an object. object.unobserve() remove observers. object.getnotifier() creates an object that allows to synthetically trigger a change. function property description arity number of formal arguments. array property description array.observe() asynchronously observing changes to arrays. array.unobserve() remove observers. number number.tointeger() parallelarray parallelarray statements for each...in i...
arguments.callee - JavaScript
within a function expression with no name (also called "anonymous functions"). warning: the 5th edition of ecmascript (es5) forbids use of arguments.callee() in strict mode. avoid using arguments.callee() by either giving function expressions a name or use a function declaration where a function must call itself. why was arguments.callee removed from es5 strict mode? (adapted from a stack overflow answer by olliej) early versions of javascript did not allow named function expressions, and for this reason you could not make a recursive function expression. for example, this syntax worked: function factorial (n) { return !(n > 1) ? 1 : factorial(n - 1) * n; } [1, 2, 3, 4, 5].map(factorial); but: [1, 2, 3, 4, 5].map(function(n) { return !(n > 1) ? 1 : /* what goes here? */ (n - ...
...e be necessary.) the other major issue is that the recursive call will get a different this value, e.g.: var global = this; var sillyfunction = function(recursed) { if (!recursed) { return arguments.callee(true); } if (this !== global) { alert('this is: ' + this); } else { alert('this is the global'); } } sillyfunction(); ecmascript 3 resolved these issues by allowing named function expressions. for example: [1, 2, 3, 4, 5].map(function factorial(n) { return !(n > 1) ? 1 : factorial(n - 1)*n; }); this has numerous benefits: the function can be called like any other from inside your code it does not create a variable in the outer scope (except for ie 8 and below) it has better performance than accessing the arguments object another feature that ...
...mous recursive function a recursive function must be able to refer to itself. typically, a function refers to itself by its name. however, an anonymous function (which can be created by a function expression or the function constructor) does not have a name. therefore if there is no accessible variable referring to it, the only way the function can refer to itself is by arguments.callee. the following example defines a function, which, in turn, defines and returns a factorial function. this example isn't very practical, and there are nearly no cases where the same result cannot be achieved with named function expressions. function create() { return function(n) { if (n <= 1) return 1; return n * arguments.callee(n - 1); }; } var result = create()(5); // returns 1...
...t very practical, and there are nearly no cases where the same result cannot be achieved with named function expressions. ...
getter - JavaScript
ease clone https://github.com/mdn/interactive-examples and send us a pull request. syntax {get prop() { ... } } {get [expression]() { ... } } parameters prop the name of the property to bind to the given function. expression starting with ecmascript 2015, you can also use expressions for a computed property name to bind to the given function. description sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. in javascript, this can be accomplished with the use of a getter. it is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it is possible to use a gett...
...to reflect the status of an internal variable without requiring the use of explicit method calls. in javascript, this can be accomplished with the use of a getter. it is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property. ...
...value is needed. if it is never needed, you never pay the cost. an additional optimization technique to lazify or delay the calculation of a property value and cache it for later access are smart (or "memoized") getters. the value is calculated the first time the getter is called, and is then cached so subsequent accesses return the cached value without recalculating it. this is useful in the following situations: if the calculation of a property value is expensive (takes much ram or cpu time, spawns worker threads, retrieves remote file, etc). if the value isn't needed just now. it will be used later, or in some case it's not used at all. if it's used, it will be accessed several times, and there is no need to re-calculate that value will never be changed or shouldn't be re-calculated.
...eed to re-calculate that value will never be changed or shouldn't be re-calculated. this means that you shouldn’t write a lazy getter for a property whose value you expect to change, because if the getter is lazy then it will not recalculate the value. note that getters are not “lazy” or “memozied” by nature; you must implement this technique if you desire this behavior. in the following example, the object has a getter as its own property. on getting the property, the property is removed from the object and re-added, but implicitly as a data property this time. finally, the value gets returned. get notifier() { delete this.notifier; return this.notifier = document.getelementbyid('bookmarked-notification-anchor'); }, for firefox code, see also the xpcomutils.jsm code mod...
Array.prototype.reduce() - JavaScript
ndex[, array]] )[, initialvalue]) parameters callback a function to execute on each element in the array (except for the first, if no initialvalue is supplied). it takes four arguments: accumulator the accumulator accumulates callback's return values. it is the accumulated value previously returned in the last invocation of the callback—or initialvalue, if it was supplied (see below). currentvalue the current element being processed in the array. index optional the index of the current element being processed in the array. starts from index 0 if an initialvalue is provided. otherwise, it starts from index 1. array optional the array reduce() was called upon. initialvalue optional a value to use as the first argument to the first call of the callback. if no ...
...alue is provided, typeerror will be thrown. if the array only has one element (regardless of position) and no initialvalue is provided, or if initialvalue is provided but the array is empty, the solo value will be returned without calling callback. ...
...educe( maxcallback ); // 22 [ { x: 2 } ].reduce( maxcallback ); // { x: 2 } [ ].reduce( maxcallback ); // typeerror // map & reduce with initialvalue; better solution, also works for empty or larger arrays [ { x: 22 }, { x: 42 } ].map( el => el.x ) .reduce( maxcallback2, -infinity ); how reduce() works suppose the following use of reduce() occurred: [0, 1, 2, 3, 4].reduce(function(accumulator, currentvalue, currentindex, array) { return accumulator + currentvalue }) the callback would be invoked four times, with the arguments and return values in each call being as follows: callback iteration accumulator currentvalue currentindex array return value first call 0 1 ...
... first call 0 1 1 [0, 1, 2, 3, 4] 1 second call 1 2 2 [0, 1, 2, 3, 4] 3 third call 3 3 3 [0, 1, 2, 3, 4] 6 fourth call 6 4 4 [0, 1, 2, 3, 4] 10 the value returned by reduce() would be that of the last callback invocation (10). you can also provide an arrow function instead of a full function. ...
Array.prototype.reduceRight() - JavaScript
and send us a pull request. see also array.prototype.reduce() for left-to-right. syntax arr.reduceright(callback(accumulator, currentvalue[, index[, array]])[, initialvalue]) parameters callback function to execute on each value in the array, taking four arguments: accumulator the value previously returned in the last invocation of the callback, or initialvalue, if supplied. (see below.) currentvalue the current element being processed in the array. indexoptional the index of the current element being processed in the array. arrayoptional the array reduceright() was called upon. initialvalueoptional value to use as accumulator to the first call of the callback. if no initial value is supplied, the last element in the array will be used and skipped. calling red...
...nitialvalue is provided but the array is empty, the solo value would be returned without calling callback. ...
... 19 fourth call 19 1 1 [0, 1, 2, 3, 4] 20 fifth call 20 0 0 [0, 1, 2, 3, 4] 20 the value returned by reduceright this time would be, of course, 20. polyfill reduceright was added to the ecma-262 standard in the 5th edition; as such 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 reduceright in implementations which do not natively support it. // production steps of ecma-262, edition 5, 15.4.4.22 // reference: http://es5.github.io/#x15.4.4.22 if ('function' !== typeof array.prototype.reduceright) { array.prototype.reduceright = function(callback /*, initialvalue*/) { 'use strict'; if (null === this || 'u...
...​​​difference between reduce and reduceright var a = ['1', '2', '3', '4', '5']; var left = a.reduce(function(prev, cur) { return prev + cur; }); var right = a.reduceright(function(prev, cur) { return prev + cur; }); console.log(left); // "12345" console.log(right); // "54321" defining composible function the concept of compose function is simple it combines n functions. it’s a flowing right-to-left, calling each function with the output of the last one. /** * function composition is way in which result of one function can * be passed to another and so on. * * h(x) = f(g(x)) * * function execution happens right to left * * https://en.wikipedia.org/wiki/function_composition */ const compose = (...args) => (value) => args.reduceright((acc, fn) => fn(acc), value) //...
Error.prototype.stack - JavaScript
te that this is the format used by firefox. there is no standard formatting. however, safari 6+ and opera 12- use a very similar format. browsers using the v8 javascript engine (such as chrome, opera 15+, android browser) and ie10+, on the other hand, uses a different format (see the archived msdn error.stack docs). argument values in the stack: prior to firefox 14, the function name would be followed by the argument values converted to string in parentheses immediately before the at (@) sign. while an object (or array, etc.) would appear in the converted form "[object object]", and as such could not be evaluated back into the actual objects, scalar values could be retrieved (though it may be — it is still possible in firefox 14 — easier to use arguments.callee.caller.arguments, as could...
...y on these for breaking the line into its component parts. thus, in firefox 14 and later this is less of an issue. different browsers set this value at different times. for example, firefox sets it when creating an error object, while phantomjs sets it only when throwing the error, and archived msdn docs also seem to match the phantomjs implementation. examples using the stack property the following html markup demonstrates the use of stack property. <!doctype html> <meta charset="utf-8"> <title>stack trace example</title> <body> <script> function trace() { try { throw new error('myerror'); } catch(e) { alert(e.stack); } } function b() { trace(); } function a() { b(3, 4, '\n\n', undefined, {}); } a('first call, firstarg'); </script> assuming the above markup is save...
...-8"> <title>stack trace example</title> <body> <script> function trace() { try { throw new error('myerror'); } catch(e) { alert(e.stack); } } function b() { trace(); } function a() { b(3, 4, '\n\n', undefined, {}); } a('first call, firstarg'); </script> assuming the above markup is saved as c:\example.html on a windows file system it produces an alert message box with the following text: starting with firefox 30 and later containing the column number: trace@file:///c:/example.html:9:17 b@file:///c:/example.html:16:13 a@file:///c:/example.html:19:13 @file:///c:/example.html:21:9 firefox 14 to firefox 29: trace@file:///c:/example.html:9 b@file:///c:/example.html:16 a@file:///c:/example.html:19 @file:///c:/example.html:21 firefox 13 and earlier would instead produce th...
...ext: starting with firefox 30 and later containing the column number: trace@file:///c:/example.html:9:17 b@file:///c:/example.html:16:13 a@file:///c:/example.html:19:13 @file:///c:/example.html:21:9 firefox 14 to firefox 29: trace@file:///c:/example.html:9 b@file:///c:/example.html:16 a@file:///c:/example.html:19 @file:///c:/example.html:21 firefox 13 and earlier would instead produce the following text: error("myerror")@:0 trace()@file:///c:/example.html:9 b(3,4,"\n\n",(void 0),[object object])@file:///c:/example.html:16 a("first call, firstarg")@file:///c:/example.html:19 @file:///c:/example.html:21 stack of eval'ed code starting with firefox 30, the error stack of code in function() and eval() calls, now produces stacks with more detailed information about the line and column numbe...
Function.prototype.call() - JavaScript
sarg may not be the actual value seen by the method. if the method is a function in non-strict mode, null and undefined will be replaced with the global object, and primitive values will be converted to objects. arg1, arg2, ...argn optional arguments for the function. return value the result of calling the function with the specified this value and arguments. description the call() allows for a function/method belonging to one object to be assigned and called for a different object. call() provides a new value of this to the function/method. with call(), you can write a method once and then inherit it in another object, without having to rewrite the method for the new object. note: while the syntax of this function is almost identical to that of apply(), the fundamental differ...
...ithout having to rewrite the method for the new object. note: while the syntax of this function is almost identical to that of apply(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments. examples using call to chain constructors for an object you can use call to chain constructors for an object (similar to java). in the following example, the constructor for the product object is defined with two parameters: name and price. two other functions, food and toy, invoke product, passing this, name, and price. product initializes the properties name and price, both specialized functions define the category. function product(name, price) { this.name = name; this.price = price; } function food(name, price) { product.c...
... function greet() { const reply = [this.animal, 'typically sleep between', this.sleepduration].join(' '); console.log(reply); } const obj = { animal: 'cats', sleepduration: '12 and 16 hours' }; greet.call(obj); // cats typically sleep between 12 and 16 hours using call to invoke a function and without specifying the fi...
... of this will be bound to object obj. function greet() { const reply = [this.animal, 'typically sleep between', this.sleepduration].join(' '); console.log(reply); } const obj = { animal: 'cats', sleepduration: '12 and 16 hours' }; greet.call(obj); // cats typically sleep between 12 and 16 hours using call to invoke a function and without specifying the first argument in the example below, we invoke the display function without passing the first argument. if the first argument is not passed, the value of this is bound to the global object. var sdata = 'wisen'; function display() { console.log('sdata value is %s ', this.sdata); } display.call(); // sdata value is wisen caution: in strict mode, the value of this will be undefined. see below. 'use strict'; var sdata = 'wis...
Intl.RelativeTimeFormat() constructor - JavaScript
the intl.relativetimeformat() constructor creates intl.relativetimeformat objects. syntax new intl.relativetimeformat([locales[, options]]) parameters locales optional. a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. options optional. ...
...ional. an object with some or all of the following properties: 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 intl. numeric the format of output message. possible values are: "always" (default, e.g., 1 day ago), or "auto" (e.g., yesterday). the "auto" value allows to not always have to use numeric values in the output. style the length of the internationalized message. possible values are: "long" (default, e.g., in 1 month) "short" (e.g., in 1 mo.), or "narrow" (e.g., in 1 mo.). the narrow style could be similar to the short style for some locales. ...
... // create a relative time formatter in your locale // with default values explicitly passed in. ...
...s: "auto" style: "long", // other values: "short" or "narrow" }); // format relative time using negative value (-1). rtf.format(-1, "day"); // > "1 day ago" // format relative time using positive value (1). rtf.format(1, "day"); // > "in 1 day" using the auto option if numeric:auto option is passed, it will produce the string yesterday or tomorrow instead of 1 day ago or in 1 day. this allows to not always have to use numeric values in the output. // create a relative time formatter in your locale // with numeric: "auto" option value passed in. const rtf = new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using negative value (-1). rtf.format(-1, "day"); // > "yesterday" // format relative time using positive day unit (1). rtf.format(1, "day"); // > "...
JSON.stringify() - JavaScript
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 json.stringify(value[, replacer[, space]]) parameters value the value to convert to a json string. replacer optional a function that alters the behavior of the stringification process, or an array of string and number that serve as an allowlist for selecting/filtering the properties of the value object to be included in the json string. if this value is null or not provided, all properties of the object are included in the resulting json string. space optional a string or number object that's used to insert white space into the output json string for readability purposes. if this is a number, it indicates the number of space char...
...eters: the key and the value being stringified. the object in which the key was found is provided as the replacer's this parameter. initially, the replacer function is called with an empty string as key representing the object being stringified. it is then called for each property on the object or array being stringified. it should return the value that should be added to the json string, as follows: if you return a number, string, boolean, or null, the stringified version of that value is used as the property's value. if you return a function, symbol, or undefined, the property is not included in the output. if you return any other object, the object is recursively stringified, calling the replacer function on each property. note: you cannot use the replacer function to remove valu...
...y using unicode escapes as \u2028 and \u2029. this recently changed: now both code points may appear literally in strings in json and javascript both. therefore, if compatibility with older javascript engines is required, it is perilous to directly substitute the string returned by json.stringify into a javascript string to be passed to eval or new function or as part of a jsonp url, and the following utility can be used: function jsfriendlyjsonstringify (s) { return json.stringify(s). 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...
...":"quux"}' var b = json.stringify({ baz: "quux", foo: "bar" }) //'{"baz":"quux","foo":"bar"}' console.log(a !== b) // true // some memoization functions use json.stringify to serialize arguments, // which may cause a cache miss when encountering the same object like above example of using json.stringify() with localstorage in a case where you want to store an object created by your user and allowing it to be restored even after the browser has been closed, the following example is a model for the applicability of json.stringify(): // creating an example of json var session = { 'screens': [], 'state': true }; session.screens.push({ 'name': 'screena', 'width': 450, 'height': 250 }); session.screens.push({ 'name': 'screenb', 'width': 650, 'height': 350 }); session.screens.push({ 'name':...
Math.hypot() - JavaScript
ths of the triangle's legs, or the complex number's real and complex components. the corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4). this function makes this calculation easier and faster; you simply call math.hypot(v1, v2) , or math.hypot(v1, v2, v3, v4, ...). math.hypot also avoids overflow/underflow problems if the magnitude of your numbers is very large. the largest number you can represent in js is number.max_value, which is around 10308. if your numbers are larger than about 10154, taking the square of them will result in infinity. for example, math.sqrt(1e200*1e200 + 1e200*1e200) = infinity . if you use hypot() instead, you get better answer: math.hypot(1e200, 1e200) = 1.4142.
...if no arguments are given, the result is +0. if any of the arguments is ±infinity, the result is infinity. if any of the arguments is nan (unless another argument is ±infinity), the result is nan. if at least one of the arguments cannot be converted to a number, the result is nan. with one argument, math.hypot() is equivalent to math.abs(). ...
...ments are given, the result is +0. if any of the arguments is ±infinity, the result is infinity. if any of the arguments is nan (unless another argument is ±infinity), the result is nan. if at least one of the arguments cannot be converted to a number, the result is nan. with one argument, math.hypot() is equivalent to math.abs(). ...
...a naive approach that does not handle overflow/underflow issues: if (!math.hypot) math.hypot = function() { var y = 0, i = arguments.length, containsinfinity = false; while (i--) { var arg = arguments[i]; if (arg === infinity || arg === -infinity) containsinfinity = true y += arg * arg } return containsinfinity ? infinity : math.sqrt(y) } a polyfill that avoids underflows and overflows: if (!math.hypot) math.hypot = function () { var max = 0; var s = 0; var containsinfinity = false; for (var i = 0; i < arguments.length; ++i) { var arg = math.abs(number(arguments[i])); if (arg === infinity) containsinfinity = true if (arg > max) { s *= (max / arg) * (max / arg); max = arg; } s += arg === 0 && max === 0 ? 0 : (arg / ma...
Math.imul() - JavaScript
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. syntax var product = math.imul(a, b); parameters a first number. b second number. return value the result of the c-like 32-bit multiplication of the given arguments. description math.imul() allows for 32-bit integer multiplication with c-like semantics. this feature is useful for projects like emscripten. because imul() is a static method of math, you always use it as math.imul(), rather than as a method of a math object you created (math is not a constructor). if you use normal javascript floating point numbers in imul, you will experience a degrade in performance. this is because of the...
...math is not a constructor). if you use normal javascript floating point numbers in imul, you will experience a degrade in performance. this is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. the reason imul exists is because it is faster in only one (so far) circumstance: asmjs. ...
...ists is because it is faster in only one (so far) circumstance: asmjs. asmjs allows for jist-optimizers to more easily implement internal integers in javascript. multiplying two numbers stored internally as integers (which is only possible with asmjs) with imul is the only potential circumstance where math.imul may prove performant in current browsers. ...
... if (!math.imul) math.imul = function(opa, opb) { opb |= 0; // ensure that opb is an integer. opa will automatically be coerced. ...
Math.random() - JavaScript
ything related to security. use the web crypto api instead, and more precisely the window.crypto.getrandomvalues() method. syntax math.random() return value a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). examples note that as numbers in javascript are ieee 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for math.random() itself) aren't exact. if extremely large bounds are 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 bet...
... exact. if extremely large bounds are 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. ...
...wo 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. function getrandomarbitrary(min, max) { return math.random() * (max - min) + min; } getting a random integer between two values this example returns a random integer between the specified values. the value is no lower than min (or the next integer greater than min if min isn't an integer), and is less than (but not equal to) max. function getrandomint(min, max) { min = math.ceil(min); max = math.floor(max); return math.floor(math.random() * (max - min) + min); //the maximum is exclusive and the minimum is inclusive } it might be tempting to use math.round() to accomplish that, but doing so would ca...
...er greater than min if min isn't an integer), and is less than (but not equal to) max. function getrandomint(min, max) { min = math.ceil(min); max = math.floor(max); return math.floor(math.random() * (max - min) + min); //the maximum is exclusive and the minimum is inclusive } it might be tempting to use math.round() to accomplish that, but doing so would cause your random numbers to follow a non-uniform distribution, which may not be acceptable for your needs. getting a random integer between two values, inclusive while the getrandomint() function above is inclusive at the minimum, it's exclusive at the maximum. what if you need the results to be inclusive at both the minimum and the maximum? the getrandomintinclusive() function below accomplishes that. function getrandomintinc...
Math.random() - JavaScript
ything related to security. use the web crypto api instead, and more precisely the window.crypto.getrandomvalues() method. syntax math.random() return value a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). examples note that as numbers in javascript are ieee 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for math.random() itself) aren't exact. if extremely large bounds are 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 bet...
... exact. if extremely large bounds are 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. ...
...wo 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. function getrandomarbitrary(min, max) { return math.random() * (max - min) + min; } getting a random integer between two values this example returns a random integer between the specified values. the value is no lower than min (or the next integer greater than min if min isn't an integer), and is less than (but not equal to) max. function getrandomint(min, max) { min = math.ceil(min); max = math.floor(max); return math.floor(math.random() * (max - min) + min); //the maximum is exclusive and the minimum is inclusive } it might be tempting to use math.round() to accomplish that, but doing so would ca...
...er greater than min if min isn't an integer), and is less than (but not equal to) max. function getrandomint(min, max) { min = math.ceil(min); max = math.floor(max); return math.floor(math.random() * (max - min) + min); //the maximum is exclusive and the minimum is inclusive } it might be tempting to use math.round() to accomplish that, but doing so would cause your random numbers to follow a non-uniform distribution, which may not be acceptable for your needs. getting a random integer between two values, inclusive while the getrandomint() function above is inclusive at the minimum, it's exclusive at the maximum. what if you need the results to be inclusive at both the minimum and the maximum? the getrandomintinclusive() function below accomplishes that. function getrandomintinc...
Number - JavaScript
lue 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 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.issa...
...ntial notation. number.prototype.tostring([radix]) returns a string representing the specified object in the specified radix ("base"). overrides the object.prototype.tostring() method. number.prototype.valueof() returns the primitive value of the specified object. overrides the object.prototype.valueof() method. ...
...er 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.max_safe_integer // (253 - 1) => 9007199254740991 const smallestint = number.min_safe_integer // -(253 - 1) => -9007199254740991 when parsing data that has been serialized ...
...int = number.min_safe_integer // -(253 - 1) => -9007199254740991 when parsing data that has been serialized to json, integer values falling outside of this range can be expected to become corrupted when json parser coerces them to number type. a possible workaround is to use string instead. larger numbers can be represented using the bigint type. using number to convert a date object the following example converts the date object to a numerical value using number as a function: let d = new date('december 17, 1995 03:24:00') console.log(number(d)) this logs 819199440000. convert numeric strings and null to numbers number('123') // 123 number('123') === 123 /// true number('12.3') // 12.3 number('12.00') // 12 number('123e-1') // 12.3 number('') // 0 number(null) ...
Object.defineProperties() - JavaScript
h to define or modify properties. props an object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. each value in props must be either a data descriptor or an accessor descriptor; it cannot be both (see object.defineproperty() for more details). ...
...tionally contain the following keys: configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. defaults to false. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. defaults to false. a data descriptor also has the following optional keys: value the value associated with the property. can be any valid javascript value (number, object, function, etc). defaults to undefined. writable true if and only if the value associated with the property may be changed with an assignment operator. defaults to false. ...
...the function's return value will be used as the value of the property. defaults to undefined. set a function which serves as a setter for the property, or undefined if there is no setter. ...
...s 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. polyfill assuming a pristine execution environment with all names and properties referring to their initial values, object.defineproperties is almost completely equivalent (note the comment in iscallable) to the following reimplementation in javascript: function defineproperties(obj, properties) { function converttodescriptor(desc) { function hasproperty(obj, prop) { return object.prototype.hasownproperty.call(obj, prop); } function iscallable(v) { // nb: modify as necessary if other values than functions are callable. return typeof v === 'function'; } if (typeof desc ...
Object.freeze() - JavaScript
object.setprototypeof(obj, { x: 20 }) obj.__proto__ = { x: 20 } freezing arrays let a = [0]; object.freeze(a); // the array cannot be modified now. a[0] = 1; // fails silentl...
...object.setprototypeof(obj, { x: 20 }) obj.__proto__ = { x: 20 } freezing arrays let a = [0]; object.freeze(a); // the array cannot be modified now. ...
...0 }) obj.__proto__ = { x: 20 } freezing arrays let a = [0]; object.freeze(a); // the array cannot be modified now. a[0] = 1; // fails silently // in strict mode such attempt will throw a typeerror function fail() { "use strict" a[0] = 1; } fail(); // attempted to push a.push(2); // throws a typeerror the object being frozen is immutable. however, it is not necessarily constant. the following example shows that a frozen object is not constant (freeze is shallow). obj1 = { internal: {} }; object.freeze(obj1); obj1.internal.a = 'avalue'; obj1.internal.a // 'avalue' to be a constant object, the entire reference graph (direct and indirect references to other objects) must reference only immutable frozen objects. the object being frozen is said to be immutable because the entire o...
...t, the entire reference graph (direct and indirect references to other objects) must reference only immutable frozen objects. the object being frozen is said to be immutable because the entire object state (values and references to other objects) within the whole object is fixed. note that strings, numbers, and booleans are always immutable and that functions and arrays are objects. what is "shallow freeze"? the result of calling object.freeze(object) only applies to the immediate properties of object itself and will prevent future property addition, removal or value re-assignment operations only on object. if the value of those properties are objects themselves, those objects are not frozen and may be the target of property addition, removal or value re-assignment operations. var employee...
Object - JavaScript
f 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 an object. object.setprototypeof() ...
.... object.values() returns an array containing the values that correspond to all of a given object's own enumerable string properties. instance properties object.prototype.constructor specifies the function that creates an object's prototype. object.prototype.__proto__ points to the object which was used as prototype when the object was instantiated. object.prototype.__nosuchmethod__ allows a function to be defined that will be executed when an undefined object member is called as a method. instance methods object.prototype.__definegetter__() associates a function with a property that, when accessed, executes that function and returns its return value. object.prototype.__definesetter__() associates a function with a property that, when set, executes that function which modi...
...() calls tostring(). object.prototype.tostring() returns a string representation of the object. object.prototype.unwatch() removes a watchpoint from a property of the object. object.prototype.valueof() returns the primitive value of the specified object. object.prototype.watch() adds a watchpoint to a property of the object. ...
...object.prototype.valueof() returns the primitive value of the specified object. object.prototype.watch() adds a watchpoint to a property of the object. examples using object given undefined and null types the following examples store an empty object object in o: let o = new object() let o = new object(undefined) let o = new object(null) using object to create boolean objects the following examples store boolean objects in o: // equivalent to o = new boolean(true) let o = new object(true) // equivalent to o = new boolean(false) let o = new object(boolean()) object prototypes when altering the behavior of existing object.prototype methods, consider injecting code by wrapping your extension before or after the existing logic. for example, this (untested) code will pre-condit...
handler.construct() - JavaScript
ternal method (i.e. new target must be valid). 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 const p = new proxy(target, { construct: function(target, argumentslist, newtarget) { } }); parameters the following parameters are passed to the construct() method. this is bound to the handler. target the target object. argumentslist the list of arguments for the constructor. newtarget the constructor that was originally called, p above. return value the construct method must return an object. description the handler.construct() method is a trap for the new operator. interceptions this trap ...
...arget object. argumentslist the list of arguments for the constructor. newtarget the constructor that was originally called, p above. return value the construct method must return an object. description the handler.construct() method is a trap for the new operator. interceptions this trap can intercept these operations: new proxy(...args) reflect.construct() invariants if the following invariants are violated, the proxy will throw a typeerror: the result must be an object. examples trapping the new operator the following code traps the new operator. const p = new proxy(function() {}, { construct: function(target, argumentslist, newtarget) { console.log('called: ' + argumentslist.join(', ')); return { value: argumentslist[0] * 10 }; } }); console.log(new ...
...the target in proxy initialization must itself be a valid constructor for the new operator. ...
...the target in proxy initialization must itself be a valid constructor for the new operator. ...
handler.defineProperty() - JavaScript
method is a trap for object.defineproperty(). 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 const p = new proxy(target, { defineproperty: function(target, property, descriptor) { } }); parameters the following parameters are passed to the defineproperty() method. this is bound to the handler. target the target object. property the name or symbol of the property whose description is to be retrieved. descriptor the descriptor for the property being defined or modified. return value the defineproperty() method must return a boolean indicating whether or not the property has been successfully...
...the property being defined or modified. return value the defineproperty() method must return a boolean indicating whether or not the property has been successfully defined. description the handler.defineproperty() method is a trap for object.defineproperty(). interceptions this trap can intercept these operations: object.defineproperty() reflect.defineproperty() invariants if the following invariants are violated, the proxy will throw a typeerror: a property cannot be added, if the target object is not extensible. a property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. a property may not be non-configurable, if a corresponding configurable property of the target object exists. if a pro...
...roperty may not be non-configurable, if a corresponding configurable property of the target object exists. if a property has a corresponding target object property then object.defineproperty(target, prop, descriptor) will not throw an exception. in strict mode, a false return value from the defineproperty() handler will throw a typeerror exception. examples trapping of defineproperty the following code traps object.defineproperty(). const p = new proxy({}, { defineproperty: function(target, prop, descriptor) { console.log('called: ' + prop); return true; } }); const desc = { configurable: true, enumerable: true, value: 10 }; object.defineproperty(p, 'a', desc); // "called: a" when calling object.defineproperty() or reflect.defineproperty(), the descriptor passed to defin...
...p = new proxy({}, { defineproperty: function(target, prop, descriptor) { console.log('called: ' + prop); return true; } }); const desc = { configurable: true, enumerable: true, value: 10 }; object.defineproperty(p, 'a', desc); // "called: a" when calling object.defineproperty() or reflect.defineproperty(), the descriptor passed to defineproperty() trap has one restriction—only following properties are usable (non-standard properties will be ignored): enumerable configurable writable value get set const p = new proxy({}, { defineproperty(target, prop, descriptor) { console.log(descriptor); return reflect.defineproperty(target, prop, descriptor); } }); object.defineproperty(p, 'name', { value: 'proxy', type: 'custom' }); // { value: 'proxy' } speci...
handler.getOwnPropertyDescriptor() - JavaScript
od is a trap for object.getownpropertydescriptor(). 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 const p = new proxy(target, { getownpropertydescriptor: function(target, prop) { } }); parameters the following parameters are passed to the getownpropertydescriptor() method. this is bound to the handler. target the target object. prop the name of the property whose description should be retrieved. return value the getownpropertydescriptor() method must return an object or undefined. description the handler.getownpropertydescriptor() method is a trap for object.getownpropertydescriptor(). i...
...operty whose description should be retrieved. return value the getownpropertydescriptor() method must return an object or undefined. description the handler.getownpropertydescriptor() method is a trap for object.getownpropertydescriptor(). interceptions this trap can intercept these operations: object.getownpropertydescriptor() reflect.getownpropertydescriptor() invariants if the following invariants are violated, the proxy will throw a typeerror: getownpropertydescriptor() must return an object or undefined. a property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. a property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. a property...
...ible. a property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. the result of object.getownpropertydescriptor(target) can be applied to the target object using object.defineproperty() and will not throw an exception. ...
... const obj = { a: 10 }; object.preventextensions(obj); const p = new proxy(obj, { getownpropertydescriptor: function(target, prop) { return undefined; } }); object.getownpropertydescriptor(p, 'a'); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[getownproperty]]' in that specification. ...
RegExp - JavaScript
ead the regular expressions chapter in the javascript guide. description literal notation and constructor there are two ways to create a regexp object: a literal notation and a constructor. the literal notation's parameters are enclosed between slashes and do not use quotation marks. the constructor function's parameters are not enclosed between slashes but do use quotation marks. the following three expressions create the same regular expression: /ab+c/i new regexp(/ab+c/, 'i') // literal notation new regexp('ab+c', 'i') // constructor the literal notation results in compilation of the regular expression when the expression is evaluated. use literal notation when the regular expression will remain constant. for example, if you use literal notation to construct a regular expressio...
..., 'i') no longer throws a typeerror ("can't supply flags when constructing one regexp from another") when the first argument is a regexp and the second flags argument is present. a new regexp from the arguments is created instead. when using the constructor 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 regex...
... against a string. regexp.prototype[@@replace]() replaces matches in given string with new substring. regexp.prototype[@@search]() searches the match in given string and returns the index the pattern found in the string. regexp.prototype[@@split]() splits given string into an array by separating the string into substrings. examples using a regular expression to change data format the following script uses the replace() method of the string instance to match a name in the format first last and output it in the format last, first. in the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern. let re = /(\w+)\s(\w+)/ let str = 'john smith' let newstr = str.replace(re, '$2, $1') console.log(newstr...
... extracting sub-domain name from url let url = 'http://xxx.domain.com' console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx' instead of using regular expressions for parsing urls, it is usually better to use the browsers built-in url parser by using the url api. specifications specification ecmascript (ecma-262)the def...
String.prototype.match() - JavaScript
end on the presence or absence of the global (g) flag, or null if no matches are found. if the g flag is used, all results matching the complete regular expression will be returned, but capturing groups will not. if the g flag is not used, only the first complete match and its related capturing groups are returned. in this case, the returned item will have additional properties as described below. additional properties as explained above, some results contain additional properties as described below. groups an object of named capturing groups whose keys are the names and values are the capturing groups or undefined if no named capturing groups were defined. see groups and ranges for more information. index the index of the search at which the result was found. input a copy of t...
... the same result as regexp.exec(). other methods if you need to know if a string matches a regular expression regexp, use regexp.test(). if you only want the first match found, you might want to use regexp.exec() instead. if you want to obtain capture groups and the global flag is set, you need to use regexp.exec() or string.prototype.matchall() instead. examples using match() in the following example, match() is used to find 'chapter' followed by 1 or more numeric characters followed by a decimal point and numeric character 0 or more times. the regular expression includes the i flag so that upper/lower case differences will be ignored. const str = 'for more information, see chapter 3.4.5.1'; const re = /see (chapter \d+(\.\d)*)/i; const found = str.match(re); console.log(found);...
...ut: 'for more information, see chapter 3.4.5.1' ] // 'see chapter 3.4.5.1' is the whole match. // 'chapter 3.4.5.1' was captured by '(chapter \d+(\.\d)*)'. // '.1' was the last value captured by '(\.\d)'. // the 'index' property (22) is the zero-based index of the whole match. // the 'input' property is the original string that was parsed. using global and ignore case flags with match() the following example demonstrates the use of the global and ignore case flags with match(). all letters a through e and a through e are returned, each its own element in the array. const str = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'; const regexp = /[a-e]/gi; const matches_array = str.match(regexp); console.log(matches_array); // ['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e'] note: ...
...the array. const str = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'; const regexp = /[a-e]/gi; const matches_array = str.match(regexp); console.log(matches_array); // ['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e'] note: see also string.prototype.matchall() and advanced searching with flags. using named capturing groups in browsers which support named capturing groups, the following code captures "fox" or "cat" into a group named "animal": const paragraph = 'the quick brown fox jumps over the lazy dog. it barked.'; const capturingregex = /(?<animal>fox|cat) jumps over/; const found = paragraph.match(capturingregex); console.log(found.groups); // {animal: "fox"} using match() with no parameter const str = "nothing will come of nothing."; str.match(); // returns [""...
String.prototype.repeat() - JavaScript
ive-examples and send us a pull request. syntax str.repeat(count) parameters count an integer between 0 and +infinity, indicating the number of times to repeat the string. return value a new string containing the specified number of copies of the given string. exceptions rangeerror: repeat count must be non-negative. ...
...fied number of copies of the given string. exceptions rangeerror: repeat count must be non-negative. rangeerror: repeat count must be less than infinity and not overflow maximum string size. 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.repeat() with the following snippet: if (!string.prototype.repeat) { string.prototype.repeat = function(count) { 'use strict'; if (this == null) throw new typeerror('can\'t convert ' + this + ' to object'); var str = '' + this; // to convert string to integer. count = +count; // check nan if (count != count) count = 0; if (count < 0) throw new rangeerror('repeat coun...
...ger. ...
... than infinity'); count = math.floor(count); if (str.length == 0 || count == 0) return ''; // ensuring count is a 31-bit integer allows us to heavily optimize the // main part. ...
String.prototype.toLocaleUpperCase() - JavaScript
own if an array element isn't of type string. description the tolocaleuppercase() method returns the value of the string converted to upper case according to any locale-specific case mappings. tolocaleuppercase() does not affect the value of the string itself. ...
... do not follow the default case mappings in unicode, there may be a different result. also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. therefore the length of the result string can differ from the input length. this also implies that the conversion is not stable, so i.e. ...
...ings in unicode, there may be a different result. also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. therefore the length of the result string can differ from the input length. this also implies that the conversion is not stable, so i.e. ...
...lt. also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. therefore the length of the result string can differ from the input length. this also implies that the conversion is not stable, so i.e. ...
Iteration protocols - JavaScript
some built-in types are built-in iterables with a default iteration behavior, such as array or map, while other types (such as object) are not. ...
...some built-in types are built-in iterables with a default iteration behavior, such as array or map, while other types (such as object) are not. ...
...that when invoked, an iterator object is returned. inside of this generator function, each entry can be provided by using yield. the iterator protocol the iterator protocol defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated. an object is an iterator when it implements a next() method with the following semantics: property value next() a zero-argument function that returns an object with at least the following two properties: done (boolean) has the value false if the iterator was able to produce the next value in the sequence. (this is equivalent to not specifying the done property altogether.) has the value true if the iterator has comp...
...one and value. if a non-object value gets returned (such as false or undefined), a typeerror ("iterator.next() returned a non-object value") will be thrown. note: it is not possible to know reflectively whether a particular object implements the iterator protocol. however, it is easy to create an object that satisfies both the iterator and iterable protocols (as shown in the example below). doing so allows an iterator to be consumed by the various syntaxes expecting iterables. thus, it is seldom useful to implement the iterator protocol without also implementing iterable. // satisfies both the iterator protocol and iterable let myiterator = { next: function() { // ... }, [symbol.iterator]: function() { return this; } }; examples using the iteration protoco...
Logical AND (&&) - JavaScript
d a boolean operator since its return value can always be converted to a boolean primitive. to explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double not operator or the boolean constructor. short-circuit evaluation the logical and expression is evaluated left to right, it is tested for possible "short-circuit" evaluation using the following rule: (some falsy expression) && expr is short-circuit evaluated to the falsy expression; short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). this happens because the value of the operator is already determined after the evaluation of the first operand. see exam...
... 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, because the && operator is executed before the || operator (see operator precedence). true || false && false // returns true, because && is executed first (true || false) && false // returns false, because operator precedence cannot apply examples using and the following code shows examples of the && (logical and) operator. a1 =...
...3 = false && true // f && t returns false a4 = false && (3 == 4) // f && f returns false a5 = 'cat' && 'dog' // t && t returns "dog" a6 = false && 'cat' // f && t returns false a7 = 'cat' && false // t && f returns false a8 = '' && false // f && f returns "" a9 = false && '' // f && f returns false conversion rules for booleans converting and to or the following operation involving booleans: bcondition1 && bcondition2 is always equal to: !(!bcondition1 || !bcondition2) converting or to and the following operation involving booleans: bcondition1 || bcondition2 is always equal to: !(!bcondition1 && !bcondition2) removing nested parentheses as logical expressions are evaluated left to right, it is always possible to remove parentheses from a co...
...ing booleans: bcondition1 && bcondition2 is always equal to: !(!bcondition1 || !bcondition2) converting or to and the following operation involving booleans: bcondition1 || bcondition2 is always equal to: !(!bcondition1 && !bcondition2) removing nested parentheses as logical expressions are evaluated left to right, it is always possible to remove parentheses from a complex expression following some rules. the following composite operation involving booleans: bcondition1 || (bcondition2 && bcondition3) is always equal to: bcondition1 || bcondition2 && bcondition3 specifications specification ecmascript (ecma-262)the definition of 'logical and expression' in that specification. ...
Object initializer - JavaScript
will reject computed property names and an error will be thrown. examples creating objects an empty object with no properties can be created like this: let object = {} however, the advantage of the literal or initializer notation is, that you are able to quickly create objects with properties inside the curly braces. you simply notate a list of key: value pairs delimited by commas. the following code creates an object with three properties and the keys are "foo", "age" and "baz". the values of these keys are a string "bar", the number 42, and another object. let object = { foo: 'bar', age: 42, baz: {myprop: 12} } accessing properties once you have created an object, you might want to read or change them. object properties can be accessed by using the dot notation or the brack...
...e.log(a) // {x: 2} in ecmascript 5 strict mode code, duplicate property names were considered a syntaxerror. with the introduction of computed property names making duplication possible at runtime, ecmascript 2015 has removed this restriction. function havees2015duplicatepropertysemantics() { 'use strict'; try { ({prop: 1, prop: 2}); // no error thrown, duplicate property names allowed in strict mode return true; } catch(e) { // error thrown, duplicates prohibited in strict mode return false; } } method definitions a property of an object can also refer to a function or a getter or setter method. let o = { property: function (parameters) {}, get property() {}, set property(value) {} } in ecmascript 2015, a shorthand notation is available, so that the...
...enerator() { ........... } }; which is equivalent to this es5-like notation (but note that ecmascript 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' + ...
... console.log(a.foo3) // 3 let param = 'size' let config = { [param]: 12, ['mobile' + param.charat(0).touppercase() + param.slice(1)]: 4 } console.log(config) // {size: 12, mobilesize: 4} spread properties the rest/spread properties for ecmascript proposal (stage 4) adds spread properties to object literals. it copies own enumerable properties from a provided object onto a new object. shallow-cloning (excluding prototype) or merging objects is now possible using a shorter syntax than object.assign(). let obj1 = { foo: 'bar', x: 42 } let obj2 = { foo: 'baz', y: 13 } let clonedobj = { ...obj1 } // object { foo: "bar", x: 42 } let mergedobj = { ...obj1, ...obj2 } // object { foo: "baz", x: 42, y: 13 } note that object.assign() triggers setters, whereas the spread operator doesn't! ...
export - JavaScript
rious modules. this can be achieved with the "export from" syntax: export { default as function1, function2 } from 'bar.js'; which is comparable to a combination of import and export: import { default as function1, function2 } from 'bar.js'; export { function1, function2 }; but where function1 and function2 do not become available inside the current module. ...
...ailable inside the current module. ...
... you can't run js modules via a file:// url — you'll get cors errors. you need to run it via an http server. using the default export if we want to export a single value or to have a fallback value for your module, you could use a ...
...we want to export a single value or to have a fallback value for your module, you could use a default export: // module "my-module.js" export default function cube(x) { return x * x * x; } then, in another script, it is straightforward to import the default export: import cube from './my-module.js'; console.log(cube(3)); // 27 using export from let's take an example where we have the following hierarchy: childmodule1.js: exporting myfunction and myvariable childmodule2.js: exporting myclass parentmodule.js: acting as an aggregator (and doing nothing else) top level module: consuming the exports of parentmodule.js this is what it would look like using code snippets: // in childmodule1.js let myfunction = ...; // assign something useful to myfunction let myvariable = ...; // ...
switch - 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. ...
...tements. (if multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.) if no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. if no default clause is found, the program continues execution at the statement following the end of switch. by convention, the default clause is the last clause, but it does not need to be so. the optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. if break is omitted, the program continues execution at the next statement in the swit...
... clause is the last clause, but it does not need to be so. the optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. if break is omitted, the program continues execution at the next statement in the switch statement. examples using switch in the following example, if expr evaluates to bananas, the program matches the value with case case 'bananas' and executes the associated statement. when break is encountered, the program breaks out of switch and executes the statement following switch. if break were omitted, the statement for the case 'cherries' would also be executed. switch (expr) { case 'oranges': console.log('oranges are $0.59 a p...
...itch (foo) { case 2: console.log(2); break; // it encounters this break so will not continue into 'default:' default: console.log('default') // fall-through case 1: console.log('1'); } it also works when you put default before all other cases. methods for multi-criteria case source for this technique is here: switch statement multiple cases in javascript (stack overflow) multi-case : single operation this method takes advantage of the fact that if there is no break below a case clause it will continue to execute the next case clause regardless if the case meets the criteria. (see the section what happens if i forgot a break?) this is an example of a single operation sequential case statement, where four different values perform exactly the same. var animal =...
icons - Web app manifests
mandatory yes the icons member specifies an array of objects representing image files that can serve as application icons for different contexts. for example, they can be used to represent the web application amongst a list of other applications, or to integrate the web application with an os's task switcher and/or system preferences. ...
...enting image files that can serve as application icons for different contexts. for example, they can be used to represent the web application amongst a list of other applications, or to integrate the web application with an os's task switcher and/or system preferences. examples "icons": [ { "src": "icon/lowres.webp", "sizes": "48x48", "type": "image/webp" }, { "src": "icon/lowres", "sizes": "48x48" }, { "src": "icon/hd_hi.ico", "sizes": "72x72 96x96 128x128 256x256" }, { "src": "icon/hd_hi.svg", "sizes": "72x72" } ] values image objects may contain the following values: member description sizes a string containing space-separated image dimensions. src the path to the image file. if src is a relati...
... "sizes": "72x72" } ] values image objects may contain the following values: member description sizes a string containing space-separated image dimensions. src the path to the image file. if src is a relative url, the base url will be the url of the manifest. type a hint as to the media type of the image. the purpose of this member is to allow a user agent to quickly ignore images with media types it does not support. purpose defines the purpose of the image, for example if the image is intended to serve some special purpose in the context of the host os (i.e., for better integration). ...
...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. ...
MathML attribute reference - MathML
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 boolean value specifying whether more vertical space is used for displayed equations or, if set to false, a more compact layout is used to display formulas. unimplemented edge <malignmark> unimplemented equalcolumns <mtable> a boolean value indicating whether to force all columns to have the same total height. ...
...limits <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 the child elements. numalign <mfrac> the alignment of the numerator over the fraction. open <mfenced> a string for the opening delimiter. unimplemented overflow <math> if an expression is too long to fit in the allowed width, this attribute sets the preferred handling. unimplemented position <msgroup>, <msrow>, <mscarries>, <msline> rowalign <mtable>, <mtd>, <mtr> specifies the vertical alignment of table cells. rowlines <mtable> specifies table row borders. rowspacing <mtable> specifies ...
...s 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 whether the operator is a separator (such as commas). ...
...<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 (centered fraction line). voffset <mpad...
<mstyle> - MathML
Web › MathML › Element › mstyle
attributes dir overall directionality of formulas. possible values are either ltr (left to right) or rtl (right to left). decimalpoint this attribute is specifying the character for the alignment point within <mstack> and <mtable> columns, if the decimalpoint value is used to specify the alignment. ...
...re vertical space is used for displayed equations or, if set to false, a more compact layout is used to display formulas. the main effect is that larger versions of operators are displayed, when displaystyle is set to true. see also largeop and movablelimits on <mo>. infixlinebreakstyle specifies the default linebreakstyle to use for infix operators. ...
...the default value is 8pt. ...
...maller 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 attributes of all presentation elements with the following exceptions: height, depth or width do not apply to <mglyph>, <mpadded> or <mtable>. rowalign, columnalign...
<mtable> - MathML
Web › MathML › Element › mtable
inside a <mtable> only <mtr> and <mtd> elements may appear. these elements are similar to <table> , <tr> and <td> elements of html. note: the <mtable> 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. ...
...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 table rather than the whole table. a negative integer value counts rows from the bottom of the table. starting with gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) the interpretation of negative values has been corrected (bug 601436). in gecko 17.0 (firefox 17.0 / thunderbird 17.0 / seamonkey 2.14) the parsing has been updated to treat whitespace c...
...seamonkey 2.5) the interpretation of negative values has been corrected (bug 601436). in gecko 17.0 (firefox 17.0 / thunderbird 17.0 / seamonkey 2.14) the parsing has been updated to treat whitespace correctly. alignmentscope unimplemented class, id, style provided for use with stylesheets. columnalign specifies the horizontal alignment of the cells. multiple values separated by space are allowed and apply to the corresponding columns (e.g. columnalign="left right center"). possible values are: left, center (default) and right. columnlines specifies column borders. multiple values separated by space are allowed and apply to the corresponding columns (e.g. columnlines="none none solid"). possible values are: none (default), solid and dashed. columnspacing specifies the space between ...
...ecified 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 values separated by space are allowed and apply to the corresponding rows (e.g. rowlines="none none solid"). possible values are: none (default), solid and dashed. unimplemented rowspacing specifies the space b...
Digital video concepts - Web media technologies
els. there are two primary methods used to represent rgb samples: using integer components and using floating-point components. when using integer components, rgb color uses 8 bits each of red, green, and blue, as well as potentially 8 bits of alpha (the amount of transparency). yuv unlike rgb, the yuv (or y'uv) color encoding system is based around how humans perceive a color image. doing so allows color data to be represented using fewer total bits of space in a video stream. the name "yuv" is generally used today to describe this color system, even though the term was originally used specifically for analog coding of color, while ycbcr was used for digital color. however, today both terms are used for digital color. the prime symbol, ', indicates that gamma compression is being used. c...
...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 somewhat fuzzy, lower-resolution map of the colors of light received across the retina at the same time. the final color image is created by the brain, which essentially layers the colors onto the greyscale pixels. yuv concepts yuv works by defining a color space with three components: luma (y') the brightness of the pixel. without the other two components, the luma of each pixel in the frame produces a greysc...
...red-difference (v or cr) the red-difference component of the chroma of the color sample. computed by substracting luma from the gamma corrected red value: v = r' - y'. chroma subsampling chroma subsampling is the process of converting the color pixels into a greyscale image and a matrix of u and v values indicating the colors to map to those pixels. since the color data is being encoded at a lower resolution 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 numb...
...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 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 th...
CSS and JavaScript animation performance - Web Performance
s: css transitions provide an easy way to make animations occur between the current style and an end css state, e.g., a resting button state and a hover state. even if an element is in the middle of a transition, the new transition starts from the current style immediately instead of jumping to the end css state. see using css transitions for more details. css animations, on the other hand, allow developers to make animations between a set of starting property values and a final set rather than between two states. css animations consist of two components: a style describing the css animation, and a set of key frames that indicate the start and end states of the animation's style, as well as possible intermediate points. see using css animations for more details. in terms of performance,...
...k the i’ll be careful, i promise! button to enter the config screen. in the search bar, search for the layers.acceleration.draw-fps preference. double-click the entry to set the value to true. now you will be able to see three little purple boxes at the upper left corner of the firefox window. the first box represents fps. running the performance test initially in the test seen below, a total of 1000 <div> elements are transformed by css animation. the animation can be switched to requestanimationframe() by clicking the toggle button. try running them both now, comparing the fps for each (the first purple box.) you should see that the performance of css animations and requestanimationframe() are very close. off main thread animation even given the test results above, w...
...he toggle button. try running them both now, comparing the fps for each (the first purple box.) you should see that the performance of css animations and requestanimationframe() are very close. off main thread animation even given the test results above, we'd argue that css animations are the better choice. but how? the key is that as long as the properties we want to animate do not trigger reflow/repaint (read css triggers for more information), we can move those sampling operations out of the main thread. the most common property is the css transform. if an element is promoted as a layer, animating transform properties can be done in the gpu, meaning better performance/efficiency, especially on mobile. find out more details in offmainthreadcompositing. to enable the omta (off main thre...
... after enabling omta, try running the above test again. you should see that the fps of the css animations will now be significantly higher. note: in nightly/developer edition, you should see that omta is enabled by default, so you might have to do the tests the other way around (test with it enabled first, then disable to test without omta.) summary browsers are able to optimize rendering flows. in summary, we should always try to create our animations using css transitions/animations where possible. if your animations are really complex, you may have to rely on javascript-based animations instead. ...
Critical rendering path - Web Performance
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 web performance includes the server requests and responses, loading, scripting, rendering, layout, and the painting of the pixels to the screen. a request for a web page or app starts with an html request. the server returns the html - response headers and data. the browse...
...oken. nodes contain all relevant information about the html element. the information is described using tokens. nodes are connected into a dom tree based on token hierarchy. if another set of starttag and endtag tokens come between a set of starttag and endtags, you have a node inside a node, which is how we define the hierarchy of the dom tree. the greater the number of nodes, the longer the following events in the critical rendering path will take. measure! a few extra nodes won't make a difference, but divitis can lead to jank. css object model the dom contains all the content of the page. the cssom contains all the styles of the page; information on how to style that dom. cssom is similar to the dom, but different. while the dom construction is incremental, cssom is not. css is render ...
...ific 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 dom and cssom trees are combined into the render tree. to construct th...
...the entire screen is painted. after that, only impacted areas of the screen will be repainted, as browsers are optimized to repaint the minimum area required. paint time depends on what kind of updates are being applied to the render tree. while painting is a very fast process, and therefore likely not the most impactful place to focus on in improving performance, it is important to remember to allow for both layout and re-paint times when measuring how long an animation frame may take. the styles applied to each node increase the paint time, but removing style that increases the paint by 0.001ms may not give you the biggest bang for your optimization buck. remember to measure first. then you can determine whether it should be an optimization priority. optimizing for crp improve page load s...
Optimizing startup performance - Web Performance
rts up. this will prevent the app, browser, and/or device from appearing to have locked up. why is it important to be asynchronous? other than the reasons suggested above, consider the impact of a non-responsive page or user interface. the user is unable to cancel if they launched your app by mistake. if the app is being run in a browser, it's possible the user may get an "unresponsive app" or "slow script" notification. you should present some kind of interface, such as a progress bar, so that the user knows how much longer they'll need to wait while your app starts up. where there's a will... if you're starting your project from scratch, it's usually pretty easy to just write everything the "right way," making appropriate bits of the code asynchronous. all pure startup calculations shoul...
...ll wind up having to run most or all of your startup code on the main thread. however, even code like that can be made asynchronous, with a little work. getting asynchronous here are some suggestions for how to build your startup process to be as asynchronous as possible (whether it's a new app or a port): use the defer or async attribute on script tags needed by the web application. this allows html parsers to continue processing the document, instead of having to wait until the scripts have been downloaded and executed before continuing. if you need to decode asset files (for example, decoding jpeg files and turning them into raw texture data for later use by webgl), that's great to do in workers. when dealing with data supported by the browser (for example, decoding image data), us...
...n code's startup process is to refactor the code into small pieces that can be done in chunks interspersed across multiple calls to your app's main loop, so that the main thread gets to handle input and the like. emscripten provides an api to help with this refactoring; for example, you can use emscripten_push_main_loop_blocker() to establish 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. how asynchronous should i get? it's worth keeping in mind that most browsers typically start complaining that ...
... that leaves, though, the problem of 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 ...
How to make PWAs installable - Progressive web apps (PWAs)
previous overview: progressive next in the last article, we read about how the example application, js13kpwa, works offline thanks to its service worker, but we can go even further and allow users to install the web app on mobile and desktop browers that support doing so. the installed web app can then be launched by users just as if it were any native app. this article explains how to achieve this using the web app's manifest. these technologies allow the app to be launched directly from the device's home screen, rather than the user having to open the browser and then navigate to the site by using a bookmark or typing the url. your web app can sit next to native applications as first class citizens. this makes the web app easier to access; additionally, you can specify tha...
... web app can sit next to native applications as first class citizens. this makes the web app easier to access; additionally, you can specify that the app be launched in fullscreen or standalone mode, thus removing the default browser user interface that would otherwise be present, creating an even more seamless and native-like feel. ...
...g the default browser user interface that would otherwise be present, creating an even more seamless and native-like feel. requirements to make the web site installable, it needs the following things in place: a web manifest, with the correct fields filled in the web site to be served from a secure (https) domain an icon to represent the app on the device a service worker registered, to allow the app to work offline (this is required only by chrome for android currently) currently, only the chromium-based browsers such as chrome, edge, and samsung internet require the service worker. if developing your app using firefox, be aware that you will need a service worker to be compatible with chromium-based browsers. the manifest file the key element is a web manifest file, which list...
...esktop), and a background color to use in loading or splash screens. this information is needed for the browser to present the web app properly during the installation process, as well as within the device's app-launching interface, such as the home screen of a mobile device. the js13kpwa.webmanifest file of the js13kpwa web app is included in the <head> block of the index.html file using the following line of code: <link rel="manifest" href="js13kpwa.webmanifest"> there are a few common kinds of manifest file that have been used in the past: manifest.webapp was popular in firefox os app manifests, and many use manifest.json for web manifests as the contents are organized in a json structure. however, the .webmanifest file format is explicitly mentioned in the w3c manifest specification, ...
Media - Progressive web apps (PWAs)
an take more than one form. for example, you are probably reading this on a device with a display. but you might also want to project it to a big screen for a large audience, or you might want to print it. these different media have different characteristics. css has the capacity to present content according to the media type. to specify rules that are specific to a type of media, use @media followed by the media type, followed by curly braces that enclose the rules. example a document on a website has a navigation area that contains the primary site menu. in the markup language, the navigation area's parent element has the id nav-area. (in html5, this can be marked up with the <nav> element instead of <div> with an id attribute.) when printing the document, the navigation area has no ...
... followed by curly braces that enclose the rules. example a document on a website has a navigation area that contains the primary site menu. in the markup language, the navigation area's parent element has the id nav-area. (in html5, this can be marked up with the <nav> element instead of <div> with an id attribute.) when printing the document, the navigation area has no purpose. this css (below) removes the navigation area when printing the document: @media print { #nav-area {display: none;} } some common media types are: screen color device display print printed paged media projection projected display all all media (the default) more details there are other ways to specify the media type for a set of rules. the documen...
...a when printing the document: @media print { #nav-area {display: none;} } some common media types are: screen color device display print printed paged media projection projected display all all media (the default) more details there are other ways to specify the media type for a set of rules. the document's markup language might allow the media type to be specified when the stylesheet is linked to the document. for example, in html, you have the option to specify the media type with a media attribute in the link element. in css, you can use @import at the start of a stylesheet to import another stylesheet from a url, optionally specifying the media type. these are ways of separating styling rules for different media types in...
...url that the user has not visited recently e:visited any e element that is a hyperlink to a url that the user has visited recently note: the information that can be obtained from the :visited selector is restricted in gecko 2.0. see privacy and the : visited selector for more details. the cursor property specifies the shape of the pointer: some of the common shapes are as follows. place your mouse over the items in this list to see the actual pointer shapes in your browser: selector selects pointer indicating a link wait indicating that the program cannot accept input progress indicating that the program is working, but can still accept input default the default (usually an arrow) an outline property...
end - SVG: Scalable Vector Graphics
Web › SVG › Attribute › end
efines an end value for the animation that can constrain the active duration. five elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set> usage notes default value none value <end-value-list> animatable no the <end-value-list> is a semicolon-separated list of values. each value can be one of the following: <offset-value> this value defines a clock-value that represents a point in time relative to the beginning of the svg document (usually the load or domcontentloaded event). negative values are valid. <syncbase-value> this value defines a syncbase and an optional offset from that syncbase. the element's animation end time is defined relative to the begin or active end of another animation...
...me relative to the beginning of the svg document (usually the load or domcontentloaded event). negative values are valid. <syncbase-value> this value defines a syncbase and an optional offset from that syncbase. the element's animation end time is defined relative to the begin or active end 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 t...
... 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, focusin, focusout, activate, auxclick, click, dblclick, mousedown, mouseenter, mouseleave, mousemove, mouseout, mouseover, mouseup, wheel, beforeinput, input, keydown, keyup, compositionstart, composition...
...nload, abort, error, select, resize, scroll, beginevent, endevent, and repeatevent . an optional offset value as defined in <offset-value> can be appended. <repeat-value> this value defines a qualified repeat event. the element animation end time is defined relative to the time that the repeat event is raised with the specified iteration value. a valid repeat value consists of an element id followed by a dot and the function repeat() with an integer value specifying the number of repetitions as parameter. an optional offset value as defined in <offset-value> can be appended. <accesskey-value> this value defines an access key that should trigger the end of the animation. the element animation will end when the user presses the specified key. a valid accesskey-value consists of the functi...
preserveAspectRatio - SVG: Scalable Vector Graphics
the preserveaspectratio attribute indicates how an element with a viewbox providing a given aspect ratio must fit into a viewport with a different aspect ratio. because the aspect ratio of an svg image is defined by the viewbox attribute, if this attribute isn't set, the preserveaspectratio attribute has no effect (with one exception, the <image> element, as described below). example <svg viewbox="-1 -1 162 92" 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 preserve...
...viewbox="0 0 100 100" width="10" height="25" preserveaspectratio="xmaxymid slice" x="150" y="0"> <use href="#smiley" /> </svg> <!-- none --> <rect x="0" y="30" width="160" height="60"> <title>none</title> </rect> <svg viewbox="0 0 100 100" width="160" height="60" preserveaspectratio="none" x="0" y="30"> <use href="#smiley" /> </svg> </svg> path { fill: yellow; stroke: black; stroke-width: 8px; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; } rect:hover, rect:active { outline: 1px solid red; } syntax preserveaspectratio="<align> [<meetorslice>]" its value is made of one or two keywords: a required alignment value and an optional "meet or slice" reference as described below: alignment value the alignment valu...
...scale the graphic content of the given element non-uniformly if necessary such that the element's bounding box exactly matches the viewport rectangle. ...
... element's viewbox with the maximum y value of the viewport. xmaxymax - force uniform scaling. align the <min-x>+<width> of the element's viewbox with the maximum x value of the viewport. align the <min-y>+<height> of the element's viewbox with the maximum y value of the viewport. ...
SVG Attribute reference - SVG: Scalable Vector Graphics
Web › SVG › Attribute
svg elements can be modified using attributes that specify details about exactly how the element should be handled or rendered. below is a list of all of the attributes available in svg along with links to reference documentation to help you learn which elements support them and how they work. ...
... svg elements can be modified using attributes that specify details about exactly how the element should be handled or rendered. below is a list of all of the attributes available in svg along with links to reference documentation to help you learn which elements support them and how they work. ...
...unitlength 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 refx refy rel rendering-intent repeatcount repeatdur requiredextensions requiredfeatures restart resul...
...rsor, direction, display, dominant-baseline, enable-background, fill, fill-opacity, fill-rule, filter, flood-color, flood-opacity, font-family, font-size, font-size-adjust, font-stretch, font-style, font-variant, font-weight, glyph-orientation-horizontal, glyph-orientation-vertical, image-rendering, kerning, letter-spacing, lighting-color, marker-end, marker-mid, marker-start, mask, opacity, overflow, pointer-events, shape-rendering, stop-color, stop-opacity, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, text-decoration, text-rendering, transform, transform-origin, unicode-bidi, vector-effect, visibility, word-spacing, writing-mode filters attributes filter primitive attributes height, result, wid...
<a> - SVG: Scalable Vector Graphics
Web › SVG › Element › a
ink around a text --> <a href="/docs/web/svg/element/text"> <text x="50" y="90" text-anchor="middle"> &lt;circle&gt; </text> </a> </svg> /* as svg does not provide a default visual style for links, it's considered best practice to add some */ @namespace svg url(http://www.w3.org/2000/svg); /* necessary to select only svg <a> elements, and not also html’s. see warning below */ svg|a:link, svg|a:visited { cursor: pointer; } svg|a text, text svg|a { fill: blue; /* even for text, svg uses fill over color */ text-decoration: underline; } svg|a:hover, svg|a:active { outline: dotted 1px blue; } since this element shares its tag name with html's <a> element, selecting a with css or queryselector may apply to the wrong kind of element. try the @namespace rul...
...e. value type: <string> ; default value: none; animatable: no href the url or url fragment the hyperlink points to. value type: <url> ; default value: none; animatable: yes hreflang the human language of the url or url fragment that the hyperlink points to. value type: <string> ; default value: none; animatable: yes ping 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. for a more widely-supported feature addressing the same use cases, see navigator.sendbeacon(). value type: <list-of-urls> ; default value: none; animatable: no referrerpolicy which referrer to send when fetching the url. value type: no-referrer|no-referrer-when-downgrade|same-or...
...-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility xlink attributes most notably: xlink:title aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
...ine, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriescontainer elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> specifications specification status comment scalable vector graphi...
Getting started - SVG: Scalable Vector Graphics
« previousnext » a simple example let us dive straight in with a simple example. take a look at the following code. <svg version="1.1" baseprofile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="100%" fill="red" /> <circle cx="150" cy="100" r="80" fill="green" /> <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">svg</text> </svg> copy the code and paste it in a file demo1.svg. then open the file in firefox. it will render as shown in the following screenshot. ...
...> <rect width="100%" height="100%" fill="red" /> <circle cx="150" cy="100" r="80" fill="green" /> <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">svg</text> </svg> copy the code and paste it in a file demo1.svg. then open the file in firefox. it will render as shown in the following screenshot. (firefox users: click here) the rendering process involves the following: we start with the <svg> root element: a doctype declaration as known from (x)html should be left off because dtd based svg validation leads to more problems than it solves before svg 2, to identify the version of the svg for other types of validation the version and baseprofile attributes should always be used instead. both version and baseprofile attributes are deprecated in svg...
...ement technologies can be implemented for browsers which normally can't process svg. see this dedicated article which deals with the topic in-depth. how svg handles sizes and units will be explained on the next page. svg file types svg files come in two flavors. normal svg files are simple text files containing svg markup. the recommended filename extension for these files is ".svg" (all lowercase). due to the potentially massive size svg files can reach when used for some applications (e.g., geographical applications), the svg specification also allows for gzip-compressed svg files. the recommended filename extension for these files is ".svgz" (all lowercase). unfortunately, it is very problematic to get gzip-compressed svg files to work reliably across all svg capable user agents ...
... a word on webservers now that you have an idea of how to create basic svg files, the next stage is to upload them to a webserver. there are some gotchas at this stage though. ...
SVG Filters Tutorial - SVG: Scalable Vector Graphics
one of these primitives is the fegaussianblur. the keyword sourcealpha identifies the input for this primitive, is in this case input 'in'. the amount of blur to be applied is done using the stddeviation attribute. ...
...ects or even merging the results of different filters. with the filter element <filter> it is possible to add these effects and later on attach them to an object. filters act like layers. when creating them, try applying and testing the effect step by step. this element has different attributes that help us create the clipping region. between the filter tags, we can define the primitives that allow us to implement the desired effect. one of these primitives is the fegaussianblur. the keyword sourcealpha identifies the input for this primitive, is in this case input 'in'. the amount of blur to be applied is done using the stddeviation attribute. svg filter example <defs> <filter id="drop-shadow"> <fegaussianblur in="sourcealpha" stddeviation="3"/> </filter> </defs> <g id="ghost" sty...
...ce the desire rendering. by adding feoffset and result, the effect layer is defined <result> attribute is a reference that can be use later. it is quite different to an xml id and only can be referenced within the actual filter. <feoffset> primitive has the blur result from the gaussian blur. ...
...ring. by adding feoffset and result, the effect layer is defined <result> attribute is a reference that can be use later. it is quite different to an xml id and only can be referenced within the actual filter. <feoffset> primitive has the blur result from the gaussian blur. ...
SVG In HTML Introduction - SVG: Scalable Vector Graphics
overview this article and its associated example shows how to use inline svg to provide a background picture for a form. it shows how javascript and css can be used to manipulate the picture in the same way you would script regular html. ...
...e in the svg namespace. the element contains a gradient and two shapes filled with the gradient. the gradient color stops have their colors set by css. when the user enters something incorrect into the form, the script sets the invalid attribute on the <body>, and a style rule changes the gradient end-stop color to red. ...
...very simple and performs very well the picture dynamically sizes itself to the required size in an intelligent way we can have declarative style rules applying to both html and svg the same script manipulates both html and svg the document is entirely standards-based to add a linked image with dom methods to an embedded svg element, one has to use setattributens to set href. like in the following example: var img = document.createelementns("http://www.w3.org/2000/svg", "image"); img.setattributens("http://www.w3.org/1999/xlink", "xlink:href", "move.png"); details the viewbox attribute establishes a logical coordinate system which the svg picture's coordinates are relative to. in this case our picture is laid out in a 100 by 100 viewport. the preserveaspectratio attribute speci...
... details the viewbox attribute establishes a logical coordinate system which the svg picture's coordinates are relative to. in this case our picture is laid out in a 100 by 100 viewport. the preserveaspectratio attribute specifies that the aspect ratio must be preserved by centering the picture in the available size, sizing to the maximum of the height or width and then cutting off any overflow. the style attribute pins the svg element to the background of the form. related links another svg in html example: a swarm of motes working example that works in both mozilla and in internet explorer with adobe's svg viewer installed. (for inline svg to work in both firefox and internet explorer it is necessary to serve documents with a different content-type to each browser. for this reas...
Texts - SVG: Scalable Vector Graphics
Web › SVG › Tutorial › Texts
g 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 refer to gradients or patterns, which makes simple coloring text in svg very powerful compared to css 2.1. setting font properties an essential part of a text is the font in which...
...zed with the fill attribute and given a stroke with the stroke attribute. both may also refer to gradients or patterns, which makes simple coloring text in svg very powerful compared to css 2.1. setting font properties an essential part of a text is the font in which it is displayed. svg offers a set of attributes, many similar to their css counterparts, to enable font selection. each of the following properties can be set as an attribute or via a css declaration: font-family, font-style, font-weight, font-variant, font-stretch, font-size, font-size-adjust, kerning, letter-spacing, word-spacing and text-decoration. other text-related elements tspan this element is used to mark up sub-portions of a larger text. it must be a child of a text element or another tspan element. a typical useca...
...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. dx start drawing the text with a horizontal offset dx from the default current position. here, too, you may provide a list of values tha...
...e characters, hence piling up the offset over time. likewise, there are y and dy for vertical displacement. rotate rotate all characters by this degree. a list of numbers makes each character rotate to its respective value, with remaining characters rotating according to the last value. textlength this is a more obscure attribute giving the calculated length of the string. it is meant to allow the rendering engine to fine-tune the positions of the glyphs when its own measured text length doesn't meet the one provided here. textpath this element fetches via its xlink:href attribute an arbitrary path and aligns the characters, that it encircles, along this path: <path id="my_path" d="m 20,20 c 80,60 100,40 120,20" fill="transparent" /> <text> <textpath xmlns:xlink="http://www.w3.or...
Using templates and slots - Web Components
t (which is well-supported in modern browsers). this element and its contents are not rendered in the dom, but it can still be referenced using javascript. let's look at a trivial quick example: <template id="my-paragraph"> <p>my paragraph</p> </template> this won't appear in your page until you grab a reference to it with javascript and then append it to the dom, using something like the following: let template = document.getelementbyid('my-paragraph'); let templatecontent = template.content; document.body.appendchild(templatecontent); although trivial, you can already start to see how this could be useful. using templates with web components templates are useful on their own, but they work even better with web components. let's define a web component that uses our template as the c...
... bit of text inside it, meaning that at the moment it is even less useful than a regular paragraph! we can make it possible to display different text in each element instance in a nice declarative way using the <slot> element. this has more limited support than <template>, available since chrome 53, opera 40, safari 10, firefox 59, and edge 79. slots are identified by their name attribute, and allow you to define placeholders in your template that can be filled with any markup fragment you want when the element is used in the markup. so, if we want to add a slot into our trivial example, we could update our template's paragraph element like this: <p><slot name="my-text">my default text</slot></p> if the slot's content isn't defined when the element is included in the markup, or if the bro...
... note: an unnamed <slot> will be filled with all of the custom element's top-level child nodes that do not have the slot attribute. this includes text nodes. and that's it for our trivial example. if you want to play with it some more, you can find it on github (see it running live also). a more involved example to finish off the article, let's look at something a little less trivial. ...
...ore css for the <dl>, <dt>, and <dd> elements in our doc: dl { margin-left: 6px; } dt { font-weight: bold; color: #217ac0; font-size: 110% } dt { font-family: consolas, "liberation mono", courier } dd { margin-left: 16px } body { margin-top: 47px } result finally let’s put all the snippets together and see what the rendered result looks like. screenshotlive sample notice the following points about this rendered result: even though the instances of the <element-details> element in the document do not directly use the <details> element, they get rendered using <details> because the shadow root causes them to get populated with that. within the rendered <details> output, the content in the <element-details> elements fills the named slots from the shadow root. in other word...
Web Components
concepts and usage as developers, we all know that reusing code as much as possible is a good idea. this has traditionally not been so easy for custom markup structures — think of the complex html (and associated style and script) you've sometimes had to write to render custom ui controls, and how using them multiple times can turn your page into a mess if you are not careful. ...
...rols, and how using them multiple times can turn your page into a mess if you are not careful. web components aims to solve such problems — it consists of three main technologies, which can be used together to create versatile custom elements with encapsulated functionality that can be reused wherever you like without fear of code collisions. custom elements: a set of javascript apis that allow you to define custom elements and their behaviour, which can then be used as desired in your user interface. shadow dom: a set of javascript apis for attaching an encapsulated "shadow" dom tree to an element — which is rendered separately from the main document dom — and controlling associated functionality. in this way, you can keep an element's features private, so they can be scripted and...
...nt's dom. disconnectedcallback: invoked when the custom element is disconnected from the document's dom. adoptedcallback: invoked when the custom element is moved to a new document. attributechangedcallback: invoked when one of the custom element's attributes is added, removed, or changed. extensions for creating custom built-in elements the is global html attribute: allows you to specify that a standard html element should behave like a registered custom built-in element. the "is" option of the document.createelement() method: allows you to create an instance of a standard html element that behaves like a given registered custom built-in element. css pseudo-classes pseudo-classes relating specifically to custom elements: :defined: matches any element t...
...ltemplateelement. <slot> a placeholder inside a web component that you can fill with your own markup, which lets you create separate dom trees and present them together. the associated dom interface is htmlslotelement. the slot global html attribute assigns a slot in a shadow dom shadow tree to an element. slotable a mixin implemented by both element and text nodes, defining features that allow them to become the contents of an <slot> element. the mixin defines one attribute, slotable.assignedslot, which returns a reference to the slot the node is inserted in. element extensions extensions to the element interface related to slots: element.slot: returns the name of the shadow dom slot attached to the element. css pseudo-elements pseudo-elements relating specifically to sl...
An Overview - XSLT: Extensible Stylesheet Language Transformations
an xslt stylesheet is an xml document. ...
...ficult to read, there is a standard mechanism for assigning a shorthand name to the namespace in the stylesheet heading. thus a full example of the opening stylesheet element might look like this. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/xsl/transform" version="1.0"> the xmlns pseudo-attribute maps the shorthand name xsl onto the full namespace for use throughout the document that follows. thus the stylesheet element above is prefixed with xsl:. although xsl is the conventionally used shorthand name (called the prefix), it is not mandatory and it is quite possible to choose a different one. the examples in this article all assume the use of the xsl prefix. all xslt transformations are performed on trees, not documents. the xslt transformation engine, called the processor, doe...
...he tree consists of a hierarchical framework of nodes. it can be made up of seven different types of nodes: the single root node, element nodes, text nodes, attribute nodes, comment nodes, processing instruction nodes, and namespace nodes. at the top of the tree is the root node. the root node does not correspond to any individual part of the xml document: it represents the document as whole. below the root node are its children, which can be elements, comments, processing instructions and so on. some of those children may also have children. and this can continue for several levels. there are certain constraints on which type of nodes can occur where: for example, text nodes can have no children. the result of the processor's action is also a tree. netscape uses this tree to render the c...
...name implies, xpath defines a "path" the processor must take through the tree to arrive at the desired node. this path consists of xpath-specific expressions to be evaluated, expressions which may include a number of conditions to be matched, a way of associating nodes, and/or an indication of directionality within the tree. a fuller description of the parts of xpath most commonly used in xslt follows in the reference section. potential conflicts in template matching are resolved by using a set of cascading precedence rules. in general, a more specific template rule takes precedence over a less specific one and, other things being equal, a template rule that appears later in the document takes precedence over one that appears earlier. stylesheets can be attached to an xml document via a pr...
Converting WebAssembly text format to wasm - WebAssembly
it about how it works, and how to use available tools to convert text format files to the .wasm assembly format. note: text format files are usually saved with a .wat extension. historically, a .wast extension was also used, however that's now used for the scripting language used by the webassembly testsuite. a first look at the text format let’s look at a simple example of this — the following program imports a function called imported_func from a module called imports, and exports a function called exported_func: (module (func $i (import "imports" "imported_func") (param i32)) (func (export "exported_func") i32.const 42 call $i ) ) the webassembly function exported_func is exported for use in our environment (e.g. the web app in which we are using our webassembly mo...
...y of the above listing inside a text file; call it simple.wat. we need to assemble this textual representation into the assembly language the browser actually reads before we can use it. to do this, we can use the wabt tool, which includes compilers to convert between webassembly’s text representation and wasm, and vice versa, plus more besides. ...
...ch includes compilers to convert between webassembly’s text representation and wasm, and vice versa, plus more besides. go to https://github.com/webassembly/wabt — follow the instructions on this page to set up the tool. once you’ve got the tool built, add the /wabt/out/clang/debug directory to your system path. next, execute the wat2wasm program, passing it the path to the input file, followed by an -o parameter, followed by the path to the output file: wat2wasm simple.wat -o simple.wasm this will convert the wasm into a file called simple.wasm, which contains the .wasm assembly code. note: 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...
...onvert 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: ...
Interacting with page scripts - Archive of obsolete content
clonedcontentscriptobject.greeting); }, false); var fails = document.getelementbyid("fails"); fails.addeventlistener("click", function() { alert(assignedcontentscriptobject.greeting); }, false); </script> </body> </html> if you run the example, clicking "i will work" displays the value of "greeting" in an alert. clicking "i will not work" fails, and the following message is logged: permission denied to access property 'greeting' expose functions to page scripts the structured clone algorithm is a bit more powerful than simple json serialization, but not much: in particular, functions aren't cloned. this means that you can't expose a function to a page script using cloneinto(), and if you clone an object into the page script scope, its methods will n...
...eventually. communicating with page scripts there are two different ways a content script can communicate with a page script: using the dom postmessage() api using custom dom events using the dom postmessage api note that before firefox 31 code in content scripts can't use window to access postmessage() and addeventlistener() and instead must use document.defaultview. see the section below on using postmessage() before firefox 31. you can communicate between the content script and page scripts using window.postmessage(). content script to page script suppose we have a page called "listen.html" hosted at "my-domain.org", and we want to send messages from the add-on to a script embedded in that page. in the main add-on code, we have a page-mod that attaches the content script "t...
... finally, "listen.html" uses window.addeventlistener() to listen for messages from the content script: <!doctype html> <html> <head></head> <body> <script> window.addeventlistener('message', function(event) { window.alert(event.data); // message from content script }, false); </script> </body> </html> page script to content scri...
Working with Events - Archive of obsolete content
window might emit both open and close events. the list of valid event types is specific to an event emitter and is included with its documentation. listener: the listener itself. this is a function which will be called whenever the event occurs. the arguments that will be passed to the listener are specific to an event type and are documented with the event emitter. for example, the following add-on registers a listener with the tabs module to listen for the ready event, and logs a string to the console reporting the event: var tabs = require("sdk/tabs"); tabs.on("ready", function () { console.log("tab loaded"); }); it is not possible to enumerate the set of listeners for a given event. the value of this in the listener function is the object that emitted the event. listeni...
...ns object passed to the constructor typically defines properties whose names are the names of supported event types prefixed with "on": for example, "onopen", "onready" and so on. then in the constructor you can assign a listener function to this property as an alternative to calling the object's on() method. for example: the actionbutton object emits an event when the button is clicked. the following add-on creates a button and assigns a listener to the onclick property of the options object supplied to the button's constructor. the listener loads https://developer.mozilla.org/: require("sdk/ui/button/action").actionbutton({ id: "visit-mozilla", label: "visit mozilla", icon: "./icon-16.png", onclick: function() { require("sdk/tabs").open("https://developer.mozilla.org/"); } ...
... mozilla", icon: "./icon-16.png" }); button.on("click", function() { require("sdk/tabs").open("https://developer.mozilla.org/"); }); removing event listeners event listeners can be removed by calling removelistener(type, listener), supplying the type of event and the listener to remove. the listener must have been previously been added using one of the methods described above. in the following add-on, we add two listeners to the tabs module's ready event. one of the handler functions removes the listener again. then we open two tabs. var tabs = require("sdk/tabs"); function listener1() { console.log("listener 1"); tabs.removelistener("ready", listener1); } function listener2() { console.log("listener 2"); } tabs.on("ready", listener1); tabs.on("ready", listener2); tabs.o...
context-menu - Archive of obsolete content
context that matches the target url. context menu items are displayed in the order created or in the case of sub menus the order added to the sub menu. menu items for each add-on will be grouped together automatically. if the total number of menu items in the main context menu from all add-ons exceeds a certain number (normally 10 but configurable with the extensions.addon-sdk.context-menu.overflowthreshold preference) all of the menu items will instead appear in an overflow menu to avoid making the context menu too large. specifying contexts as its name implies, the context menu should be reserved for the occurrence of specific contexts. contexts can be related to page content or the page itself, but they should never be external to the page. for example, a good use of the menu would be...
...he node argument passed to the "context" event will not always match the type specified in selectorcontext. selectorcontext will match if the menu is invoked on the node specified or any descendant of that node, but the "context" event handler is passed the actual node on which the menu was invoked. ...
...ject properties: property description documenttype the mime type of the document the menu was invoked in. e.g. text/html for html pages, application/xhtml+xml for xhtml, or image/jpeg if viewing an image directly. documenturl the url of the document the menu was invoked in. targetname the name of the dom element that the menu was invoked on, in lower-case. targetid the id attribute of the element that the menu was invoked on, or null if not set. iseditable true if the menu was invoked in an editable element, and that element isn't disabled or read-only. this includes non-input elements with the contenteditable attribute set to true. selectiontext the current selection as a text string, or null. if the me...
content/worker - Archive of obsolete content
that will registered as a listener to a 'message' events. onerror function functions that will registered as a listener to an 'error' events. worker worker is composed from the eventemitter trait, therefore instances of worker and their descendants expose all the public properties exposed by eventemitter along with additional public properties that are listed below. methods postmessage(data) asynchronously emits "message" events in the enclosed worker, where content script was loaded. parameters data : number,string,json the data to send. must be stringifiable to json. destroy() destroy the worker by removing the content script from the page and removing all registered listeners. a detach event is fired just before removal. properties port object...
...ds postmessage(data) asynchronously emits "message" events in the enclosed worker, where content script was loaded. parameters data : number,string,json the data to send. must be stringifiable to json. destroy() destroy the worker by removing the content script from the page and removing all registered listeners. a detach event is fired just before removal. properties port object that allows you to: send customized messages to the worker using the port.emit function receive events from the worker using the port.on function url the url of the content. tab if this worker is attached to a content document, returns the related tab. events message this event allows the content worker to receive messages from its associated content scripts. calling the self.postmessage() funct...
... arguments error : the event listener is passed a single argument which is an error object. detach this event is emitted when the document associated with this worker is unloaded or the worker's destroy() method is called. ...
ui/button/action - Archive of obsolete content
e updated across all windows and tabs. but sometimes you want a button attached to one window (or tab) to have a different state to a button attached to a different window (or tab). that's what state() is for. to set a button's properties for a specific window or tab, call state(), passing it the window or tab you want the property to apply to, and the property value to set. a special shortcut allows you to pass the string "window" or "tab" to select the currently active window or tab. for example, if you have a button like this: var { actionbutton } = require('sdk/ui/button/action'); var button = actionbutton({ id: "my-button", label: "default", icon: "./firefox-16.png" }); you can change its label for only the currently active window like this: button.state("window", { "label"...
...if a property value for a node in the tree has not been set explicitly using state(), then it inherits its value from the next level up. so if you have one window containing two tabs, and have set the button's label only for tab a, then tab b will inherit label's value from the window, and changing the value for the w...
...if a property value for a node in the tree has not been set explicitly using state(), then it inherits its value from the next level up. so if you have one window containing two tabs, and have set the button's label only for tab a, then tab b will inherit label's value from the window, and changing the value for the window will implicitly change the value ...
ui/button/toggle - Archive of obsolete content
e updated across all windows and tabs. but sometimes you want a button attached to one window (or tab) to have a different state to a button attached to a different window (or tab). that's what state() is for. to set a button's properties for a specific window or tab, call state(), passing it the window or tab you want the property to apply to, and the property value to set. a special shortcut allows you to pass the string "window" or "tab" to select the currently active window or tab. for example, if you have a button like this: var { togglebutton } = require('sdk/ui/button/toggle'); var button = togglebutton({ id: "my-button", label: "default", icon: "./firefox-16.png" }); you can change its label for only the currently active window like this: button.state("window", { "label"...
...if a property value for a node in the tree has not been set explicitly using state(), then it inherits its value from the next level up. so if you have one window containing two tabs, and have set the button's label only for tab a, then tab b will inherit label's value from the window, and changing the value for the w...
...if a property value for a node in the tree has not been set explicitly using state(), then it inherits its value from the next level up. so if you have one window containing two tabs, and have set the button's label only for tab a, then tab b will inherit label's value from the window, and changing the value for the window will implicitly change the value ...
ui/toolbar - Archive of obsolete content
frame"); var frame = new frame({ url: "./frame.html" }); var toolbar = toolbar({ title: "my toolbar", items: [frame] }); toolbar.on("show", showing); toolbar.on("hide", hiding); function showing(e) { console.log("showing: " + e.title); } function hiding(e) { console.log("hiding: " + e.title); } parameters event : string the name of the event to listen to. toolbar supports the following events: attach, detach, show, and hide. listener : function the listener function. this may be passed arguments, depending on the particular event. once(event, listener) assign a listener to the first occurrence only of an event emitted by the toolbar. toolbar supports the following events: attach, detach, show, and hide. the listener is automatically removed after the first time the event...
...e"); var frame = new frame({ url: "./frame.html" }); var toolbar = toolbar({ title: "my toolbar", items: [frame] }); toolbar.once("show", showing); toolbar.once("hide", hiding); function showing(e) { console.log("showing: " + e.title); } function hiding(e) { console.log("hiding: " + e.title); } parameters event : string the name of the event to listen to. toolbar supports the following events: attach, detach, show, and hide. listener : function the listener function. this may be passed arguments, depending on the particular event. removelistener(event, listener) removes an event listener. for example, this code is equivalent to once(): var { toolbar } = require("sdk/ui/toolbar"); var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" });...
...le: "my toolbar", items: [frame] }); toolbar.on("show", showing); toolbar.on("hide", hiding); function showing(e) { console.log("showing: " + e.title); toolbar.removelistener("show", showing); } function hiding(e) { console.log("hiding: " + e.title); toolbar.removelistener("hide", hiding); } parameters event : string the event the listener is listening for. toolbar supports the following events: attach, detach, show, and hide. listener : function the listener to remove. off(event, listener) this function is an alias for removelistener(). parameters event : string the event the listener is listening for. toolbar supports the following events: attach, detach, show, and hide. listener : function the listener to remove. destroy() destroys the toolbar. after calling this...
window/utils - Archive of obsolete content
argument and an optional hash of options as its second argument. var { open } = require('sdk/window/utils'); var window = open('data:text/html,hello window'); this function wraps nsiwindowwatcher.openwindow. parameters uri : string uri of the document to be loaded into the window. only chrome, resource, and data schemes are accepted. options : object options for the function, with the following properties: name type parent nsidomwindow parent for the new window. optional, defaults to null. name string name that is assigned to the window. optional, defaults to null. features object map of features to set for the window, defined like this: { width: 10, height: 15, chrome: true }. see the window.open features d...
...}); args object extra argument(s) to be attached to the new window as the window.arguments property. returns nsidomwindow opendialog(options) opens a top level window and returns its nsidomwindow representation. this is the same as open, but you can supply more features. it wraps window.opendialog. parameters options : object options for the function, with the following properties: name type url string uri of the document to be loaded into the window. defaults to "chrome://browser/content/browser.xul". name string optional name that is assigned to the window. defaults to "_blank". features string map of features to set for the window, defined like: { width: 10, height: 15, chrome: true }.
...its possible values are the same as those expected by that function. in particular: null: get all window types navigator:browser: get "normal" browser windows devtools:scratchpad: get scratchpad windows navigator:view-source: get view source windows if you're not also passing options, you can omit this, and it's the same as passing null. options : object options object containing the following property: name type includeprivate boolean whether to include private windows. defaults to false. the add-on must also have opted into private windows for this to have an effect. returns array: array of nsidomwindow instances. isdocumentloaded(window) check if the given window's document is completely loaded. this means that its "load" event has b...
jpm-mobile - Archive of obsolete content
you can use jpm and jpm-mobile for firefox 38 and onwards. this article is the reference for jpm-mobile. the node-based replacement for cfx --force-mobile. enables you to run and test add-ons for firefox mobile (aka fennec). jpm usage is: jpm-mobile [command] [options] jpm supports the following global options: -h, --help - show a help message and exit -v, --version - print the jpm version number installation jpm-mobile is distributed using the node package manager npm, so to get jpm-mobile you need to have npm installed, if you haven't already. 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 mi...
...h other sdk users in #jetpack on mozilla's irc network. command reference there are currently two jpm commands: jpm-mobile run launch an instance of firefox with your add-on installed. jpm-mobile test runs your add-on's unit tests. jpm-mobile run this command runs a new instance of firefox with the add-on installed: jpm-mobile run jpm-mobile run accepts the following options: --adb /path/to/adb provides the path to adb. -b --binary binary use the package name of firefox specified in binary. jpm-mobile run -b fennec you can get the package name by following command. $ adb shell pm list packages | grep org.mozilla package:org.mozilla.firefox $ jpm-mobile run -b firefox # the package name is firefox -...
...y following command. $ adb shell pm list packages | grep org.mozilla package:org.mozilla.firefox $ jpm-mobile run -b firefox # the package name is firefox -v --verbose verbose operation. jpm-mobile test jpm-mobile test see the tutorial on unit testing and the reference documentation for the assert module for more details on this. jpm-mobile test accepts the following options: --adb /path/to/adb provides the path to adb. -b --binary binary use the package name of firefox specified in binary. jpm-mobile test -b fennec you can get the package name by following command. $ adb shell pm list packages | grep org.mozilla package:org.mozilla.firefox $ jpm-mobile run -b firefox # the package name is firefox -...
Creating annotations - Archive of obsolete content
ns: the url for the page, the id attribute value, and the text content of the page element. ...
... function toggleactivation() { annotatorison = !annotatorison; activateselectors(); return annotatorison; } we'll be using this url in all our screenshots. because cfx run doesn't preserve browsing history, if you want to play along it's worth taking a note of the url. save the file and execute cfx run again. activate the annotator by clicking the widget and load a page: the screenshot below uses http://blog.mozilla.com/addons/2011/02/04/ overview-amo-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...
... textarea.value = ''; } }; self.on('message', function() { var textarea = document.getelementbyid('annotation-box'); textarea.value = ''; textarea.focus(); }); save this inside data/editor as annotation-editor.js. updating main.js again now we'll update main.js again to create the editor and use it. ...
Getting Started (jpm) - Archive of obsolete content
lue or accepted the default for these properties, you'll be shown the complete contents of "package.json" and asked to accept it. implementing the add-on now you can write the add-on's code. unless you've changed the value of "entry point" ("main" in package.json), this goes in "index.js" file in the root of your add-on. this file was created for you in the previous step. ...
...uccessfully created xpi at /path/to/my-addon/@my-addon-0.0.1.xpi to test that this worked, try installing the xpi file in your own firefox installation. you can do this by pressing the ctrl+o key combination (cmd+o on mac) from within firefox, or selecting the "open" item from firefox's "file" menu. this will bring up a file selection dialog: navigate to the "@my-addon.xpi" file, open it and follow the prompts to install the add-on. note that firefox by default requires add-ons, even locally developed ones, to be signed. after installation they'll show up disabled in the list of installed add-ons, noting the missing signature. during development, or if you don't plan to distribute, you can open about:config and set xpinstall.signatures.required to false to run it unsigned. this setting app...
...can try it out jpm xpi to package the add-on into an xpi file for distribution these are the three main commands you'll use when developing sdk add-ons. there's comprehensive reference documentation covering all the commands you can use and all the options they take. the add-on code itself uses two sdk modules, action button and tabs. there's reference documentation for all the high-level and low-level apis in the sdk. what's next? to get a feel for some of the things you can do with the sdk apis, try working through some of the tutorials. ...
Listening for Load and Unload - Archive of obsolete content
if your add-on exports a function called main(), then that function will be called whenever the add-on is loaded, and it will be passed an object containing a string describing the reason it was loaded as well as any arguments passed to it. if your add-on exports a function called onunload(), then that function will be called when the add-on is unloaded, and it will be passed a string describing the reason it was unloaded. you don't have to use exports.main() or exports.onunload(). you can just place your add-on's code at the top level instead of wrapping it in a function assigned to exports.main(). it will be loaded in the same circumstances, but you won't get access to the load/unload reason or arguments. ...
...d main(), that function will be called immediately after the overall main.js is evaluated, and after all top-level require() statements have run (so generally after all dependent modules have been loaded). exports.main = function (options, callbacks) {}; options is an object describing the parameters with which your add-on was loaded. ...
...ich your add-on was loaded. options.loadreason options.loadreason is one of the following strings describing the reason your add-on was loaded: install enable startup upgrade downgrade exports.onunload() if your add-on exports a function called onunload(), that function will be called when the add-on is unloaded. exports.onunload = function (reason) {}; reason reason is one of the following strings describing the reason your add-on was unloaded: uninstall disable shutdown upgrade downgrade if your add-on is disabled, then uninstalled, your onunload listener will only be called once, with the disable reason. this happens because disabling an add-on also disables its onunload listeners, so there is no listener remaining when the add-on is uninstalled. for more, see bug 627432, ...
Logging - Archive of obsolete content
to follow this tutorial you'll need to have learned the basics of jpm. the dom console object is useful for debugging javascript. because dom objects aren't available to the main add-on code, the sdk provides its own global console object with most of the same methods as the dom console, including methods to log error, warning, or informational messages. you don't have to require() anything to get access to the console. it is automatically made available to you. ...
...ages. you don't have to require() anything to get access to the console. it is automatically made available to you. ...
... console in content scripts you can use the console in content scripts as well as in your main add-on code. ...
Dialogs and Prompts - Archive of obsolete content
dows dialogs in mozilla whenever you want to create a dialog in your application, use <dialog> (instead of usual <window>) as root element in the xul file. this will: handle a few keyboard events (enter/esc and more), which is good for keyboard accessibility. add ok and cancel buttons in an order that is consistent with os default (but the button set and layout is highly customizable, see below). simple dialog code the following xul code defines a simple dialog with two buttons, ok and cancel (buttons="accept,cancel" attribute on dialog). <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/global.css" type="text/css"?> <dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="..." title="..." buttons="accept,cancel" ondialogaccept="return on...
...xtra2 — two buttons without any predefined labels or meaning. extra2 is positioned at the left side of the dialog (by default). for each of these buttons you can set their label, accesskey and oncommand handler by adding buttonlabel<buttonname>, buttonaccesskey<buttonname> and ondialog<buttonname> attributes to the dialog element. ...
...nd cancel buttons from script, use this: // disable the ok and cancel btns document.documentelement.getbutton("accept").disabled = true; document.documentelement.getbutton("cancel").disabled = true; links dialog.xml — xbl bindings for <dialog> and <dialogheader> elements. passing parameter to a dialog and getting return values from it. passing arguments and displaying a dialog the following code demonstrates how to pass custom arguments to a dialog, process those arguments in the dialog, and return user-modified arguments to the caller. the code to open a dialog named mydialog.xul and pass it arguments: var params = {inn:{name:"foo", description:"bar", enabled:true}, out:null}; window.opendialog("chrome://myext/content/mydialog.xul", "", "chrome, dialog, modal, resizable...
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. this example is what the final xul overlay could look like, assuming a javascript overlay titled overlay.js: <?xml version="1.0" encoding="utf-8"?> <overlay id="htmltip-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml"> <script type="application/x-javascript" src="overlay.js"/> <popup id="contentareacontextmenu"> <menuitem id="htmltip1" label="foo1" onmouseover="htmltip.onmousetooltip(event)" tooltip="myhtmltip" /> <menuitem id="htmltip...
...our customized tooltiphtml attribute for each element can be set at any time. var htmltip = { onload: function() { //at any point you can save an html string to a xul attribute for later injection into the tooltip document.getelementbyid("htmltip1").setattribute("tooltiphtml", "<font color='red'>red foo</font>") document.getelementbyid("htmltip2").setattribute...
...tml) .parsefragment(txt, false, null, div); //attach the dom object to the html div element div.appendchild(injecthtml); } } window.addeventlistener('load', htmltip.onload, false); in the xul overlay, xmlns:html is used to enable html tags to be used inside the xul. our enhanced xul tooltip is an element that is written ahead of time, and it contains an html div element whose type attribute lowers its privileges to being that content element, although it is an element of chrome. this is recommended for security reasons, especially if remote html is to be inserted. a number of menuitems have a tooltip attribute pointing to the same tooltip. that tooltip is empty now, but we will use the mouseover event to dynamically populate the tooltip (which is about to be shown) with a different mes...
JavaScript Debugger Service - Archive of obsolete content
bsolete since gecko 33 (firefox 33 / thunderbird 33 / seamonkey 2.30) 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. in firefox versions prior to gecko 33 (firefox 33 / thunderbird 33 / seamonkey 2.30), the javascript debugger service (or simply jsd) used to be an xpcom component that allows the tracking of javascript while it was being executed in the browser. however, jsd has been removed in favor of the debugger api. see the tracking bug bug 800200 for more details. snippets acquiring the service we acquire the service by calling the xpcom object. var jsd = components.classes["@mozilla.org/js/jsd/debugger-service;1"] .getservice(components.interfaces.jsdidebuggerser...
...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...
...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 }; return filter; }, we then add the filters we want. ...
On page load - Archive of obsolete content
this article is for xul/javascript developers who want to have custom code executed each time a new page is loaded in browser/mail. if you need finer control over custom code execution—for example, as documents are loading or when tabs are switched—see progress listeners. progress listeners allow extensions to be notified of events associated with documents loading in the browser and with tab switching events. progress listeners implement the nsiwebprogresslistener interface. ...
... loading or when tabs are switched—see progress listeners. progress listeners allow extensions to be notified of events associated with documents loading in the browser and with tab switching events. progress listeners implement the nsiwebprogresslistener interface. ...
...epane = document.getelementbyid("messagepane"); // mail if(messagepane){ messagepane.addeventlistener("load", function(event) { myextension.onpageload(event); }, true); } }, onpageload: function(aevent) { var doc = aevent.originaltarget; // doc is document that triggered "onload" event // do something with the loaded page. // doc.location is a location object (see below for a link). // you can use it to make your code executed on certain pages only. if(doc.location.href.search("forum") > -1) alert("a forum page is loaded"); // add event listener for page unload aevent.originaltarget.defaultview.addeventlistener("unload", function(event){ myextension.onpageunload(event); }, true); }, onpageunload: function(aevent) { // do something...
Windows - Archive of obsolete content
to perform. opening new browser windows to open a new browser window, you can simply use window.open(). however, window.open() returns a window object for content, not for the browser window itself, so you should get the chrome window first. the simplest way to do that is to use nsiwindowmediator. example window.open(); //this open a pop-up window that could be "blocked" client-side //the following code generate an error as describe in the following warning box var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var newwindow = wm.getmostrecentwindow("navigator:browser"); var b = newwindow.gbrowser; the code generate a typeerror from firefox console. in particular the components.classes is unde...
...r newwindow = wm.getmostrecentwindow("navigator:browser"); var b = newwindow.gbrowser; the code generate a typeerror from firefox console. in particular the components.classes is undefined and the components object is deprecated. it will soon be removed. draggable windows to make a window draggable by clicking on the window's contents, you can use the mousedown and mousemove events. the following code does not care which element is clicked on, simply responding to all mousedown events equally. you could improve this code by checking the event.target element and only setting the startpos if the element matches some criteria. example var startpos = null; function mousedown(event) { startpos = [event.clientx, event.clienty]; } function mousemove(event) { if (startpos) { var ne...
... var hr = document.createelementns("http://www.w3.org/1999/xhtml", "html:hr"); document.getelementbyid("id1").appendchild(hr); ...
How to convert an overlay extension to restartless - Archive of obsolete content
// and resource:// but not chrome://, everyone who learned of this new feature learned that you had to load jsm from resource:// uris and just stuck with that forever. it does still work if you don't have restartlessness to worry about, though the protocol (or scheme, or whatever term you prefer) really should be avoided at this point. the resource:// protocol actually bleeds into content which allows webpages to detect installed add-ons using the protocol, which is not particularly fantastic (just the static file contents, not any loaded script/data). step 2a: load your jsm from chrome:// now with that preface out of the way, this part is easy: drop support for firefox 3.x if you haven't already, move your jsm files to wherever you've got your chrome mapping to for your xul overlay and/or ...
...ptions. the first is to use the nsizipreader interface which permits continuing to use nsiinputstreams, etc. the second is to re-code to use xmlhttprequest. a file:// uri to the install location, or .xpi file, is available in installpath property of the bootstrap data structure passed to the startup(), shutdown(), install(), and uninstall() functions in what will be your bootstrap.js file (see below). how to get and load the data of of your add-on's files using the add-on manager api: // this is the old way of getting one of your files const myaddonid = ...; // just store a constant with your id components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getaddonbyid(myaddonid,function(addon) { var file = services.io.newuri("resource://myaddon/filename.ext",null,n...
...once you've got the machinery to load and save preferences without having to jump through the various pref type hoops the actual preferences api sends you through, loading the actual preferences file is one lin...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
e issues given in the previous section about functions remain. alternative: just assign most of the time, assigning properties will just work. someexistingobject.someproperty = "abc"; // we already demonstrated with with functions in a previous example alternative: object.defineproperty() for most objects it is possible to (re-)define properties with the object.defineproperty() api, which allows to not override values, but also lets you define getters and setters. alternative: proxy if you cannot override objects or properties easily, e.g. because the object is frozen or sealed, then creating a proxy around the object might be a viable approach. triggering event handlers sometimes scripts might want to manually trigger an event handler that is defined directly in the xul document. c...
...de values, but also lets you define getters and setters. alternative: proxy if you cannot override objects or properties easily, e.g. because the object is frozen or sealed, then creating a proxy around the object might be a viable approach. triggering event handlers sometimes scripts might want to manually trigger an event handler that is defined directly in the xul document. consider the following xul fragment throughout the rest of this section. <menuitem id="mymenu" oncommand="executesomething(); executesomethingelse();"/> <label id="mylabel" onclick="executesomething(); executesomethingelse();"/> add-on authors commonly use eval to trigger the handlers. // do not use eval(document.getelementbyid("mymenu").getattribute("oncommand")); eval(document.getelementbyid("mylabel").getattr...
... not use! eval("myaddon.phrases.word" + word + " = '" + phrase + "';"); again, this is not only unnecessarily hard to parse for a human, but may also contain security vulnerabilities if you compute the names using external data. alternative: using bracket-access to object properties object properties can always accessed using the bracket syntax: obj["property"] === obj.property hence the following will work just fine without having to resort to eval. myaddon.phrases["word" + word] = "phrase"; if there is no way around eval()... please consider creating an unprivileged sandbox and execute your code by calling evalinsandbox. did i mention that you should use native json methods to parse json data? special thanks special thanks goes to wladimir palant of adblock plus, who wrote an a...
Mozilla Documentation Roadmap - Archive of obsolete content
per.mozilla.org". secondly, there are several important articles that are very lacking in information, like the preferences system page. and finally, what we mentioned in our xpcom section: almost no documentation on xpcom components. the documentation on interfaces is very complete, but it isn't nearly as useful as the documentation that existed at xulplanet and was later taken down. xulplanet allowed you to navigate between interfaces and their related components, which makes locating components very easy. hopefully this will be corrected in the future. in the meantime, you can still navigate xulplanet using the wayback machine. mdc should be your first stop when looking for documentation. if you find it lacking or missing some piece of information, please consider adding it once you've fo...
... best search queries, but it's an invaluable resource of information. mozilla blogs several mozilla community members maintain blogs that are updated frequently, often including information on api changes, bug fixes, useful tools and future release plans. many of the tips and tricks included in this tutorial were discovered by reading these blogs. there are several useful feeds that you can follow using a feed reader, such as thunderbird. here are some important 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 ca...
... the about:mozilla newsletter is a weekly publication that includes the highlights of what is posted at planet mozilla. ...
User Notifications and Alerts - Archive of obsolete content
users will find them annoying and probably will learn to dismiss them as quickly as possible without even reading what they have to say. or they will just get rid of your add-on. ...
... 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 boxes are designed to be easily dismissed. all notifications have an additional close button, so you should take into account that it's possible that none of your custom ...
...ity issues. you should use the 2 alternatives mentioned above whenever possible. if none of those fit your needs then this is an acceptable solution. an easy way to display alerts is to include a hidden box in your overlay, which you can fill with any content you need before removing the hidden attribute so that it is displayed to the user. the best locations for this kind of box are above and below the tab browser. below is preferrable because it only cuts the bottom part of the current page, as opposed to pushing down all tabs and content. notification boxes are a good guideline to what you should aim for: thin, informative and easy to dismiss. another option is to also add a hidden box to the overlay, but use css positioning to locate it where you want. this usually means that the box wi...
Security best practices in extensions - Archive of obsolete content
other items are recommendations. the difference will be clearly flagged. this is written from the perspective of a firefox extension, but most items apply to extensions for other mozilla-based applications such as thunderbird or seamonkey. ...
...t/chrome security barrier, if for example, you want a web page to send a notification to the add-on (or vice versa). one way to do this is to use custom dom events; see interaction between privileged and non-privileged pages. regardless of where the document comes from, you can further restrict what it can do by applying properties to the document holder, known as the docshell. frame.docshell.allowimages = false; frame.docshell.allowjavascript = false; frame.docshell.allowplugins = false; there are more examples listed in the document listed above in this section. in certain circumstances you may want to run code in your extension, but you would like to give it restricted privileges. one of the best ways to do this is to use components.utils.evalinsandbox(). note that objects passed into...
...ular data format for return formats for web services. be sure to read using native json to find out the correct way to handle it. apis can't be used with self-signed certificates. remote javascript and content there are a number of ways of remote scripts being used in extensions. they can be included in content, or downloaded at intervals. non-chrome urls in chrome xul or html such as the following example are not allowed: <script type="text/javascript" src="http://mysite.greatsite.com/js/wow-content.js" /> in general, scripts that are from remote sources that run in the chrome context are not acceptable, as many times the source of the script can never be 100% guaranteed, and they are vulnerable to man-in-the-middle attacks. the only legitimate environment for remote scripts is to run...
Signing an extension - Archive of obsolete content
note: these instructions are outdated. for an extension to work in firefox it must be signed by mozilla, not by yourself. see signing and distributing your add-on. this article describes how to digitally sign your extension for firefox and thunderbird, with a code signing certificate for object signing. the following instructions also apply to a theme and other xpi files. these instructions assume you're working on mac and you've already got a valid certificate from ca. get the signing tool we use nss to sign an extension. this can be easily installed with macports. sudo port install nss export your certificate if you have your certificate in firefox, export it by following the steps below. the certificate which the author purchased from verisign was directly installed to firef...
...here's an example of verisign: nss-certutil -m -n "verisign class 3 public primary certification authority" -t "c,c,c" -d . nss-certutil -m -n "verisign class 3 public primary certification authority - g5 - verisign, inc." -t "c,c,c" -d . nss-certutil -m -n "verisign class 3 code signing 2010 ca - verisign, inc." -t "c,c,c" -d . it's all done. sign the basic usage of the signing tool is as follows: nss-signtool \ -d (path to the directory that contains your certificate database files) \ -k (your certificate nickname) \ -p (your certificate password) \ -x -z (output path/name of signed file) \ (path to your extension working directory that contains chrome directory, chrome.manifest file, install.rdf file, etc.) writing your password directly in the script is dangerous. for produ...
...pi file into the content area of firefox. on the installation dialog, you can see your organization name along with the file name. references signing a xpi - more detailed instructions including test procedures. key manager - a firefox extention that has the ability to sign xpi files. signing a firefox extension with a windows authenticode ssl certificate / key - note that some cas do not allow (or support) to divert an authenticode certificate to object signing. please check the terms of service. signing an executable with authenticode - for signing executable file (exe) ...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
the interface conventions we've come to expect from web pages. the brains and primary driving force behind this compelling new design is douglas bowman, network design manager for terra lycos, who graciously agreed to an interview and in the process shed a lot of light on what goes into a standards-based redesign. wired news redesign in a nutshell driven by xhtml 1.0 transitional and css; allows centralized control over layout and appearance for thousands of pages; simple markup allows for rapid changes to templates; average page weight dropped by almost half; page layout accomplished with simple css positioning; vastly increased accessibility without special coding or user agent detection. why did you pursue a standards-based redesign of wired news? as network design manager at ...
...rouble ensuring a consistent vertical start position of columns using floats. two column layouts using floats seemed easy. but adding a third column to the mix created too many width variables for some browsers to dynamically calculate a total. resizing the browser window often resulted in one column getting pushed to the bottom of another. using absolute positioning for left and right columns allowed the markup for each column to fall in any order. there are some technicalities in the order of our markup and some ad units that would require too much to cover here. but positioning did allow the center column to fall first in the markup. it also guarantees each column will start in the same vertical position. to be fair, i did note two disadvantages of positioning. when one or more columns i...
...e print template for stories. however, since some of our stories are broken up into 2 or 3 pages, we created a slightly altered template for print versions which pulls the entire text of the story into one (web) page. since we had a separate template to work with, we changed the media attribute of the linked print style sheet to "all", and eliminated the links to normal screen media files. this allows us to temporarily display on screen the same formatting to be used for printing that page. so what advantages does this redesign give you as a site administrator? you mean besides the fact that as designer, i can control design details on thousands of news pages with just a few files? besides the fact that the engineers can finally focus on building out the working functionality of the site ra...
Underscores in class and ID Names - Archive of obsolete content
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. ...
.... given this fact, authors who write css often attempt to employ the underscore in a similar fashion when creating class and id names. this should not be done. although underscores are, as of this writing, technically permitted in class and id names, there are many historical and practical reasons why they should be avoided. the css1 specification, published in its final form in 1996, did not allow for the use of underscores in class and id names unless they were "escaped." an escaped underscore would look something like this: p.urgent\_note {color: maroon;} this was not well supported by browsers at the time, however, and the practice has never caught on. css2, published in 1998, also forbade the use of underscores in class and id names. however, errata to the specification published in ...
...havior with regard to underscores is rather convoluted. netscape 6.x permits underscores and escaped underscores. navigator 4.x honored the restriction against underscores, and so any class or id name with an underscore will be ignored by navigator 4.x, so the associated styles will never be applied. it also ignored escaped underscores. internet explorer 4.x and 5.x for windows erroneously allowed underscores, and so were both non-conformant on this point until the errata was published. the same is true of ie4.x and 5.x for macintosh. internet explorer 6 for windows, published after the errata, permits underscores and escaped underscores. opera 3.x through 5.x does not recognize underscores or escaped underscores, and so acts the same as navigator 4.x in this regard. recommendation ...
Creating a dynamic status bar extension - Archive of obsolete content
rmation about the stock. concepts covered in the previous sample won't be reiterated here; instead, refer to the downloadable sample code or to the previous sample for further details. download the sample you can download a copy of this sample to look over, or to use as the basis for your own extension. or, if you've already got the code from the creating a status bar extension sample, 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 f...
...e use the window.addeventlistener() 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(). the following sections will examine these one by one. startup() the startup() function is called when a new browser window is opened. we end up reloading data from each of the windows once in 10 minutes - fixing this by creating a js component responsible for communication with the server is a good idea for one of the future articles startup: function() { this.refreshinformation(); window.setinterval(th...
...we need this so that we can make changes to the status bar panel itself. we then fetch the result returned by the web server into the variable ou...
cert_override.txt - Archive of obsolete content
elds fields are separated by a tab character. each line is terminated by a line feed character (unix format). ...
...aracter. each line is terminated by a line feed character (unix format). ...
...rt 443 for https (ssl) hash algorithm oid sha1-256: oid.2.16.840.1.101.3.4.2.1 (most used) sha-384: oid.2.16.840.1.101.3.4.2.2 sha-512: oid.2.16.840.1.101.3.4.2.3 certificate fingerprint using previous hash algorithm one or more characters for override type: m : allow mismatches in the hostname u : allow untrusted certs (whether it's self signed cert or a missing or invalid issuer cert) t : allow errors in the validity time, for example, for expired or not yet valid certs certificate's serial number and the issuer name as a base64 encoded string ...
Making a Mozilla installation modifiable - Archive of obsolete content
xul, xbl, javascript, and css files are all in text format and can be edited in a standard text editor, while image files are in binary gif, jpg, or png format and must be edited with an image editing program. the files are then collected into a series of jar archives, which are just zip files that contain a specially formatted "manifest" file which describes the contents of the archive so mozilla knows what to do with them. ...
...se the extracted files instead of the original jar archives. the archives are stored within the chrome subdirectory of the mozilla installation directory. use your unzip utility to extract all files in that directory with a .jar extension. make sure you extract them into the same (chrome) directory in which they are located. on unix-like operating systems with bash-like shells, you can run the following command within that directory to accomplish this task: for file in *.jar; do unzip $file; done on operating systems with dos-like shells, the following command accomplishes this task: for %file in (*.jar); do unzip %file note that there are platform-specific files — en-mac.jar, en-unix.jar, and en-win.jar — in that directory. extract only the one appropriate for your platform. after extr...
...s a bunch of complicated configuration statements in which you will find a number of urls of the form jar:resource:/chrome/something.jar!/something-else... which point to directories within the jar archives. change them so they point to the extracted files by removing the leading jar: and the part in the middle that says something.jar!. if you have perl on your system, you can do this with the following command: perl -pi.orig -e 's/(jar:)|(\/[^.\/]+\.jar!)//g' chrome.rdf installed-chrome.txt for example, to convert the url jar:resource:/chrome/comm.jar!/content/necko/, change it to resource:/chrome/content/necko/. after you make these changes, try starting the copy of mozilla you have modified. make sure you start the modified copy and not the default installation on your machine, and shut d...
Getting Started - Archive of obsolete content
for mac os x: folder_with_seamonkey/chrome/classic.jar copy classic.jar to another easily accessible folder -- classic is recommended -- extract the contents of that folder, being sure to maintain the directory structure. directories inside classic.jar is one directory, skin. skin skin simply contains another directory, classic which holds all the good stuff. skin\classic classic contains the following directories. skin\classic\communicator 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 he...
...tall-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. ...
...d open button.css in your favorite text editor. scroll down to button {. this section defines the normal button in its basic state (there is no mouse over it, it's not disabled, and it's not selected). change the background-color: to darkblue and the color: to white, and save the file. ...
Creating a Microsummary - Archive of obsolete content
r example: 174475447 fx downloads. we'll build the xslt transform sheet that converts that page into its microsummary, learn how to specify that the generator applies to that page, and find out how to make the generator available for download and installation. in each step of revising the transform sheet and other code in this tutorial, new material added will be shown in boldface so you can follow along more easily. note: if you are a web site developer, and you want to create microsummaries for pages on your site, you can write generators to do so, but a simpler and more efficient approach is to create the microsummaries on the server-side using the same tools and languages you already use to generate pages. for example, if you use php scripts to generate pages on your site, you could w...
...eb and then create a javascript link on some web page that calls firefox's window.sidebar.addmicrosummarygenerator() method to download and install the generator. ...
...aries/tutorial/sfx-generator.xml')">install the spread firefox home page microsummary!</button> clicking that button will generate a javascript error on browsers that don't support microsummaries, however, so to improve the experience for those users, we should check to see if the user is using a microsummaries-enabled browser and display an explanatory message if not. ...
In-Depth - Archive of obsolete content
this is only a list of properties which may be useful to you; it is in no way all of the mozilla specific properties available. ...
...this is only a list of properties which may be useful to you; it is in no way all of the mozilla specific properties available. ...
...be wondering, how do i know where everything is? well there is an easy way to find out - using the dom inspector. if you didn't install it when you first installed mozilla you may have to run the installer again. load mozilla and one browser window. then open the dom inspector (tools->web development->dom inspector). click file->inspect and select the browser window. what appears in a tree view below is the actual code for the interface. using this, we can figure out what objects are where, what classes/id's they have applied to them, and most importantly, which file the style is located in. click on the inspect icon and then click on the back button in the browser window. what this will do is find the code for the back button and display it in the dom inspector. selected in the tree view wi...
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
copy classic.jar to another easily accessible folder -- classic is recommended -- extract the contents of that folder, being sure to maintain the directory structure. directories inside classic.jar is one directory, skin, as well as two files, preview.png and icon.png. skin skin simply contains another directory, classic which holds all the good stuff. skin\classic classic contains the following directories. skin\classic\browser browser contains all the toolbar icons, 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 dir...
...tall-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. ...
...to the global global directory and open button.css in your favorite text editor. scroll down to "button {". this section defines the normal button in its basic state (there is no mouse over it, it's not disabled, and it's not selected). change the background-color: to darkblue and the color: to white, and save the file. repackaging jar now all you need to do is repackage a jar file with the following directory structure, using your favorite archive manager to create a zip archive: /browser/* /communicator/* /global/* /help/* /mozapps/* /contents.rdf /install.rdf /icon.png /preview.png make sure not to just zip up the my_theme parent directory since that will cause the drag and drop install in the next section to fail without error messages. once you have put the files in the zip folde...
Using microformats - Archive of obsolete content
firefox 3 implements a global microformats object that provides access to microformats. this object and its api make finding and reading microformats easy to do. loading the microformats api the microformats object is created using the new javascript script loader added to firefox 3. ...
... that match specified criteria. var nummicroformats = microformats.count(name, rootelement, options); parameters name the name of the microformat to count. rootelement required. the dom element at which to begin the search. if you want to search the entire document, specify content.document. options optional. if provided, this is a javascript object that contains zero or more of the following flags: recurseexternalframes if true, child frames are included in the search. the default is true. showhidden if true, hidden microformats are added; otherwise they're left out. the default is false. debug specify true if debug mode is in use; otherwise, specify false. the default is false. return value an integer value indicating the number of microformats that match the specif...
...specified criteria. var microformatsarray = microformats.get(name, rootelement, options, targetarray); parameters name the name of the microformat to find. rootelement required. the dom element at which to begin the search. if you want to search the entire document, specify content.document. options optional. if provided, this is a javascript object that contains zero or more of the following flags: recurseexternalframes if true, child frames that reference external content are included in the search. the default is true. showhidden if true, hidden microformats are added; otherwise they're left out. the default is false. debug specify true if debug mode is in use; otherwise, specify false. the default is false. targetarray optional. if provided, this is an array of ...
importUserCertificates - Archive of obsolete content
is certificate has the same dn as one or more certificates that already exist in the user's certificate store, the nickname associated with the certificate(s) of the same dn in the certificate store is used, and the <tt>"nicknamestring"</tt> parameter is ignored. ...
... the importusercertificates() method is used to import newly issued certificates for the user. the private key for the certificates must already reside in the user's personal private key database. ...
...es() method is used to import newly issued certificates for the user. the private key for the certificates must already reside in the user's personal private key database. the request id in the response being imported must match the request id in the associated certification request or recovery request. if the import operation succeeds, an empty string will be returned. ...
Selection - Archive of obsolete content
tions made by the user. features can get, set, and listen for selection events in html or plain text. the namespace for this api is jetpack.selection. this api currently lives in the future and must be imported for use: jetpack.future.import("selection"); getting and setting the selection the current version of jetpack.selection includes these formats: .text and .html getting the selection the following is an example of getting the selection from the user. jetpack.import.future("selection"); var textofsel = jetpack.selection.text; var htmlofsel = jetpack.selection.html; setting the selection the following is an example of getting the selection from the user. jetpack.import.future("selection"); jetpack.selection.text = 'hello'; jetpack.selection.html = '<b>hello</b>'; methods onselection(f...
...g the selection from the user. jetpack.import.future("selection"); var textofsel = jetpack.selection.text; var htmlofsel = jetpack.selection.html; setting the selection the following is an example of getting the selection from the user. jetpack.import.future("selection"); jetpack.selection.text = 'hello'; jetpack.selection.html = '<b>hello</b>'; methods onselection(func function)this method allows you to execute an event function when a selection is made. funca function to be called when the selection is made. this function receives no arguments. use jetpack.selection.*. ...
...ethods onselection(func function)this method allows you to execute an event function when a selection is made. funca function to be called when the selection is made. this function receives no arguments. use jetpack.selection.*. function adding a selection event jetpack.selection.onselection( fn ); removal of a selection event jetpack.selection.onselection.unbind( fn ); verbose example the following example will bold the html that you select. jetpack.import.future("selection"); jetpack.selection.onselection(function(){ var html = jetpack.selection.html; jetpack.selection.html = "<b>" + html + "</b>"; }); ...
Selection - Archive of obsolete content
Archive › Mozilla › Jetpack › docs › UI › Selection
tions made by the user. features can get, set, and listen for selection events in html or plain text. the namespace for this api is jetpack.selection. this api currently lives in the future and must be imported for use: jetpack.future.import("selection"); getting and setting the selection the current version of jetpack.selection includes these formats: .text and .html getting the selection the following is an example of getting the selection from the user. jetpack.import.future("selection"); var textofsel = jetpack.selection.text; var htmlofsel = jetpack.selection.html; setting the selection the following is an example of getting the selection from the user. jetpack.import.future("selection"); jetpack.selection.text = 'hello'; jetpack.selection.html = '<b>hello</b>'; methods onselection(f...
...g the selection from the user. jetpack.import.future("selection"); var textofsel = jetpack.selection.text; var htmlofsel = jetpack.selection.html; setting the selection the following is an example of getting the selection from the user. jetpack.import.future("selection"); jetpack.selection.text = 'hello'; jetpack.selection.html = '<b>hello</b>'; methods onselection(func function)this method allows you to execute an event function when a selection is made. funca function to be called when the selection is made. this function receives no arguments. use jetpack.selection.*. ...
...ethods onselection(func function)this method allows you to execute an event function when a selection is made. funca function to be called when the selection is made. this function receives no arguments. use jetpack.selection.*. function adding a selection event jetpack.selection.onselection( fn ); removal of a selection event jetpack.selection.onselection.unbind( fn ); verbose example the following example will bold the html that you select. jetpack.import.future("selection"); jetpack.selection.onselection(function(){ var html = jetpack.selection.html; jetpack.selection.html = "<b>" + html + "</b>"; }); ...
LIR - Archive of obsolete content
it is a typed assembly language. the lir instruction set is best learnt by reading nanojit/liropcode.tbl. code for manipulating lir is in nanojit/lir.h. nanojit lir instruction cheat sheet.also in pdf format see attachment. category op code code name return type featured description miscellaneous 0 start void start of a fragment 1 regfence void a register fence causes no code to be generated, but it affects register allocation so that no registers are live when it is reached. 2 skip void links code chunks. ...
...bit truncate quad to int (removes the high 32 bits) 111 i2d double convert int to double 112 ui2d double convert unsigned int to double 113 d2i integer convert double to int (no exceptions raised) 114 dasq quad 64 bit interpret the bits of a double as a quad 115 qasd double 64 bit interpret the bits of a quad as a double overflow arithmetic 116 addxovi integer add int and exit on overflow 117 subxovi integer subtract int and exit on overflow 118 mulxovi integer multiply int and exit on overflow 119 addjovi integer add int and branch on overflow 120 subjovi integer subtract int and branch on overflow 121 muljovi integer multiply int and branc...
...c 116 addxovi integer add int and exit on overflow 117 subxovi integer subtract int and exit on overflow 118 mulxovi integer multiply int and exit on overflow 119 addjovi integer add int and branch on overflow 120 subjovi integer subtract int and branch on overflow 121 muljovi integer multiply int and branch on overflow 122 addjovq quad 64 bit add quad and branch on overflow 123 subjovq quad 64 bit subtract quad and branch on overflow softfloat 124 dlo2i integer softfloat get the low 32 bits of a double as an int 125 dhi2i integer softfloat get the high 32 bits of a double as an int 126 ii2d double softfloat join two ints (1st arg is low bits, 2nd is...
Porting NSPR to Unix Platforms - Archive of obsolete content
the file suffix <tt>.mk</tt>. if the return value of <tt>uname -s</tt> is too long or ambiguous, you can modify it in <tt>mozilla/nsprpub/config/arch.mk</tt> (the makefile variable <tt>os_arch</tt>). <tt>mozilla/nsprpub/pr/include/md/_netbsd.cfg</tt> we have a program <tt>mozilla/nsprpub/pr/include/gencfg.c</tt> to help you generate partof this file. you can build the <tt>gencfg</tt> tool as follows: cd mozilla/nsprpub/pr/include gmake gencfg gencfg > foo.bar then you use the macro values in <tt>foo.bar</tt> as a basis for the <tt>_xxxos.cfg</tt> file. <tt>mozilla/nsprpub/pr/include/md/_netbsd.h</tt>: for local threads only version, the main challenge is to figure out how to define the three thread context switch macros. in particular, you need to figure out which element in the <tt>jmp...
...-force experiments. i usually print out every element in the <tt>jmp_buf</tt> and see which one is the closest to the address of a local variable (local variables are allocated on the stack). on some platforms, <tt>jmp_buf</tt> is a struct, then you should look for a struct member named <tt>sp</tt> or something similar. <tt>mozilla/nsprpub/pr/src/md/unix/netbsd.c</tt> you need to modify the following existing files: <tt>mozilla/nsprpub/pr/include/md/makefile</tt> <tt>mozilla/nsprpub/pr/include/md/_unixos.h</tt>: just fix the compiling errors, usually pointed out by the <tt>#error</tt> preprocessor directives we inserted. <tt>mozilla/nsprpub/pr/include/md/prosdep.h</tt> <tt>mozilla/nsprpub/pr/src/md/prosdep.c</tt> <tt>mozilla/nsprpub/pr/src/md/unix/makefile</tt> <tt>mozilla/nsprpub/p...
...first a warning: some of the tests are broken. further, we don't have documentation of our unit tests, so you often need to resort to read the source code to under...
Proxy UI - Archive of obsolete content
click "cancel" to discard changes. the radio buttons do not map to the proxy type in order (due the evolution of the ui): proxy mode "network.proxy.type" no proxy (direct) network.proxy.type=0 auto-detect proxy settings... (wpad) network.proxy.type=4 manual proxy configuration (manual) network.proxy.type=1 automatic proxy configuration url (pac) network.proxy.type=2 manual manual allows the entry of a proxy server hostname name and server. the entries are on a per-protocol basis for: http, ssl (https), ftp, gopher. if configured, socks is used as a default: if the protocol was proxyable and did not match any of the previous protocols), then use socks. the socks version is selected by radio buttons: ( ) socks v4 ( ) socks v5 "no proxy for:" discussed in detail elsewhere... but...
...oxy for:" discussed in detail elsewhere... but should be noted that if you cut and paste from ie, the semi-colons are automatically converted to commas when you save changes (ff, tb, sm). automatic proxy configuration url supports a url (which is checked via urifixup) and a reload button. offline|online "plug" location status bar on the right side. right-click a menu is displayed that has the following items: online (proxy: none) online (proxy: auto discover) online (proxy: auto url) online (proxy: manual) --- proxy configuration... <h7 name="details">details</h7> the menu should display the current proxy mode with a dot. the modes that can have an empty configuration (auto url and manual) will be disabled if the prefs are blank. selecting an enabled item sets the menu selection and the prox...
...nline (proxy: auto url) online (proxy: manual) --- proxy configuration... <h7 name="details">details</h7> the menu should display the current proxy mode with a dot. the modes that can have an empty configuration (auto url and manual) will be disabled if the prefs are blank. selecting an enabled item sets the menu selection and the proxy mode (network.proxy.type) selecting a disabled item is not allowed. selecting "proxy configuration..." opens the preferences panel to "advanced > proxies" (tbdescribed: changing the prefs values). unfiled bug: changing proxy mode does not update the menu. mouseover when online, the tooltip will include the current proxy mode: code http://mxr.mozilla.org/seamonkey/sou...ityoverlay.xul bugs bug 243624 reference network.proxy.type ...
RDF Datasource How-To - Archive of obsolete content
"important friend". deciding on a vocabulary the vocabulary is the 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,...
...sid. replace "my data source" with a descriptive string that should appear in the registry. finally, replace "my-datasource" with a value appropriate for your datasource. this value, when prefixed with "rdf:", is a datasource identifier, and may be used with nsirdfservice::getdatasource() to retrieve your datasource from the rdf service. for example, the above datasource would be accessable as follows: nsirdfservice* rdf; rv = nsservicemanager::getservice(krdfservicecid, kirdfserviceiid, (nsisupports**) &rdf); if (ns_succeeded(rv)) { nsirdfdatasource* mydatasource; rv = rdf->getdatasource("rdf:my-datasource", &mydatasource); if (ns_succeeded(rv)) { // ...do something to mydatasource here... ns_release(mydatasource); } ...
...); } nsservicemanager::releaseservice(krdfservicecid, rdf); } displaying rdf as content now that you've gone through all this pain to expose your information as a datasource, you probably want to see it. using xul, you can display the contents of your datasource in a tree control, a menu, or a toolbar. in fact, you can convert rdf to an arbitrary content model using xul templates. ...
Frequently Asked Questions - Archive of obsolete content
show source code/gibberish instead of svg? there are two possible reasons for this: a simple mistake in the svg file, or a misconfigured server. if there's a grey area at the top of the source with the text "this xml file does not appear to have any style information associated with it" then the problem is with the svg file. to be valid the root <svg> tag in svg files must have at least the following two "namespace bindings". <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> actually the second binding isn't always required, but unless you understand namespaces, we'd strongly recommend you include it. for more information see this link. if source code is displayed without a gray area at the top, or if you just see gibberish, then the problem is server ...
...nts. mozilla will show this message when there's an xml well formedness error in the file it tried to load. (it doesn't mean there's an error in mozilla.) there are many different xml errors, but the most common one in svg files is "xml parsing error: prefix not bound to a namespace". this is (almost certainly) because the 'xmlns:xlink' attribute has been used in the file without including the following two namespace bindings on the root <svg> tag. <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> make sure all your svg files have these bindings. for more information see this link. why am i asked to choose a program to open svg files? when you try to load svg files from some websites you may get a dialogue asking you "what should firefox do with this fil...
...er this question to save you searching for this information elsewhere. see these install instructions on mozdev.org. it's also useful to know that you can check whether mozilla has recognised your plug-ins by typing 'about:plugins' into your address bar (linking to that doesn't work for security reasons). does mozilla work with corel's svg plug-in? there are reports that it does, but that it's slower than the adobe plug-in. see this document for information on how to install it. can you have both native svg support and an svg plug-in installed? yes. if the plug-in works with the equivalent non-svg version of mozilla, then it should also work in the svg enabled version. to be able to use it, you must make sure the svg.enabled pref is set to false. this will disable the native svg support. ...
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...
...being looked at). for the nsidomdocumentxbl interface's nsidomdocumentxbl.addbinding() and nsidomdocumentxbl.loadbindingdocument() methods, the originating principal is the one of the script making the call, or the principal of the document the call is made on if there isn't a script. checks performed once the originating principal is determined, checks are done to make sure the load should be allowed. the checks performed are: if the principal originating the load is the system principal, the load is allowed. a call to checloaduriwithprincipal() is done to make sure the principal is able to link to the given uri in the first place. a content policy check is performed. if the uri is a chrome: uri, the load is allowed. note that step 2 already denied the load attempt for cases in which the c...
...l is able to link to the given uri in the first place. a content policy check is performed. if the uri is a chrome: uri, the load is allowed. note that step 2 already denied the load attempt for cases in which the chrome: uri isn't accessible to untrusted content. a checkmayload() check is performed on the originating principal for the given uri. if the checkmayload() check passes, the load is allowed. ...
Static Analysis for Windows Code under Linux - Archive of obsolete content
build gcc corss-compiler with plugin support by default gcc does not support plugins. ...
...e http://hg.mozilla.org/users/tglek_mo...-moz-plugin-mq .hg/patches # apply gty.diff and plugin.diff # if you have mq setup, do hg qpush -a (for file in `cat .hg/patches/series`; do cat .hg/patches/$file; done) |patch -p1 cd .. now, the gcc source with plugin supports is ready, we should now build a cross compiler from this source. and the instructions are exactly the same with the one here. follow that instructions strictly for making a cross compiler. build dehydra for cross-compiler build the dehydra plugin dehydra is a shared library which will be loaded by the above plugin-support gcc. build dehydra for a cross compiler has nothing 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 ha...
...ilding 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 check_treehydra run static analysis on mozilla windows 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 .mozc...
Table Cellmap - Archive of obsolete content
td><td>cell 2</td></tr> <tr><td>cell 3</td><td>cell 4</td></tr> </tbody> </table> now we have two different rowgroups and and the rowspans can not cross the borders between the different rowgroups. (ref xhtml-2.0). further the table header and footer will be repeated on every page when printed out. due to this behind the cellmap for the table we will find a cellmap for every rowgroup. in this low level cellmap the row count begins every time with 0. a typical code segment to come from the table level down to the rowgroup level nscellmap* map = mfirstmap; while (map) { if (map->getrowcount() > rowindex) { // add your action here } rowindex -= map->getrowcount(); map = map->getnextsibling(); } data entry the usual way to populate the cellmap is via nstableframe::insertrows. ...
...e rowgroup level nscellmap* map = mfirstmap; while (map) { if (map->getrowcount() > rowindex) { // add your action here } rowindex -= map->getrowcount(); map = map->getnextsibling(); } data entry the usual way to populate the cellmap is via nstableframe::insertrows. enabling the debug code at the function entrance and exit gives a quite complete picture of the cellmap structure. below follows the dump for the 2x2 table. insertrowsbefore firstrow=0 ***start table dump*** mcolwidths= row(0)=02763344 cell(0)=02763528 cell(0)=0276381c row(0)=02763940 cell(0)=02763990 cell(0)=02763ab4 ***** start table cell map dump ***** 023566b0 cols array orig/span-> 023566b0 ***** start group cell map dump ***** 023565b0 maprowcount=0 tablerowcount=0 ***** end group cell map dump ***** *...
...s. the current solution is to use nscellmap::getdataat with a special argument aupdatezerospan to repair the cellmap if it encounters a empty cell (nsnull), by looking for a origin of a zero row- or colspan that spans the queried place in the cellmap. this can produce enormous costs once the cellmap contains large holes that are not caused by zero spans, this is at least a o2(n) algorithm. the following routines seem to be hot spots performance wise: nscellmap::colhasspanningcells nscellmap::rowhasspanningcells nscellmap::rowisspannedinto users of nscellmap::getdataat outside nscellmap.cpp the border collapse code relies on the cellmap. the collapsing of rows and columns uses the cellmap. and finally the line iterator methods which are used for arrow navigation through a table. o...
Table Layout Regression Tests - Archive of obsolete content
than your main profile. select from the regression-test menu the add new list...entry. select %moz_src%/layout/html/tests/block/rtest.lst. execute the baseline test shutdown the layoutdebugger execute mozilla -layoutdebug - p foo >selftest.txt execute the verify test make a note which tests have failed grep 'failed' selftest.txt (these are false positives, quite frequently they indicate reflow problems, pages showing differently when loaded from cache) make your changes to the source, recompile. execute mozilla -layoutdebug - p foo >outputfile.txt execute the verify test make a note which tests have failed grep 'failed' outputfile.txt check how many tests have failed and analyze your results: if the regression tests have failed at the same place as the previous diagnosed false po...
...xul data="0 0 0 0 0 1 <svg data="0 1.000000 1.000000 0 1.000000" /> </stylecontext> the baseline log will look like: type manifest file: e:\moz_src\mozilla\obj-i586-pc-msvc\dist\bin\components\xpti.dat +++ javascript debugging hooks installed. ++webshell == 1 ++domwindow == 1 ++webshell == 2 ++domwindow == 2 note: styleverifytree is disabled note: frameverifytree is disabled note: verifyreflow is disabled ++webshell == 3 ++domwindow == 3 running baseline test for e:\moz_src\mozilla\layout\html\tests\block\rtest.lst. writing regression data to e:\moz_src\mozilla\layout\html\tests\block\base\baseline\width-fixed_html.rgd writing regression data to e:\moz_src\mozilla\layout\html\tests\block\base\baseline\width-percent_html.rgd writing regression data to e:\moz_src\mozilla\layout\html\test...
... reference frame dump. if they differ in critical points the test fails. a typical part of the verify log would look like: type manifest file: e:\moz_src\mozilla\obj-i586-pc-msvc\dist\bin\components\xpti.dat +++ javascript debugging hooks installed. ++webshell == 1 ++domwindow == 1 ++webshell == 2 ++domwindow == 2 note: styleverifytree is disabled note: frameverifytree is disabled note: verifyreflow is disabled ++webshell == 3 ++domwindow == 3 running verify test for e:\moz_src\mozilla\layout\html\tests\block\rtest.lst. writing regression data to e:\moz_src\mozilla\layout\html\tests\table\core\verify\standards1.rgd comparing to regression data from e:\moz_src\mozilla\layout\html\tests\table\core\baseline\standards1.rgd frame bbox mismatch: 0,26437,4824,600 vs. 0,26437,4872,600 node 1: tabl...
Actionscript Acceptance Tests - Archive of obsolete content
any avm arguments can be placed before the |multiabc| directive, or the line can start with the directive. any test arguments (--) must be placed after the multiabc file listings. here is a more complicated example that passes both avm args, multiple abcs and test args: -ojit |multiabc| $dir/testname_support/a.abc -- test_args a dir.avm_args file can also be created with the same contents t...
... both avm args, multiple abcs and test args: -ojit |multiabc| $dir/testname_support/a.abc -- test_args a dir.avm_args file can also be created with the same contents that will apply to the entire directory. testname.as.avm_args files will take precedence over the dir.avm_args file testname.as.tz if a test is only valid for certain timezones, the timezones can be specified in this support file. below is a sample file that covers the 4 main us timezones: # place all timezones that this file applies to. # these values correspond to the value returned by time.tzname tuple. # (see http://docs.python.org/library/time.html for details) # e.g.: eastern standard time/eastern daylight time = ('est','edt') # write timezones as tuples, one to each line. ('est', 'edt') ('cst', 'cdt') ('mst', 'mdt') ('p...
...created. the directory name should not include any testname extensions. ...
Running Tamarin acceptance tests - Archive of obsolete content
note: the name of the avmshell executable varies among the build systems; use the name of the avm shell produced from the build process you used, above. ...
...note: the name of the avmshell executable varies among the build systems; use the name of the avm shell produced from the build process you used, above. ...
...1056.abs ... test run passed! tests complete at 2010-09-28 10:39:26.751797 start date: 2010-09-28 10:38:07.221457 end date : 2010-09-28 10:39:26.751797 test time : 0:01:19.530340 passes : 59291 failures : 0 expected failures : 75 tests skipped : 76 the -f flag tells runtests.py to force recompilation of all the scripts. for help on runtests.py options, see below or use python runtests.py -h. notes on using acceptance runtests.py threading in order to speed up the execution time of the acceptance testsuite, the runtests script automatically detects the number of cores on the machine and sets an equivalent number of threads. this can be overrided with the threads flag: python ./runtests.py --threads=3 threading on cygwin / windows due to an issue with cyg...
Running Tamarin performance tests - Archive of obsolete content
set the builtinabc environment variable to the path of the builtin.abc. (in the tamarin-redux/generated directory) set the shellabc environment variable to the path of the shell_toplevel.abc. (in tamarin-redux/generated directory) set the asc environment variable to the path of the asc.jar compiler. ...
...le times. specifying ./runtests.py -i 10 will run each tests 10 time and use the fastest result. if more than 2 repetitions are specified the 95% percentile confidence rating is calculated. the confidence rating measures the percentage of the mean 95% of the results were within the range. ...
... shell chmod 777 /data/app/android_runner.sh test it out with a simple .abc or no args for usage (should return exitcode=0) $ tamarin-redux/platform/android/android_shell.h hello.abc hello exitcode=0 running performance tests to run performance tests on android you don't need to pass --androidthreads or --threads=1 as with the acceptance tests; in fact, a usage error will result. just type the following commands after making sure you've set the environment variables correctly. $ cd /test/performance $ ./runtests.py note on using an emulator: the emulator does seem to support hardware floating point but gives a buserror when running avmshell -darm_vfp. it's unreliable, losing its adb connection frequently. an emulator is ok for testing a few abc files but for any consistency a real device is...
Tuning Pageload - Archive of obsolete content
tuning pageload can be beneficial if you know what you're doing. firefox (and all mozilla products/projects which do page-loading) ship with what are considered the "best" settings for the most cases. this document explains which preferences to tweak to affect your pageload time. you use the url about:config or the file prefs.js in your profile 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 ...
... 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, when true, means that the content sink can tell the parser to stop for now and return to the event loop, which allows layout and painting to happen. if the parser gets a large chunk of data, it will try to parse it all, building the corresponding content model. since layout and painting happen asynchronously, while the parser is working there is no layout or painting. so this preference is used to increase responsiveness, especially on cached loads (where data comes into the parser in large chunks) content.m...
...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 content.switch.threshold microseconds. as in, if the user is moving the mouse or typing in that window, we'll be more responsive; if there is no user activity, we will aim for less parser interruption and less responsiveness but lower overall load time. content.notify.* controls the information flow from content sink to rendering model. in particular, the way things work right now is that the parser and content sink construct the dom; then every so often, the content sink lets the rendering model constructor (nscssframeconstructor) know that there are new dom nodes. the reason for this is that nscssframeconstructor is mo...
Binding Implementations - Archive of obsolete content
. without disambiguating, if two bindings define the same method or property, then the most derived binding's method or property will be used. because bindings extend dom elements, they can override any built-in methods or properties on the dom element. for example, a binding could override the setattribute method on element or the retrieval of the value property for an htmlinputelement. ...
...this is an open issue. ...
...n open issue. should we attempt to define a language-independent abstraction, or specify that it must be possible to access base bindings' methods and properties? for example, given a binding with an implementation colorpickergrid that derives from an implementation colorpicker where the two implementations both specify the setcolor method, a caller could invoke colorpicker's method with the following syntax: ... // myelement is a colorpickergrid myelement.colorpicker.setcolor(); // calls the colorpicker method. myelement.setcolor(); // calls the colorpickergrid method. ... in addition to being able to specifically name a base class, the name basebinding can be used to specify the method or property on the base binding without necessarily knowing what the base class is. this situation ca...
Example Sticky Notes - Archive of obsolete content
12)"/> </svg:g> </svg:svg> <children/> </content> <implementation> <!-- here and futher cdata wrappers around javascript code are not mandatory but recommended. this way you protect yourselve from < and > signs breaking your xml layout. it also speeds up the parsing as the engine doesn't go through cdata sections but simply skip on them. --> <constructor><![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 con...
...any) will be used as initial value. */ "normal"; ]]></field> <property name="innertext"> <!-- new "virtual" property for the bound element. unlike <field> these are really two functions (getter and setter). within the virtual properties you cannot set or get the named property itself. say an attempt to assign this.innertext='something' will lead to circular setter call and stack overflow. --> <getter><![cdata[ var st = this.innerhtml || ''; if (st != '') { var re = /<\/?[^>]+>/gi; return st.replace(re,''); } else { return ''; } ]]></getter> <setter><![cdata[ // "val" in setter contains the assignment value. // here we simply echoing it back: return val; ]]></setter> </property> <method name="setborder"> <!-- new method for the bound element. unlike virtual p...
...nt="mouseover"><![cdata[ this.$bg = this.style.backgroundcolor || '#ffff00'; this.style.backgroundcolor = '#ffcc00'; ]]></handler> <handler event="mouseout"><![cdata[ this.style.backgroundcolor = this.$bg; ]]></handler> </handlers> </binding> </bindings> notes.css .sticker { position: relative; left: 0px; right: 0px; float: left; clear: none; width: 10em; height: 10em; overflow: visible; margin: 1em 1em; padding: 0.5em 0.5em; border: 2px solid blue; background-color: yellow; font: 1em normal "times new roman",serif; font-style: italic; cursor: default; } view this example ...
compareTo - Archive of obsolete content
min minor version number. ...
... an installversion object or a string representing version information in the format "4.1.2.1234". returns if the versions are the same, this method returns 0. if this version object represents a smaller (earlier) version than that represented by the version parameter, this method returns a negative number. otherwise, it returns a positive number. in particular, this method returns one of the following values: -4 this version object has a smaller (earlier) major number than version. -3 this version object has a smaller (earlier) minor number than version. -2 this version object has a smaller (earlier) release number than version. -1 this version object has a smaller (earlier) build number than version. 0 the version ...
...he same; both objects represent the same version. 1 this version object has a larger (newer) build number than version. 2 this version object has a larger (newer) release number than version. 3 this version object has a larger (newer) minor number than version. 4 this version object has a larger (newer) major number than version. ...
loadResources - Archive of obsolete content
nting the path to the properties file in the xpi in which the key/value pairs are defined. returns a javascript object whose property names are the keys from that file and whose values are the strings. description the format of the properties file expected by loadresources is the same as that of the chrome locale .properties files. ...
...alues are the strings. description the format of the properties file expected by loadresources is the same as that of the chrome locale .properties files. this method is used to internationalize installation scripts by allowing the installer to retrieve localized string values from a separate file. be aware that the parameter specifies the file within the xpi and not on the file system, as the following example demonstrates. example given a xpi with this internal structure: install.js bin/res_eg_2.properties bin/somefile.exe bin/... ...
... files. this method is used to internationalize installation scripts by allowing the installer to retrieve localized string values from a separate file. be aware that the parameter specifies the file within the xpi and not on the file system, as the following example demonstrates. example given a xpi with this internal structure: install.js bin/res_eg_2.properties bin/somefile.exe bin/... ...
browser.type - Archive of obsolete content
the type of browser, which can be used to set access of the document loaded inside the browser. if this is not set, the loaded document has the same access as the window containing the browser. more precisely: the document loaded into a chrome window is always of chrome type. subdocuments of chrome documents are of chrome type, unless the container element (one of iframe, browser or editor) has one of the special type attribute values (the common ones are content, content-targetable and content-primary) indicating that the subdocument is of content type. ...
..., and preventing documents from inheriting the principal of the parent document. the type attribute on all frames in content documents is ignored; subdocuments of content documents are always content documents. warning: the type attribute must be set before the element is inserted into the document. content a browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. content-primary the primary browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. for instance, in a web browser, this would be the element that displays the web page. the window for the primary content can be retrieved more conveniently using window.content. content-targetable one browser among ma...
...this is the preferred value for any browser element in an application, which will use multiple browsers of equal privileges, and is unselected at the moment. chrome (default behaviour): a browser, intended to be used for loading privileged content using a chrome:// uri. ...
mousethrough - Archive of obsolete content
« xul reference home mousethrough type: one of the values below determines whether mouse events are passed to the element or not. 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. ...
...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. the mousethrough attribute is typically used in conjunction with a stack to allow elements to be stacked above other elements yet allow mouse events to be sent to lower elements. in the following example, the image appears above the button, yet the mousethrough attribute specified on the image causes mouse events to be ignored on the image and instead fall through to the button. if the mousethrough attribute was not used, the image would receive all mouse events and the button...
...s to be sent to lower elements. in the following example, the image appears above the button, yet the mousethrough attribute specified on the image causes mouse events to be ignored on the image and instead fall through to the button. if the mousethrough attribute was not used, the image would receive all mouse events and the button could not be pressed with the mouse. ...
Building accessible custom components in XUL - Archive of obsolete content
, we can declare the role of each element in our spreadsheet. the grid element is really a spreadsheet. each label element is really a cell within the spreadsheet. each description element is really a row or column header within the spreadsheet. you can find a list of all the supported roles in firefox 1.5 on mozilla.org. role declarations are a little confusing at first glance, but they all follow the same pattern. the role attribute itself is in the xhtml 2 namespace. we will need to declare the namespace (xmlns:x2="http://www.w3.org/tr/xhtml2") so we can add an xhtml2:role attribute to each xul element. the role attribute value is also in a namespace. we will need to declare this namespace as well (xmlns:wairole="http://www.w3.org/2005/01/wai-rdf/guiroletaxonomy#"), and then use this nam...
...var label = done_edit(textbox, true); label.focus(); }, 0); break; case key_escape: settimeout(function() { var label = done_edit(textbox, false); label.focus(); }, 0); break; } } </code> with this new code, we can now navigate to a specific cell within the spreadsheet and press enter to edit the value. the start_edit function replaces the label with a textbox, which allows the user to change the cell value. <caption>editing a cell</caption> once we're satisfied with our changes, we can press enter again to accept the value. the done_edit function recreates the original label element and sets the new value. note that the role is once again "cell", since we explicitly set it when we recreated the label element. <caption>after editing a cell</caption> ...
... further reading accessible html spreadsheet demo on mozilla.org future enhancements now that we know how to create an accessible spreadsheet, it should be possible to use xbl to create a reusable component that encapsulates the accessibility implementation. all of the dhtml accessibility roles, the keyboard navigation, and the focus tracking could be defined within the xbl file. this would allow xul developers to add a single spreadsheet element to their xul applications (for example), with rowheader, columnheader, and cell elements as children, without requiring them to manage the accessibility support for each spreadsheet control. ...
Working With Directories - Archive of obsolete content
nd save dialogs, reading textual data, writing textual data, list of file-related error codes. a reference to a directory may be created in the same way as with a file by using nsiscriptableio.getfile(). you can access a subdirectory by supplying a directory name as the second argument, or refer to one of the special directories by supplying a null string for the second argument. the first line below with retrieve the directory corresponding to the user's home directory, while the second will retrieve the directory 'myfiles' on the desktop. var dir1 = io.getfile("home", ""); var dir2 = io.getfile("desktop", "myfiles"); to refer to a subdirectory, rather than using a path, use nsifile.append() to build up a path. for instance: var dir2 = io.getfile("desktop", "myfiles"); dir2.append("pictures...
...", "myfiles"); to refer to a subdirectory, rather than using a path, use nsifile.append() to build up a path. for instance: var dir2 = io.getfile("desktop", "myfiles"); dir2.append("pictures"); dir2.append("vacations"); in this example, a subdirectory several levels down is referenced. each call to nsifile.append() navigates to a further subdirectory. the result is a subdirectory three levels below the desktop directory. these directories do not need to exist yet, but they can be created using nsifile.create(). see creating directories below for information about this. note that nsifile.append() modifies the file object, rather than returning a new one. both files and directories are represented using the same kind of object so most of the functions available for nsifile will work for both.
...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. ...
Reading from Files - Archive of obsolete content
g text files characters are interpreted from a text input stream using a specified character encoding. this means that if a character within the file occupies several bytes, it will converted into a single character when read. this is done automatically as long as you specify the 'text' flag to nsiscriptableio.newinputstream(). the default character encoding is utf-8 which means that characters below value 128 will occupy a single byte whereas characters above value 128 will occupy multiple bytes, depending on their value. however, a number of other character encodings are available; see reading other character encodings below for details about reading text in other encodings. there are several methods available to read from an input stream. the two most common for text files are the readstri...
...eam for a file. once the stream has been opened, you can read from the file using various reading methods. the readstring method may be used to read a certain number of bytes into a string. this example will keep reading 20 byte blocks from a file and append them to a string. ...
...read8 will read a single byte and return it. the 8 in the method name indicates that 8 bits of data are being read. ...
Moving, Copying and Deleting Files - Archive of obsolete content
py, and the second is the directory in which to copy the file to. nsifile.copyto() of the former is called, passing the latter as the first argument to nsifile.copyto(). naturally, the destination must be a directory or an error will occur. in this case, we assume that 'source.txt' is a file. if the item to copy is a directory, it can be copied in the same manner as above without changes. this allows an entire directory and its contents to be copied from one location to another. you might use this to make a backup of a directory of files for instance. var file = io.newfile("home", "importantdata"); var destination = io.newfile("desktop", ""); destination.append("backups"); file.copyto(destination, ""); this example copies an item called 'importantdata' into a directory called 'backups' wi...
...ng a file, for instance if the file to copy does not exist or the destination directory is not writable. it is a good idea to enclose file operations within a try-catch block in order to capture any errors that might occur. for a list of possible file related errors, see file errors. moving a file to move a file, nsifile.moveto() may be used which functions similarly to nsifile.copyto(). the following example moves a file 'myfile.txt' in the user's home directory into the temporary directory. as with nsifile.copyto(), nsifile.moveto() takes two arguments, the destination directory and the new filename. if you do not want to rename the file and keep its existing name, use a null string for the second argument. var file = io.newfile("home", "myfile.txt"); var destination = io.newfile("tempor...
...emporary", ""); 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() before moving the file. deleting a file to delete a file, use nsifile.remove(). this method takes one boolean argument which indicates whether ...
addTab - Archive of obsolete content
Archive › Mozilla › XUL › Method › addTab
it also adds the relatedtocurrent parameter; firefox uses this to decide whether the new tab should be inserted next to the current tab. ...
...it also adds the relatedtocurrent parameter; firefox uses this to decide whether the new tab should be inserted next to the current tab. ...
...it also adds the relatedtocurrent parameter; firefox uses this to decide whether the new tab should be inserted next to the current tab. see code snippets: tabbed browser for examples. ...
appendNotification - Archive of obsolete content
the priority level is used. priority - notification priority; see priority levels. buttons - array of button descriptions to appear on the notification. eventcallback optional - a javascript function to call to notify you of interesting things that happen with the notification box. see notification box events. ...
...see priority levels. buttons - array of button descriptions to appear on the notification. eventcallback optional - a javascript function to call to notify you of interesting things that happen with the notification box. see notification box events. ...
...on the notification. eventcallback optional - a javascript function to call to notify you of interesting things that happen with the notification box. see notification box events. priority levels (defined as properties of notificationbox) : priority_info_low priority_info_medium priority_info_high priority_warning_low priority_warning_medium priority_warning_high priority_critical_low priority_critical_medium priority_critical_high priority_critical_block buttons : the buttons argument is an array of button descriptions. each description is an object with the following properties: accesskey - the accesskey to appear on the button callback - function to be called when the button is activated. this function is passed three arguments: the <notification> the ...
PopupKeys - Archive of obsolete content
on linux and the macintosh, disabled items within the menu are skipped over when navigating with the cursor keys. ...
...on linux and the macintosh, disabled items within the menu are skipped over when navigating with the cursor keys. ...
... yourself. while a menu is open, the focus remains where it was before the menu was open. for example, focusing a textbox and opening the textbox's context menu keeps the focus within the textbox. however, the capturing listener ensures that no key events reach the textbox while the menu is open. unlike with a menu, when a panel is opened, the focus is removed from any element that has it. this allows the focus to be shifted to elements within the panel. for more information about focus handling within panels, see focus in panels. ignoring keys the ignorekeys attribute may be used to disable the key listener described above. when the ignorekeys attribute is placed on a <menupopup> or <panel> element, and its value is set to the value true, the key listener is not used. <panel ignorekeys="tr...
Popup Guide - Archive of obsolete content
hat may extend outside of the edge of the main window. popup types xul provides a number of different types of elements which may be used to create popup menus or other types of popup widgets, which vary based on the manner in which they are attached to an element and the manner in which they are opened. a brief overview of each type is listed here; more details for each type can be found by following the corresponding links. a popup is not created as a separate window or file, instead it is included inside another window or dialog. in this guide, the term 'popup' refers to all types of popups, whereas the term 'menu' refers to a specific type of popup. specifically, the first two types in the list below are menus. menus a menu is used when you wish to have a series of commands that ca...
...nu except that the commands it contains apply to what the user had clicked on to open the context menu. often, depending on what was clicked on, certain commands may be hidden if not applicable to that element. panels a panel can contain any type of content. it is useful when you wish to display some controls temporarily over the existing ui. for example, a popup search field could be used to allow searching and will disappear when a search term has been entered. a panel is created using the panel element. floating panels a floating popup is a type of panel with a titlebar and acts like an auxiliary window. usually it would contain tools related to the main window, or an inspector which displays properties of a selected element. tooltips when the mouse is positioned over a ui control, ...
...displays properties of a selected element. tooltips when the mouse is positioned over a ui control, a tooltip provides a small box with descriptive help about that control. when the mouse is moved away from the control, the tooltip automatically disappears. a tooltip can be created by setting the tooltiptext attribute on an element or by using the tooltip element. working with popups the following additional information is available about manipulating menus and popups. opening a menu or popup most menus and popups are opened automatically when they are 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 ...
Providing Command-Line Options - Archive of obsolete content
extensions and xul applications can modify the way command line parameters are handled by writing a component that implements the nsicommandlinehandler interface and registering it in a category. see also: xulrunner:commandline overview the code below is an example of writing a javascript xpcom component to handle command line parameters. you can learn more about how the command line is interpreted by looking at the documentation for the nsicommandline interface. example the below example component implements two command line parameters: firefox.exe -myapp opens a chrome window for my application. firefox.exe -viewapp url opens a chrome window for my application and passes it an nsiuri object. using the example to use this sample code, save the commandline.js file i...
... for the nsicommandline interface. example the below example component implements two command line parameters: firefox.exe -myapp opens a chrome window for my application. firefox.exe -viewapp url opens a chrome window for my application and passes it an nsiuri object. ...
... } } catch (e) { components.utils.reporterror("incorrect parameter passed to -viewapp on the command line."); } // changeme: change "myapp" to your command line flag (no argument) if (cmdline.handleflag("myapp", false)) { openwindow(chrome_uri, null); cmdline.preventdefault = true; } }, // changeme: change the help info as appropriate, but // follow the guidelines in nsicommandlinehandler.idl // specifically, flag descriptions should start at // character 24, and lines should be wrapped at // 72 characters with embedded newlines, // and finally, the string should end with a newline helpinfo : " -myapp open my application\n" + " -viewapp <uri> view and edit the uri in my application,\n" + ...
Building Menus With Templates - Archive of obsolete content
ther elements. however, unlike with other elements, the content of a menu is only generated once the menu has been opened. this means that a menu created with a template will not have any of the generated items until the user opens the menu, or a script opens the menu. this applies to menus on menubars, submenus, as well as menu-type buttons such as those with a type attribute set to menu. this allows for better performance as the entire content of a complex menu does not need to be created until the user needs to use the menu. it is very simple to create a menu using a template. here is an example using an xml source: <button type="menu" datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="person"/> <action> <menupopup> <menuitem uri="?" label="?n...
...he menu tag is different (menuitem versus menu), and the label is taken from a different rdf predicate. at the outer level, the second rule matches the streets, so a menupopup and menu element are created. the uri attribute is on the menu element since we don't want to repeat the popup for every result. after the first level of the menu has been generated, the content will be equivalent to the following (ignoring the template related content): <button label="houses in my neighbourhood" type="menu"> <menupopup> <menu uri="http://www.xulplanet.com/rdf/marion" label="marion street"/> <menu uri="http://www.xulplanet.com/rdf/garden" label="garden avenue"/> </menupopup> </button> the inner pass through the data handles the houses. the houses match the first rule so a menupopup and menu...
...ton> the inner pass through the data handles the houses. the houses match the first rule so a menupopup and menuitem element are generated and inserted inside the street content (the menu element). again, the popup is only created once since the uri attribute is on the menuitem element. the effect is a menu with a submenu. there's nothing special about the way menus are handled -- the builder follows the same method for any type of content. however, the nature of menus can make this tricky to follow. here is the result of the above example after both levels have been handled. <button label="houses in my neighbourhood" type="menu"> <menupopup> <menu uri="http://www.xulplanet.com/rdf/marion" label="marion street"> <menupopup> <menuitem uri="http://www.xulplanet.com/rdf/gard...
Building Trees - Archive of obsolete content
d the tree builder. without this flag, the template will be handled by the content builder. note: while a tree builder can only be used with trees, a content builder can be used with any type of content. if you wish, you can also use the content builder for a tree. there may be situations that call for this, typically when handling smaller amounts of data. however, the content builder becomes slower as the amount of data increases. apart from the flags attribute, the template syntax for the tree builder and the content builder are identical. however, the tree builder requires a very specific form to the action body. specifically, the action body should be a single treeitem with its rows and cells. here is an example (using an rdf source): <tree id="photoslist" flex="1" datasources="templa...
...tribute on a cell becomes extremely useful. it can be used to define extra properties for reference later in a stylesheet. for example, if the properties attribute was set to the value "?creator", you could style the photos created by different people differently. alternatively, you could also use static values (in addition to variables) in the properties attribute. for instance, consider the following css: treechildren::-moz-tree-cell(dave) { background-color: lightgreen; } this would set the background color of a cell to green for any cell with the “dave” property. you can also use the properties attribute on the treerow to change the style for an entire row. this example sets the country associated with a photo as a property of a tree’s rows. we can use that property to change th...
... « previousnext » ...
Containment Properties - Archive of obsolete content
to do this, use the containment attribute on the root node, set to the predicate to iterate over. let's look back at the very first example again. ...
...tp://www.xulplanet.com/rdf/a"> <rdf:li rdf:resource="http://www.xulplanet.com/rdf/e"/> <rdf:li rdf:resource="http://www.xulplanet.com/rdf/f"/> </rdf:seq> the effect is that there are five results instead of three. three generated via the use of the containment attribute, and two generated because the starting resource is a container with two children. effectively, the containment attribute allows you to specify additional predicates that provide children. you can specify multiple predicates in the containment attribute by separating them with spaces. each will be applied in sequence. the containment attribute also applies to member tests when using the extended template syntax. that is, in addition to iterating over the children, it will iterate over the predicates listed in the containm...
...tes that provide children. you can specify multiple predicates in the containment attribute by separating them with spaces. each will be applied in sequence. the containment attribute also applies to member tests when using the extended template syntax. that is, in addition to iterating over the children, it will iterate over the predicates listed in the containment attribute. for example, the following is equivalent to the previous example, except that the full query syntax is used. <vbox datasources="template-guide-ex3.rdf" ref="http://www.xulplanet.com/rdf/a" containment="http://www.xulplanet.com/rdf/relateditem"> <template> <query> <content uri="?start"/> <member container="?start" child="?child"/> </query> <action> <label uri="?child" val...
RDF Query Syntax - Archive of obsolete content
gle 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="http://www.xulplanet.com/rdf/relateditem" object="?relateditem"/> the triple statement 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...
...', so that is filled in. the ?relateditem variable doesn't have any known value, so it will be left as is. once the variables are filled in, the builder can query the rdf graph. the query will look for all arrows that start at the node 'http://www.xulplanet.com/rdf/a' with the predicate (or arrow label) 'http://www.xulplanet.com/rdf/relateditem'. ...
....xulplanet.com/rdf/a' with the predicate (or arrow label) 'http://www.xulplanet.com/rdf/relateditem'. since ?relateditem isn't known, the builder will allow any value for the node the arrow points to, and will look in the datasource for all possible values. in a triple statement, the subject is always the start of an arc, while the object is what it points to. for this triple, the builder will follow the arrows in the forward direction. here is the rdf graph again: starting at node a and following the relateditem arcs, we can see that there are three possible values for the ?relateditem variable, b, c and d. this is new data, so the builder adds it to the graph. since three values have been found, the network will now have three potential results: (?start = http://www.xulplanet.com/rdf/a, ?r...
Simple Example - Archive of obsolete content
riable you wish. (?start = http://www.xulplanet.com/rdf/myphotos) the member element is used to iterate over the children of a container (or the reverse). first, any known variables are filled into the member statement for the current result. there's only one result so far; the member element's container attribute is set to value of the ?start variable of this result. this will result in the following: <member container="http://www.xulplanet.com/rdf/myphotos" child="?photo"/> as with processing a triple, the builder will now try to find as many values for the ?photo variable as possible and create potential results using them. the container attribute specifies the container and the child attribute specifies the children. in the rdf data, the container 'http://www.xulplanet.com/rdf/myphoto...
... above', so it will be added to the data network, assigned to the ?title variable. note that this value is a literal rather than a resource. (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/palace.jpg, ?title = 'palace from above') the process continues in a similar manner for the other two results. ...
...ace from above') (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/canal.jpg, ?title = 'canal') (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg, ?title = 'obelisk') since the triple is the last statement, three matches total have been found. the action body might look like the following, which displays the image using its url and title in a label. you might note that the image's src attribute uses the member variable ?photo <action> <vbox uri="?photo" align="start"> <image src="?photo"/> <label value="?title"/> </vbox> </action> it shouldn't be too difficult to tell what would appear in the window in this example. you can see if you guessed correctly by viewing ...
The Joy of XUL - Archive of obsolete content
n start building 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 th...
...ut and appearance of xul applications can be altered independently of the application definition and logic. further, the application can be localized for different languages and regions independently of its logic or presentation. this degree of separation results in applications that are easier to maintain by programmers and readily customized by designers and language translators. the work flow of these interdependent activities is more easily coordinated than with html-based web applications, with less impact on the overall stability and quality of the system. easy customization, localization, or branding another highly practical benefit of the separation that xul provides among application logic, presentation, and language text is the ease of customizing for different ...
... 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 javascript, and they can be used from c, c++, javascript, python, java, and perl. xpconnect is a technology which enables simple interoperation between xpcom and javascript. xpconnect allows javascript objects to transparently access and manipulate xpcom objects. it also enables javascript objects to present xpcom compliant interfaces to be called by xpcom objects. together, xpcom and xpconnect enable developers to create xul applications that require the raw processing power of compiled languages (c/c++) or access to the underlying operating system. xpinstall x...
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
rtoolbarpalette"> <toolbarbutton id="myextension-button" class="toolbarbutton-1" label="&toolbarbutton.label;" tooltiptext="&toolbarbutton.tooltip;" oncommand="myextension.ontoolbarbuttoncommand(event);"/> </toolbarpalette> notes: the id of the palette (browsertoolbarpalette in the example) depends on the window (the parent window of the toolbar you wish to insert a button). see below for the list of common palette ids. class="toolbarbutton-1" makes the toolbar button appear correctly in icons and text mode; it also adjusts padding. set the command to be executed when the button is clicked in the oncommand attribute. if you need to handle middle-click, add this line after the oncommand line. onclick="checkformiddleclick(this, event)" you can also handle middle-click an...
... tutorial. although the article covers creating an entire toolbar, rather than just a button, it has a great explanation of the techniques we'll use here. icon size toolbar buttons can have two different sizes -- big and small. this means you'll need to provide two icons for each of your toolbar buttons. ...
...to atta...
Adding Buttons - Archive of obsolete content
se is the button tag. this element is used to create simple buttons. the button element has two main properties associated with it, a label and an image. you need one or the other or both. thus, a button can have a label only, an image only or both a label and an image. buttons are commonly used for the ok and cancel buttons in a dialog, for example. syntax of buttons the button tag has the following syntax: <button id="identifier" class="dialog" label="ok" image="images/image.jpg" disabled="true" accesskey="t"/> the attributes are as follows, all of which are optional: id a unique identifier so that you can identify the button with. you'll see this attribute on all elements. you'll want to use this if you want to refer to the button in a style sheet or scri...
...thers will be discussed later. some examples of buttons example 1 : source view <button label="normal"/> <button label="disabled" disabled="true"/> the examples above will generate the buttons in the image. the first button is a normal button. the second button is disabled so it appears greyed out. we'll start by creating a simple find button for the find files utility. the example code below shows how to do this. <button id="find-button" label="find"/> note: firefox does not allow you to open chrome windows from web pages, so the view links in the tutorial will open in normal browser windows. due to this, the buttons will appear to stretch across the window. you can add align="start" to the window tag to prevent the stretching. the findfile.xul example let's add this code to th...
...ks in the tutorial will open in normal browser windows. due to this, the buttons will appear to stretch across the window. you can add align="start" to the window tag to prevent the stretching. the findfile.xul example let's add this code to the file findfile.xul that we created in the previous section. the code needs to be inserted in-between the window tags. ...
Creating Dialogs - Archive of obsolete content
alert("you pressed ok!"); return true; } function docancel(){ alert("you pressed cancel!"); return true; } </script> <description value="select a button"/> </dialog> you may place any elements that you wish in a dialog. the dialog element has some additional attributes that windows do not have. the buttons attribute is used to specify which buttons should appear in the dialog. the following values may be used, seperated by commas: accept - an ok button cancel - a cancel button help - a help button disclosure - a disclosure button, which is used for showing more information you can set code to execute when the buttons are pressed using the ondialogaccept, ondialogcancel, ondialoghelp and ondialogdisclosure attributes. if you try the example above, you will find that the do...
... next, we'll see how to open file dialogs. « previousnext » ...
... next, we'll see how to open file dialogs. « previousnext » ...
Creating a Wizard - Archive of obsolete content
the wizards are often used to help the user perform a complex task. each page contains a single question or a set of related questions. after the last page, the operation is carried out. ...
...lled when the back, next and cancel buttons are pressed respectively. these functions are called regardless of which page is currently displayed. to have different code called depending on which page you are on, use the onpagerewound or onpageadvanced attributes on a wizardpage element. they work in a similar way to the other functions except that you can use different code for each page. this allows you to validate the input entered on each page before the user continues. a third option is to use the onpagehide and onpageshow attributes on the wizardpage element. these methods will be called when the page is hidden or shown, regardless of which button was pressed (except when cancel is pressed -- you need to use onwizardcancel to check for this.) these three methods should provide enough ...
...the user continues. a third option is to use the onpagehide and onpageshow attributes on the wizardpage element. these methods will be called when the page is hidden or shown, regardless of which button was pressed (except when cancel is pressed -- you need to use onwizardcancel to check for this.) these three methods should provide enough flexibility to handle navigation as you need to. the following is a summary of attribute functions that are called when the user presses next, in the order that they will be checked. as soon as one returns false, the navigation will be cancelled. attribute place on tag when it is called pagehide wizardpage called on the page that the user is leaving. pageadvanced wizardpage called on the page the user is l...
Cross Package Overlays - Archive of obsolete content
ou could add menu items or toolbars to the mozilla browser window. we'll use this feature to add a toolbar to the mozilla browser window. the mozilla mail application uses overlays to add content to the browser window. for example, if mail is not installed, there will be no new message command. however, if mail is installed, an overlay will be applied to the menu to add the new message command. below, we'll add a find files toolbar to the browser. it probably wouldn't be useful to have this feature, but we'll do it anyway. mozilla allows you to add a list of overlays to the contents.rdf file that you use to list chrome packages, skins and locales. once you have created an overlay, you can add it to the contents.rdf file. then add items, one for each window that you want the overlay to apply t...
...<code>navigator-toolbox</code>" to "<code>browser-toolbox</code>" in firefox 3 beta 3. you can support both firefox 2 and earlier and firefox 3 by duplicating the <code><span class="plain">' .. <toolbox> .. '</span></code> section with that id. to add this overlay to the manifest file, we need to add two resources. first, we add one for each window that we are applying an overlay to. the code below should be added into contents.rdf just before the closing rdf tag. <rdf:seq about="urn:mozilla:overlays"> <rdf:li resource="chrome://navigator/content/navigator.xul"/> </rdf:seq> this declares that we are adding a overlay window, a child of the root overlay node (urn:mozilla:overlays). you can add additional nodes for any other windows that you want to apply overlays to by adding additiona...
...information in the chrome/overlayinfo directory. you do not need to manually modify the files in this directory. it is automatically generated and modified when mozilla is first run or when new packages are installed. however, you can force the data to be rebuilt by deleting this directory and the chrome.rdf file. as a side note, you can use a similar technique to apply extra style sheets. the following example shows how: <rdf:seq about="urn:mozilla:stylesheets"> <rdf:li resource="chrome://messenger/content/messenger.xul"/> </rdf:seq> <rdf:seq about="chrome://messenger/content/messenger.xul"> <rdf:li>chrome://blueswayedshoes/skin/myskinfile.css</rdf:li> </rdf:seq> next, we'll see how to create an installer for a xul application. « previousnext » ...
Groupboxes - Archive of obsolete content
abeled using the caption element. the groupbox is displayed in a special way—usually with a beveled border and a caption, although you can change the appearance using css. you can create a caption for your groupbox by inserting a caption element as the first child. groupboxes are box elements, so you can use the box attributes, such as orient and flex. a simple groupbox example the example below shows a simple groupbox: example 1 : source view <groupbox> <caption label="answer"/> <description value="banana"/> <description value="tangerine"/> <description value="phone booth"/> <description value="kiwi"/> </groupbox> this will cause four pieces of text to be displayed surrounded by a box with the label answer. note that the groupbox has a vertical orientation by default whic...
...es"/> </groupbox> in this example, a checkbox has been used as a caption. we might use a script to enable and disable the contents of the groupbox when the checkbox is checked and unchecked. the groupbox contains a horizontal box with a label and textbox. both the textbox and groupbox have been made flexible so the textbox expands when the window is expanded. the additional checkbox appears below the textbox because of the vertical orientation of the groupbox. we'll add a groupbox to the find files dialog in the next section. radio groups you can use the radiogroup element to group radio elements together. the radiogroup is a type of box. you can put any element you want inside it, and apart from its special handling of radio buttons, it works like any other box. any radio buttons placed ...
...roup element to group radio elements together. the radiogroup is a type of box. you can put any element you want inside it, and apart from its special handling of radio buttons, it works like any other box. any radio buttons placed inside the radio group will be grouped together, even if they are inside nested boxes. this could be used to add extra elements within the structure, such as in the following example: example 3 : source view <radiogroup> <radio id="no" value="no" label="no number"/> <radio id="random" value="random" label="random number"/> <hbox> <radio id="specify" value="specify" label="specify number:"/> <textbox id="specificnumber"/> </hbox> </radiogroup> note that the radiogroup element does not draw a border around it. you should place a groupbox element arou...
Introduction - Archive of obsolete content
orial will demonstrate creating a simple find file user interface, much like that provided by the macintosh's 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 ti...
... of menus, trees and other elements can be populated with this data, or with your own data supplied in an rdf file. there are several ways you can use xul: firefox extension an extension adds functionality to the browser itself, often in the form of extra toolbars, context menus, or customizations to the browser's user interface. this is done using a feature of xul called an overlay, which allows the ui provided from one source, in this case, the firefox browser, to be merged together with the ui from the extension. extensions may also be applied to other mozilla based products such as thunderbird. standalone xulrunner application xulrunner is a packaged version of the mozilla platform which allows you to create standalone xul applications. a browser isn't required to run these applica...
...ever, these types of applications do not have security restrictions placed on them, so they may access local files and read and write preferences, for example. for extensions, the xul files and associated scripts and images used by an application would 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...
More Menu Features - Archive of obsolete content
inside other menus (nested menus) using the existing elements. remember that you can put any element inside a menupopup. we've looked at placing menuitems and menuseparators in menupopups. however, you can create submenus by simply placing the menu element inside the menupopup element. this works because the menu element is valid even when it isn't directly placed inside a menu bar. ...
... check placed beside the command and a feature that is disabled has no check. when the user selects the menu, the check state is switched. you may also want to create radio buttons on menu items. the checks are created in a similar way to the checkbox and radio elements. this involves 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 attribut...
...o check is used when you want a group of menu items where only one item can be checked at once. an example might be a font menu where only one font can be selected at a time. when another item is selected, the previously selected item is unchecked. in order to group a set of menu items together, you need to put a name attribute on each one to group. set the value to the same string. ...
Scrolling Menus - Archive of obsolete content
« previousnext » this section will describe scrolling menus and how to use the mechanism with other elements. creating a large menu you might wonder what happens if you create a menu with a lot of commands on it, such that all the items won't fit on the screen at once. mozilla will provide a scrolling mechanism that will allow you to scroll through the items. if the available space is too small, arrows will appear on each end of the menu. if you move the mouse over the arrows, the menu will scroll up and down. if the available space is large enough, the arrows will not appear. note that the exact behavior of the scrolling will depend on the current theme. this behavior is automatic. you do not have to do anything in order to get scrolling menus. it will apply to menus on ...
...mplemented using an arrowscrollbox element. this element can be used to create a scrolling box with arrows. the arrowscrollbox can be used anywhere a regular box can be used. you don't have to use it in menus. it is always a vertical box and may contain any elements inside it. you could use it to implement a list when you don't want it to be a drop-down. ...
...se it to implement a list when you don't want it to be a drop-down. example - scrolling list of buttons the following example shows how to create a scrolling list of buttons (you will need to resize the window to see the arrow buttons): example 1 : source view <arrowscrollbox orient="vertical" flex="1"> <button label="red"/> <button label="blue"/> <button label="green"/> <button label="yellow"/> <button label="orange"/> <button label="silver"/> <button label="lavender"/> <button label="gold"/> <button label="turquoise"/> <button label="peach"/> <button label="maroon"/> <button label="black"/> </arrowscrollbox> if you try this example, it will first open at full size. however, if you shrink the height of the window, the scroll arrows will appear. making the window larg...
The Chrome URL - Archive of obsolete content
the chrome url xul files can be referenced with a regular http url (or any type of url) just like html files. however, packages that are installed into mozilla's chrome system can be referenced with special chrome urls. the packages included with mozilla will already be installed but you can register your own. installed packages have the advantage that they don't have security restrictions placed on them, which is necessary for many applications. another advantage over other url types is that they automatically handle multiple themes and locales. ...
... 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 url is as follows: chrome://<package name>/<part>/<file.xul> the text <package name> is the package name, such as messenger or editor. all package names are case insensitive, but lowercase names are preferred. the <part> is either 'content', 'skin' or 'locale' depending on which part you want. <file.xul> is simply the filename. example: chrome://messenger/content/messenger.xul the example here refers to the mess...
...eed to change. here are some more examples. note how none of the urls specify which theme or locale is used and none specify a specific directory. chrome://messenger/content/messenger.xul chrome://messenger/content/attach.js chrome://messenger/skin/icons/folder-inbox.gif chrome://messenger/locale/messenger.dtd to refer to subdirectories, you can just add them to the end of the chrome url. the following url will refer to the bookmarks window, listed for firefox: chrome://browser/content/bookmarks/bookmarksmanager.xul you can enter chrome urls anywhere normal urls can be used. you can even enter them directly into the url bar in a firefox browser window. if you enter the url mentioned above into the browser's address bar, you should see that window appear like a web page might do and for the ...
Tree Box Objects - Archive of obsolete content
position of 100. naturally, it doesn't really matter what the value of the x coordinate is since rows always take up the entire horizontal space of the tree. one important thing to note is that the coordinates are measured from the upper left corner of the containing document, not the edge of the tree itself. this makes it easy to pass event coordinates directly to these functions, as in the following example of the getcellat() function. example 2 : source view <script> function updatefields(event){ var row = {}, column = {}, part = {}; var tree = document.getelementbyid("thetree"); var boxobject = tree.boxobject; boxobject.queryinterface(components.interfaces.nsitreeboxobject); boxobject.getcellat(event.clientx, event.clienty, row, column, part); if (column.value && typeof ...
...f the row the mouse is over, since we call it with the event coordinates of a mousemove event. if the coordinate is not over a row, the row value will be set to -1. the column is a column object in mozilla 1.8 and later. in earlier versions, columns are identified with a string, the id of the column. in later versions, a separate column object exists, which can be queried for column data. the following line is used so that the example above will work in all versions. if (column.value && typeof column.value != "string") { column.value = column.value.id; } if the column is a string, we are running on mozilla 1.7 or earlier, but for later versions we get the column id from the column object. if you are writing code for multiple versions, you should check for this as above. the last argume...
...e 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 on and just want the row and column. to go in reverse and get the coordinates of a specific cell, use the getcoordsforcellitem() function. it takes seven arguments, as described below. var x = {}, y = {}, width = {}, height = {}; if (typeof tree.columns != "undefined") column = tree.columns[column]; tree.boxobject.getcoordsforcellitem( row, column, part, x, y, width, height ); the row, column, and part arguments are similar to those returned from the getcellat() function. again, the column should be either a string or a column object depending on which version you are using...
Tree Selection - Archive of obsolete content
o change the selection by using the cursor keys. if the user holds down the cursor key to rapidly scroll through the items, the event handler is not called until the user stops. this results in a performance improvement. this also means that the highlight will appear on several items even though the select event is never fired for those items. the syntax of the onselect() event handler is shown below. <tree id="treeset" onselect="alert('you selected something!');"> tree indices the tree has a property currentindex, which can be used to get the currently selected item, where the first row is 0. child items are included in the count just after their parents. this means that if there are 3 top-level items and each has two child items, there will be a total of 9 items. the first item (at index 0...
... next item at index 1 will be its first child. the second child will be at index 2 and the second parent item will be at position 3 and so on. in the image, there are eight rows displayed, of which two are selected. the first selected row has an index of 4 and the second has an index of 7. the rows that are not displayed are not included in the index count. multiple selection for trees that allow multiple selection, getting the list of selected rows is a bit more complicated. the tree's view has a selection property which holds information about the selected rows. this selection will be an nsitreeselection object. the view doesn't need to implement this object itself, the tree will assign a selection object to the view's selection property when the view is attached to a tree. from the tre...
...unction. it takes a row index as an argument and returns true if that row is selected. alert(tree.view.selection.isselected(3)); modifying the tree selection the selection object has a number of functions which may be used to change the selection. the simplest function is the select() function, which deselects any rows that are currently selected and selects one specific row. for example, the following code will select the row at index 5: tree.view.selection.select(5); note that you should not just change the tree's currentindex property to change the selection. instead, you should use the selection's select function as in the example above. you can select all rows with the selectall() function. note that rows nested inside containers that are not open will not be selected. naturally, this ...
Tree View Details - Archive of obsolete content
chical 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 before it with a lower nesting value. all of these methods must be implemented by the view for children to be handled properly. containers there are also three functions, iscontainer, iscontainerempty and iscontaineropen that are used to handle a parent item in the tree. the iscontainer method should return true if a row is a container and might contain children. the iscontainerempty method should return true i...
...); if (nextlevel == thislevel) return true; if (nextlevel < thislevel) break; } return false; } the hasnextsibling function needs to return true if there is a row at the same level after a given row. the code above uses a brute force method which simply iterates over the rows looking for one, returning true if a row exists with the same level and false once it finds a row that has a lower level. in this simple example, this method is fine, but a tree with a larger set of data will want to use a more optimal method of determining whether a later sibling exists. opening or closing a row the final function of note is toggleopenstate, which is the most complex. it needs to modify the visibledata array when a row is opened or closed. toggleopenstate: function(idx) { var item = t...
...e number of rows to insert. in the code above we indicate that the starting row is the value of 'idx' plus one, which will be the first child under the parent. the tree will use this information and add space for the appropriate number of rows and push the rows afterwards down. make sure to pass the right number or the tree might redraw incorrectly or try to draw more rows than necessary. the following code is used to delete rows when a row is closed. item[2] = false; var thislevel = this.getlevel(idx); var deletecount = 0; for (var t = idx + 1; t < this.visibledata.length; t++) { if (this.getlevel(t) > thislevel) deletecount++; else break; } if (deletecount) { this.visibledata.splice(idx + 1, deletecount); this.treebox.rowcountchanged(idx + 1, -deletecount); } first, the item is...
Updating Commands - Archive of obsolete content
code. you will need to use these extra steps when invoking commands implemented by a controller. in addition, you will need to do this when creating your own menu commands, for instance to implement the edit menu commands in your own application. fortunately, the extra code is fairly simple. all we need to do is get the needed controller and call the command. a simple way of doing this is the following: var controller = document.commanddispatcher.getcontrollerforcommand("cmd_paste"); if (controller && controller.iscommandenabled("cmd_paste")){ controller.docommand(command); } the code above first retrieves the controller for the 'cmd_paste' command from the command dispatcher. then, it checks to see whether the command is enabled, and then executes the command using the docommand method o...
...implement a paste button. it is attached to the command which will invoke the command on the necessary controller when called. the code above is all you need to implement the functionality of the paste command in your application. the only other thing you need to do is ensure that the enabled status of the paste command, and therefore the button, is updated at the right time, which is described below. command updaters a command updater is a feature of the commandset element which allows it to update commands when certain events happen. you will need to think about when a command is valid and when it is not. in addition, you will need to consider when the state could change and when the commands should be updated. for example, the paste command is valid when a textbox has the focus and there i...
...ommand. if you have several commands to update, call the goupdatecommand method once for each command. note that the command updater will receive notifications about all focus events on all elements, even if other event handlers respond to the event. essentially, a command updater is like a global event handler. command updaters have a number of events which they can respond to which are listed below. it is also possible to create your own. focus: occurs when the focused element changes. select: occurs when the selected text changes. undo: occurs when the undo buffer changes. clipboard: occurs when the contents of the clipboard changes. the following example shows the command updaters used in the mozilla browser to update the edit menu commands. the functions used can be found in th...
XUL Changes for Firefox 1.5 - Archive of obsolete content
ated with the <richlistitem> element may be selected. see xul:richlistbox for more information. preferences system several elements have been added which may be used for creating preference windows. these windows are special types of dialogs which support several panels, each of which may be contained in the same file or a separate file. a set of icons will appear across the top of the dialog allowing the user to switch panels. along with the new preference elements and some additional attributes for existing elements, they make it easy to set preferences without having to use code. for more information, see preferences system. bfcache mozilla now caches the page's dom, so that navigating back and forward does not reload the page, making navigation much more efficient. the pageshow and pa...
...n some platforms. for instance <button icon="help"> will create a button with a help icon. this is used typically on gnome systems where possible values are: accept, cancel, help, open, save, find, clear, yes, no, apply, close, print, add, remove, refresh, go-forward, go-back, properties, select-font, select-color, network. <menulist> items in a <menulist> support the description attribute to allow for extra descriptive text to appear beside an item's label. the menulist modification methods appenditem and insertitemat take an extra description argument when creating items this way. <listbox> the removeitemat method was sometime non zero-based due to a bug (bug 236068). this has been fixed in firefox 1.5 and all code depending on this non zero-based behaviour should be changed. <stringbu...
...s this way. <listbox> the removeitemat method was sometime non zero-based due to a bug (bug 236068). this has been fixed in firefox 1.5 and all code depending on this non zero-based behaviour should be changed. <stringbundle> the <stringbundle> element has a strings property which may be used to retrieve an enumeration of all of the strings in the bundle. draggable tabs the tabbrowser now allows the user to rearrange tabs by dragging them. <tabbox> the <tabbox> element now supports a selectedindex attribute to specify the tab to be selected by default. loading overlays dynamically xul now supports loading overlays dynamically with the document.loadoverlay function. original document information author(s): neil deakin ...
XML - Archive of obsolete content
flexibility is a lack of implicit functionality -- the lack ofintuition, you might say, that xul has in interpreting what it is you want. in order to provide flexibility to you as adesigner of interfaces, xul offers no flexibility to you as acoder. you must be very careful about your syntax, and in particular about these four cardinal rules of xul: all events and attributes must be written in lowercase. unlike html, xul is very sensitive to case. all of the events and attributes -- even the javascript event listeners normally formatted in the javascript world with uppercase verbs (e.g., onclick, onload) -- must be lowercase or they are invalid. all strings must be double quoted. all of the values for all of the attributes declared in xul are strings. when an attribute is assigned ...
...in xul, elements must either be of the form <tag></tag> or <tag/> to be valid. for example, <html:img src="box.gif" /> is valid, but <html:img src="box.gif"> is not. all attributes must have a value. ...
... built-in flexibility for using extra resources like images, html elements, and other standards-based technologies. but this is all you need to build any interface. xul is timely. only quite recently have the standards out of which xul was fashioned matured to a level where they might really be powerful and flexible enough to support the sort of development that xul provides for. as the figure below indicates, xul is an amalgam of these different standards: css for styling or "skinning", dom for the object model and scriptable access, javascript for the linking and behavior, rdf for resources, xml for the structure, and html for the content and some little extras. in this way, it's more like a developmentplatform or framework than a user interface language, particularly when it's used with r...
assign - Archive of obsolete content
e needed) attributes expr type: string for xml queries, an xpath expression which returns results. any namespace prefixes declared on the element may be used within the expression. var type: string for the xul assign attribute, this is the variable to assign the value to; otherwise it's a reference to a template variable such as "?name". ...
...tributes expr type: string for xml queries, an xpath expression which returns results. any namespace prefixes declared on the element may be used within the expression. var type: string for the xul assign attribute, this is the variable to assign the value to; otherwise it's a reference to a template variable such as "?name". ...
...t, 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, 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 addeventlist...
bbox - Archive of obsolete content
Archive › Mozilla › XUL › bbox
« xul reference home [ examples | attributes | properties | methods | related ] a horizontal box that is baseline aligned. it is equivalent to using an hbox element with an align attribute set to baseline. ...
... « xul reference home [ examples | attributes | properties | methods | related ] a horizontal box that is baseline aligned. it is equivalent to using an hbox element with an align attribute set to baseline. ...
...t, 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, 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 addeventlist...
binding - Archive of obsolete content
d within a bindings element. a binding is used to bind a variable to a node. like the triple element in syntax, it can be used to bind a particular property of a matched node to a particular variable name. that name can then be used within the action of a rule. ...
...ndings element. a binding is used to bind a variable to a node. like the triple element in syntax, it can be used to bind a particular property of a matched node to a particular variable name. that name can then be used within the action of a rule. ...
...idth properties object type: string the object of the element. it can be a variable reference, an rdf resource uri, or an rdf literal value. predicate type: uri the predicate 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. ...
bindings - Archive of obsolete content
of variable bindings for a rule. this element should be contained within a rule element and contain one or more binding elements. this element is optional in firefox 3/mozilla 1.9 and later; instead binding elements may be placed directly inside the rule element. more information is available in the template guide. ...
...bindings for a rule. this element should be contained within a rule element and contain one or more binding elements. this element is optional in firefox 3/mozilla 1.9 and later; instead binding elements may be placed directly inside the rule element. more information is available in the template guide. ...
... object type: string the object of the element. it can be a variable reference, an rdf resource uri, or an rdf literal value. predicate type: uri the predicate 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. ...
box - Archive of obsolete content
Archive › Mozilla › XUL › box
overlap. the default orientation is horizontal. more information is available in the xul tutorial. ...
... default orientation is horizontal. more information is available in the xul tutorial. ...
...t, 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, 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 addeventlist...
broadcaster - Archive of obsolete content
omatically. an onbroadcast event will be sent to the observers when a change is made. for menuitems or buttons that just want to have their disabled status set when the feature should be disabled, you should use a command element instead. more information is available in the broadcasters and observers xul tutorial. ...
...n onbroadcast event will be sent to the observers when a change is made. for menuitems or buttons that just want to have their disabled status set when the feature should be disabled, you should use a command element instead. more information is available in the broadcasters and observers xul tutorial. ...
...t, 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, 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 addeventlist...
broadcasterset - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a container element for broadcaster elements. the broadcasterset and its descendants are not displayed. more information is available in the xul tutorial. ...
... « xul reference home [ examples | attributes | properties | methods | related ] a container element for broadcaster elements. the broadcasterset and its descendants are not displayed. more information is available in the xul tutorial. ...
...t, 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, 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 addeventlist...
checkbox - Archive of obsolete content
an 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 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. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (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; } disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is disabled. disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, a...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. src ty...
colorpicker - Archive of obsolete content
disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. color ...
...tional state. color type: color string the currently selected color. this is modified when the user selects a color. you can assign a string of the form #rrggbb to this property to change the selected color. overview an onchange attribute is an event listener to the object for the event change. a change event is fired in different ways for different xul input elements as listed below: onchange type: script code textbox when enter key is pressed radio/check box when the state is changed select list when the selected item is changed what is accessible the script context at this point can only access the following things: global values/functions i.e. window, document, or any of the functions/objects/variables bound to the wind...
...this attribute only has any effect when used inside a prefwindow. more information is available in the preferences system article. tabindex type: integer the tab order of the element...
column - Archive of obsolete content
in each successive cell of the grid. the column with the most child elements determines the number of rows in each column. 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. ...
...ssive cell of the grid. the column with the most child elements determines the number of rows in each column. 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. ...
...t, 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, 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 addeventlist...
columns - Archive of obsolete content
mns to appear in the grid. the columns element may be nested inside another columns element. other elements placed inside a columns element occupy the full height of the grid and are placed in their corresponding positions between the columns. more information about columns is available in the xul tutorial. example see grid for an example. ...
... in the grid. the columns element may be nested inside another columns element. other elements placed inside a columns element occupy the full height of the grid and are placed in their corresponding positions between the columns. more information about columns is available in the xul tutorial. example see grid for an example. ...
...t, 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, 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 addeventlist...
command - Archive of obsolete content
s function has the advantage that the command will be sent to the part of the ui which will respond to it. typically, this will be the currently focused element. like a broadcaster, commands forward attributes to other elements. more information is available in the xul tutorial. ...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. label t...
... use in the content. this means that, to execute these commands, key events won't be passed to content, and event listeners registered for them in content will not be executed. currently, the 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. ...
conditions - Archive of obsolete content
mark (?). when evaluating the rule for a particular rdf resource, the variables are replaced with values from the resource. if all variables can be replaced, the rule matched. this element is used with firefox 2/mozilla 1.8 and earlier instead of the query element. more information is available in the xul tutorial. ...
...n evaluating the rule for a particular rdf resource, the variables are replaced with values from the resource. if all variables can be replaced, the rule matched. this element is used with firefox 2/mozilla 1.8 and earlier instead of the query element. more information is available in the xul tutorial. ...
...t, 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, 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 addeventlist...
datepicker - Archive of obsolete content
three types are available, which can be specified using the type attribute. normal - a datepicker with three fields for entering the year, month and date. grid - a datepicker with a calendar grid for selecting a date. popup - a normal datepicker with three fields, but with an additional dropdown button to display a popup grid. there are several ways to set the selected day. in xul, the value attribute may be set to a value of the form yyyy-mm-dd to initialize the datepicker to a certain date. ...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. firstda...
...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 higher tabindex are later in the tab sequence. type type: one of the values below you can set the type attribute to one of the values below to specify the type of datepicker to use normal a datepicker with three fields for entering the year, month and date. this is the default value so do not specify the type attribute if this kind is desired. grid a datepicker that displays a calendar grid where one mo...
deck - Archive of obsolete content
Archive › Mozilla › XUL › deck
"2"> <description value="this is the first page"/> <button label="this is the second page"/> <box> <description value="this is the third page"/> <button label="this is also the third page"/> </box> </deck> attributes selectedindex type: integer gets and sets the index of the currently selected panel. the first item is at index 0. ...
...iption value="this is the first page"/> <button label="this is the second page"/> <box> <description value="this is the third page"/> <button label="this is also the third page"/> </box> </deck> attributes selectedindex type: integer gets and sets the index of the currently selected panel. the first item is at index 0. ...
...assigning -1 to this property, all items will be deselected. returns -1 if no items are selected do not hide panels; the deck element only understands visible panels. selectedpanel 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. ...
dialogheader - Archive of obsolete content
an ellipsis will be used in place of the cropped text. if the box direction is reversed, the cropping is reversed. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (or the maxwidth attribute) to override this size. ...
...example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } description type: string descriptive text to appear in addition to the dialog title. title type: string the text to appear in the title bar of the window. ...
dropmarker - Archive of obsolete content
a dropmarker is a button with an arrow which will reveal more details when pressed. a dropmarker is not intended to be used as a separate element, but as part of another element. for instance the menulist and the popup type of datepicker use a dropmarker, that when pressed, will reveal a popup menu. ...
... is a button with an arrow which will reveal more details when pressed. a dropmarker is not intended to be used as a separate element, but as part of another element. for instance the menulist and the popup type of datepicker use a dropmarker, that when pressed, will reveal a popup menu. ...
...inal, 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. ...
editor - Archive of obsolete content
e provided. if you do not set the editortype attribute on an editor, you must enable editing using the makeeditable method. to specify the document to load in the editor use the src attribute. however, an issue is that if you specify the src attribute initially on the editor tag in the xul file, the document does not become editable by default. to enable editing on an editor, do either of the following: set the src attribute on the editor after the outer window has loaded, for example, in the onload handler. you might also set the src attribute based on what the user selects from a file dialog. in this case, set the editortype attribute on the editor. call the makeeditable method to make the document loaded in the editor editable. enable the design mode of the document loaded in the edi...
...ry"/> once editable, the document can have special formatting and other html pieces added to it using the document.execcommand method: var editor = document.getelementbyid("myeditor"); // toggle bold for the current selection editor.contentdocument.execcommand("bold", false, null); see the midas overview for more command strings. attributes editortype type: one of the values below the type of editor to use. this value will be overridden depending on the content type of the document in the editor. html an html editor. text a plaintext editor. src type: uri the uri of the content to appear in the element. type type: string if set to the string content-primary, this editor becomes the primary content for the page. the window...
...jsobject to obtain a dom(html) window object docshell type: nsidocshell this read-only property contains the nsidocshell object for the document. editingsession type: nsieditingsession the editing session for the editor which is used to initialize the editor. you would not normally need to use this. editortype type: one of the values below the type of editor to use. this value will be overridden depending on the content type of the document in the editor. html an html editor. text a plaintext editor. webbrowserfind type: nsiwebbrowserfind this read-only property contains an nsiwebbrowserfind object which can be used to search for ...
grippy - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] an element that may be used inside a splitter which can be used to collapse a sibling element of the splitter. more information is available in the xul tutorial. ...
... « xul reference home [ examples | attributes | properties | methods | related ] an element that may be used inside a splitter which can be used to collapse a sibling element of the splitter. more information is available in the xul tutorial. ...
...t, 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, 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 addeventlist...
groupbox - Archive of obsolete content
or instance, only the caption appears with no border around the group. more information is available in the xul tutorial. ...
...only the caption appears with no border around the group. more information is available in the xul tutorial. ...
...inal, 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. ...
hbox - Archive of obsolete content
Archive › Mozilla › XUL › hbox
ated ] a container element which can contain any number of child elements. this is equivalent to the box element, except it defaults to horizontal orientation. more information is available in the xul tutorial. ...
...ntainer element which can contain any number of child elements. this is equivalent to the box element, except it defaults to horizontal orientation. more information is available in the xul tutorial. ...
...t, 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, 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 addeventlist...
listcols - Archive of obsolete content
t box has a single column. ...
...ingle column. ...
...t, 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, 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 addeventlist...
member - Archive of obsolete content
s | attributes | properties | methods | related ] used within a rule's conditions element to match elements that are containers or are contained within another element. both the container and child attributes may use variables. more information is available in the xul tutorial. ...
...es | properties | methods | related ] used within a rule's conditions element to match elements that are containers or are contained within another element. both the container and child attributes may use variables. more information is available in the xul tutorial. ...
...ype: ? a variable reference to a node that is expected to be a child of the element that is referred to by the container element. container type: ? a variable reference to a node 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. ...
observes - Archive of obsolete content
attribute name the attribute that the observer is observing. when the value of the attribute changes, the broadcast event is called on the observer. use the value * to observe all attribute of the broadcasters. the id, ref, and persist attributes are not observed. element type: id the id of the broadcaster element that the observer is observing. ...
...e the attribute that the observer is observing. when the value of the attribute changes, the broadcast event is called on the observer. use the value * to observe all attribute of the broadcasters. the id, ref, and persist attributes are not observed. element type: id the id of the broadcaster element that the observer is observing. ...
...t, 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, 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 addeventlist...
page - Archive of obsolete content
Archive › Mozilla › XUL › page
« xul reference home [ examples | attributes | properties | methods | related ] similar to a window, except it should be used for xul files that are to be loaded into an iframe. ...
... « xul reference home [ examples | attributes | properties | methods | related ] similar to a window, except it should be used for xul files that are to be loaded into an iframe. ...
...t, 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, 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 addeventlist...
popupset - Archive of obsolete content
optional; the given elements need not appear in a popupset container. more information is available in the xul tutorial. ...
... given elements need not appear in a popupset container. more information is available in the xul tutorial. ...
...t, 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, 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 addeventlist...
query - Archive of obsolete content
Archive › Mozilla › XUL › query
r attribute and may optionally contain assign elements. for sql datasources, the query should contain an sql statement as text. attributes expr examples (example needed) attributes expr type: string for xml queries, an xpath expression which returns results. any namespace prefixes declared on the element may be used within the expression. ...
...nd may optionally contain assign elements. for sql datasources, the query should contain an sql statement as text. attributes expr examples (example needed) attributes expr type: string for xml queries, an xpath expression which returns results. any namespace prefixes declared on the element may be used within the expression. ...
...t, 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, 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 addeventlist...
queryset - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a container for query elements when more than one query is used. for more information, see multiple queries. ...
... « xul reference home [ examples | attributes | properties | methods | related ] a container for query elements when more than one query is used. for more information, see multiple queries. ...
...t, 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, 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 addeventlist...
radiogroup - Archive of obsolete content
if this attribute is set, the element is disabled. disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not...
... disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. focused...
... this attribute only has any effect when used inside a prefwindow. more information is available in the preferences system article. 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 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 merely associate data with an element, you could 1) use another attribute like "value2" or "data-myatt" (as in the html5 draft), as xul does not require ...
row - Archive of obsolete content
Archive › Mozilla › XUL › row
ows 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. ...
...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. ...
...t, 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, 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 addeventlist...
script - Archive of obsolete content
pplication/javascript. note: if the javascript file is in chrome://, setting this attribute to application/javascript will always use the latest available javascript version. if you omit this attribute, the default (and older) javascript version is used (like you get when including a javascript file from web content without specifying a version number). ...
...vascript. note: if the javascript file is in chrome://, setting this attribute to application/javascript will always use the latest available javascript version. if you omit this attribute, the default (and older) javascript version is used (like you get when including a javascript file from web content without specifying a version number). ...
...t, 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, 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 addeventlist...
scrollcorner - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] this element is used for the small box where the horizontal and vertical scrollbars meet. ...
... « xul reference home [ examples | attributes | properties | methods | related ] this element is used for the small box where the horizontal and vertical scrollbars meet. ...
...t, 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, 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 addeventlist...
spacer - Archive of obsolete content
place spacing within a container. if you don't specify that the spacer has a size or is flexible, the spacer does not occupy any space. if you want a small gap, consider using a separator instead. more information is available in the xul tutorial. ...
...g within a container. if you don't specify that the spacer has a size or is flexible, the spacer does not occupy any space. if you want a small gap, consider using a separator instead. more information is available in the xul tutorial. ...
...t, 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, 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 addeventlist...
spinbuttons - Archive of obsolete content
ed ] spin buttons are two arrows, one to increase a value and one to decrease a value. spin buttons are not used as separate elements, but are used in combination with other elements to create a control that can be increased and decreased. for instance, spinbuttons are used for the number type textbox, and with the timepicker and datepicker. ...
...uttons are two arrows, one to increase a value and one to decrease a value. spin buttons are not used as separate elements, but are used in combination with other elements to create a control that can be increased and decreased. for instance, spinbuttons are used for the number type textbox, and with the timepicker and datepicker. ...
...t, 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, 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 addeventlist...
stack - Archive of obsolete content
Archive › Mozilla › XUL › stack
top="10" bottom="10"/> </hbox> <hbox> <!-- some content here. --> </hbox> </stack> in this example, the resulting width of the top-most hbox will be 400px (600px - 200px - 0) : <stack width="600"> <hbox flex="1"> <!-- content --> </hbox> <hbox left="0" right="200" > <!-- some content here. ...
...tom="10"/> </hbox> <hbox> <!-- some content here. --> </hbox> </stack> in this example, the resulting width of the top-most hbox will be 400px (600px - 200px - 0) : <stack width="600"> <hbox flex="1"> <!-- content --> </hbox> <hbox left="0" right="200" > <!-- some content here. ...
...t, 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, 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 addeventlist...
statusbar - Archive of obsolete content
ong the bottom of a window. it is virtually equivalent to a standard box, but may be rendered differently. contains statusbarpanels. ...
...m of a window. it is virtually equivalent to a standard box, but may be rendered differently. contains statusbarpanels. ...
...rdinal, 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. ...
stringbundle - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] an element which can be used to load localized resources from property files. stringbundles should be placed inside a stringbundleset element. a property file is a list of property key-value pairs each on a separate line. the key and value is separated with an equals sign. for example, the following defines two properties: message.displayerror=an error occured trying to display this message message.namealreadyused=the name %s is already being used by another account. more information is available in the xul tutorial. the "src" attribute accepts only absolute chrome:// urls (see bugs 133698, 26291) attributes src properties applocale , src, stringbundle, strings methods getf...
...able in the xul tutorial. the "src" attribute accepts only absolute chrome:// urls (see bugs 133698, 26291) attributes src properties applocale , src, stringbundle, strings methods getformattedstring, getstring examples (example needed) attributes src type: uri the uri of the property file that contains the localized strings. ...
...ul tutorial. the "src" attribute accepts only absolute chrome:// urls (see bugs 133698, 26291) attributes src properties applocale , src, stringbundle, strings methods getformattedstring, getstring examples (example needed) attributes src type: uri the uri of the property file that contains the localized strings. ...
stringbundleset - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a container for stringbundle elements. ...
... « xul reference home [ examples | attributes | properties | methods | related ] a container for stringbundle elements. ...
...t, 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, 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 addeventlist...
tabpanel - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a individual panel in a tabpanels element. this element is optional and you may just use any other container in place of it. more information is available in the xul tutorial. ...
... « xul reference home [ examples | attributes | properties | methods | related ] a individual panel in a tabpanels element. this element is optional and you may just use any other container in place of it. more information is available in the xul tutorial. ...
...t, 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, 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 addeventlist...
template - Archive of obsolete content
r reference variable. if not specified, the variable specified in the uri attribute of the content tag in the template's first rule is used. member type: string may optionally be set to the variable to use as the member variable. if not specified, the variable specified in the uri attribute in the action body of the template's first rule is used. ...
...ariable. if not specified, the variable specified in the uri attribute of the content tag in the template's first rule is used. member type: string may optionally be set to the variable to use as the member variable. if not specified, the variable specified in the uri attribute in the action body of the template's first rule is used. ...
...t, 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, 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 addeventlist...
textnode - Archive of obsolete content
e attribute. this is useful if you want to use the html element or other elements that have text content inside them instead of in attributes. this element does nothing outside of a template. attributes value examples (example needed) attributes value type: uri the text value to display. this value should be an rdf property (predicate). ...
... this is useful if you want to use the html element or other elements that have text content inside them instead of in attributes. this element does nothing outside of a template. attributes value examples (example needed) attributes value type: uri the text value to display. this value should be an rdf property (predicate). ...
...t, 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, 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 addeventlist...
titlebar - Archive of obsolete content
ive titlebar of normal windows; instead, it's used to create custom titlebars for chromeless windows. if the titlebar is in a panel element, dragging it will move the panel. elements inside the titlebar usually don't receive any mouse events, so e.g. buttons inside it can't be clicked and textboxes can't be focused with the mouse. if you don't want this behavior, you can override it by setting allowevents="true" on the titlebar element. the titlebar will send a command event after the move is complete. examples this xul file will create a hud-style window that can be moved with the mouse. it will close if the mouse button is released. <?xml version="1.0"?> <window title="movable hud window" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" width="300" ...
... style="background: rgba(30, 30, 30, 0.9); -moz-border-radius: 10px; -moz-box-shadow: 0 1px 8px rgba(0, 0, 0, 0.8); margin: 8px 12px 16px;"/> </window> it can be opened from the error console like this: open("file:///users/markus/sites/hudwindow.xul", "", "chrome=1, titlebar=0") 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, sortd...
... 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 note: the allowevents attribute did not work for title bars prior to firefox 3. 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, res...
toolbar - Archive of obsolete content
an effect on windows and needs to be combined with type="menubar" 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 ...
...lso 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. mode not in seamonkey 1.x type: one of the values below how the toolbarbuttons on the toolbar are displayed. icons show only icons. text show only text. full show both. toolbarname not in seamonkey 1.x type: string the name of the toolbar, which is listed on the show/hide toolbars menu. properties accessibletype type: integer a value indicating the type of accessibility object for the element. currentse...
...me of the toolbar, which is listed on the show/hide toolbars menu. properties accessibletype type: integer a value indicating the type of accessibility object for the element. currentset not in seamonkey 1.x type: comma-separated list of strings holds a comma-separated list of the ids of the items currently on the toolbar. for spacers, separators, and flexible spacers the following strings are used instead of ids: "spacer", "separator", "spring". an empty toolbar has a currentset value of "__empty". you may change the current set of items by setting this property. be careful, as setting this property doesn't automatically update the currentset attribute. firstpermanentchild not in seamonkey 1.x type: element the first permanent child of the toolbar. a perman...
toolbargrippy - Archive of obsolete content
properties | methods | related ] not in firefox the notch on the side of a toolbar which can be used to collapse and expand it. this element is used internally by the toolbar and should only be used directly when modifying its theme. more information is available in the xul tutorial. ...
... methods | related ] not in firefox the notch on the side of a toolbar which can be used to collapse and expand it. this element is used internally by the toolbar and should only be used directly when modifying its theme. more information is available in the xul tutorial. ...
...ugh, 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. ...
toolbarpalette - Archive of obsolete content
erlays the toolbarpalette with the idbrowsertoolbarpalette. ...
...olbarpalette with the idbrowsertoolbarpalette. ...
...t, 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, 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 addeventlist...
toolbarseparator - Archive of obsolete content
a separator between groups of toolbar items. it is functionally equivalent to a normal separator but some themes may apply a different appearance. ...
...etween groups of toolbar items. it is functionally equivalent to a normal separator but some themes may apply a different appearance. ...
...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. ...
toolbarset - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] firefox only this element is used as a container for custom toolbars, which are added in the custom toolbar dialog. ...
... « xul reference home [ examples | attributes | properties | methods | related ] firefox only this element is used as a container for custom toolbars, which are added in the custom toolbar dialog. ...
...ght, 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, 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 addeventlisten...
toolbarspacer - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] firefox only a space between toolbar items. ...
... « xul reference home [ examples | attributes | properties | methods | related ] firefox only a space between toolbar items. ...
...inal, 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. ...
toolbarspring - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] firefox only a flexible space between toolbar items. ...
... « xul reference home [ examples | attributes | properties | methods | related ] firefox only a flexible space between toolbar items. ...
...rdinal, 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. ...
treechildren - Archive of obsolete content
ne container rows in the tree. more information is available in the xul tutorial. attributes alternatingbackground attributes alternatingbackground obsolete since gecko 2.0 type: boolean if true, the background of the tree's rows will alternate between two colors. you can use the :-moz-tree-row css style to do this instead. ...
...rows in the tree. more information is available in the xul tutorial. attributes alternatingbackground attributes alternatingbackground obsolete since gecko 2.0 type: boolean if true, the background of the tree's rows will alternate between two colors. you can use the :-moz-tree-row css style to do this instead. ...
...t, 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, 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 addeventlist...
treecols - Archive of obsolete content
elated ] a group of treecol elements. there should one and only one treecols element in a tree. more information is available in the xul tutorial. attributes pickertooltiptext properties accessibletype examples (example needed) attributes pickertooltiptext type: string the text for the tooltip on the column picker. ...
...group of treecol elements. there should one and only one treecols element in a tree. more information is available in the xul tutorial. attributes pickertooltiptext properties accessibletype examples (example needed) attributes pickertooltiptext type: string the text for the tooltip on the column picker. ...
...inal, 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. ...
treerow - Archive of obsolete content
ed in a treechildren element inside the parent treeitem. more information is available in the xul tutorial. attributes properties examples (example needed) attributes properties type: space-separated list of property names sets the properties of the element, which can be used to style the element. for more information, see styling a tree. ...
...hildren element inside the parent treeitem. more information is available in the xul tutorial. attributes properties examples (example needed) attributes properties type: space-separated list of property names sets the properties of the element, which can be used to style the element. for more information, see styling a tree. ...
...t, 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, 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 addeventlist...
treeseparator - Archive of obsolete content
[ examples | attributes | properties | methods | related ] used to place a separator row in a tree. attributes properties examples (example needed) attributes properties type: space-separated list of property names sets the properties of the element, which can be used to style the element. for more information, see styling a tree. ...
... | attributes | properties | methods | related ] used to place a separator row in a tree. attributes properties examples (example needed) attributes properties type: space-separated list of property names sets the properties of the element, which can be used to style the element. for more information, see styling a tree. ...
...t, 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, 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 addeventlist...
triple - Archive of obsolete content
attributes object type: string the object of the element. it can be a variable reference, an rdf resource uri, or an rdf literal value. predicate type: uri the predicate 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. ...
... object type: string the object of the element. it can be a variable reference, an rdf resource uri, or an rdf literal value. predicate type: uri the predicate 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. ...
...t, 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, 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 addeventlist...
vbox - Archive of obsolete content
Archive › Mozilla › XUL › vbox
ods | related ] a container element which can contain any number of child elements. this is equivalent to the box element, except it defaults to vertical orientation. more information is available in the xul tutorial. ...
...d ] a container element which can contain any number of child elements. this is equivalent to the box element, except it defaults to vertical orientation. more information is available in the xul tutorial. ...
...t, 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, 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 addeventlist...
wizard - Archive of obsolete content
devtools:scratchpad - scratchpad windows navigator:view-source - the view source windows properties canadvance type: boolean this property is set to true if the user can press the next button to go to the next page. if this property is false, the user cannot navigate to the next page. set this property to true to indicate that the user can go to the next page. set to false to disallow moving to the next page. this has the effect of enabling or disabling the next button, or, on the last page of the wizard, the finish button. canrewind type: boolean this property is set to true if the user can press the back button to go to the previous page. if this property is false, the user cannot navigate to the previous page. set this property to true to indicate that the user can ...
...e effect of enabling or disabling the next button, or, on the last page of the wizard, the finish button. canrewind type: boolean this property is set to true if the user can press the back button to go to the previous page. if this property is false, the user cannot navigate to the previous page. set this property to true to indicate that the user can go back a page. set to false to disallow moving to the previous page. this has the effect of enabling or disabling the back button. currentpage type: wizardpage element this property returns the wizardpage element that is currently displayed. you can modify this value to change the current page. onfirstpage type: boolean this property is set to true if the user is on the first page, which may or may not be the first inde...
...d(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata « xul reference home advance( pageid ) return type: no return value call this method to go to the next page. this is equivalent to pressing the next button. the canadvance property must be set to true for the page to be changed. the pageid argument allows you to specify the index of the page to which to jump. supply null as the argument to go to the next page in the sequence. cancel() return type: no return value call this method to cancel and close the wizard. getbutton( type ) return type: button element returns the button element in the dialog corresponding to the given type. getpagebyid( pageid ) return type: wizardpage eleme...
Building XULRunner with Python - Archive of obsolete content
f particular interested is access to msaa and iaccessible2 via the python comtypes package. development machine setup first a word of warning that zonealarm has exhibited memory leaks that cause build machines to crash with rather spurious errors. you may want to uninstall it if you suspect this to be a problem. you will also want to disable any virus scanner resident monitoring as that will slow builds. ensure the pc is running xp with all the latest service packs and patches applied. microsoft c++ compiler is required and whilst the current free version is visual studio 8 express (msvc8) you will almost certainly want to use visual studio .net 2003 (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...
.... 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 project specific .mozconfig files as sometimes shown. it effectively specifies a release build that is not particularly suitable for debugging xulrunner itself. it uses the trunk (or latest) code in cvs so may be unstable. mk_add_options moz_objdir=@topsrcdir@/../obj-xulrunner mk_add_options moz_co_project=x...
...ons --disable-activex ac_add_options --disable-activex-scripting ac_add_options --disable-tests ac_add_options --enable-optimize to check out all the required source code and build it the first time with no local client.mk file, execute cd /c/projects cvs -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot co mozilla/client.mk cd mozilla make -f client.mk for subsequent updates from cvs followed by a build, use cd /c/projects/mozilla make -f client.mk which will also checkout client.mk itself for build only, without checkouts, use make -f client.mk build and see client.mk for other options. the built xulrunner can then be found asc:\projects\obj-xulrunner\dist\bin\xulrunner.exe. using python in xul applications add the following to yourprefs.js during development pref("brows...
calICalendarView - Archive of obsolete content
t picture of the current state of those nodes. it should be noted, however, that the methods and attributes implemented by a calicalendarview need not behave in any predictable fashion. for instance, when the showdate method of the the calendar-multiday-view (an implementation of this interface) will sometimes show an entire week of dates, and sometimes show only the single date passed in. this allows lack of required predictability allows calicalendarview implementations to be re-used in a variety of sitatuations. it also fueled the development, however, of the more predictable, but less flexible calidecoratedview, which usually contains an embedded calicalendarview. calendar/base/public/calicalendarview.idlscriptable please add a summary to this article. last changed in gecko ? ...
...ations, and deletions of items it may be displaying. note that in most cases, this attribute will be set by the consumers of calicalendarview very early in an application/extension's loading process. controller the controller for a calicalendarview is an implementation of calicalendarviewcontroller and provides an integral link with the code in which a calicalendarview may be used. this link allows the calicalendarview to have a way of creating, modifying, and deleting events based on user interaction with the dom nodes it controls, often without requiring any other user interaction. in general, therefore, a calicalendarview will not provide its own controller, but rather rely on other code to set this attribute. implementations should therefore be wary to check whether a controller has be...
...s 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 corresponding to the currently active item i...
2006-11-10 - Archive of obsolete content
summary: mozilla.dev.builds - november 4th to november 10th 2006 browser buttons november 4th: mojr wants to know if firefox has a similar feature that the new ie 6 has built in. this feature consists of creating buttons using a small program, that allows you to create shortcuts to a particular address. the button gets added to the toolbar, separate from the links. reflow branch build failed with vc 7.1 sp1 november 8th: roy received an error when he tried to reflow a branch build using vc 7.1 sp1. on the same day he posted the answer to his posting that he found in last weeks posting. click here to see the answer to the problem. building xulrunner application with mozilla november 8th: kirans is trying to build mozilla with xulrunner option on a windows machine. wh...
...that he set is home variable to c:\mozilla, and is not sure what he is doing wrong. november 9th: jonathan watt responded to his posting stating that he must have the wrong line endings in his mozconfig or some other script fill that he is probably using to run. ...
...ng line endings in his mozconfig or some other script fill that he is probably using to run. ...
NPVariant - Archive of obsolete content
t holds a value and the type of that value. the value is held in a union, and the type is one of types defined in the npvarianttype enumeration. syntax typedef struct _npvariant { npvarianttype type; union { bool boolvalue; int32_t intvalue; double_t doublevalue; npstring stringvalue; npobject *objectvalue; } value; } npvariant; fields the data structure has the following fields: type a member of the npvarianttype enumeration specifying the data type contained in the npvariant. value the value contained in the npvariant structure. it may be a boolean, integer, double, string, or object, depending on the variant type. javascript type to npvarianttype enumeration mapping when using npvariants to access javascript objects in the browser, or vise versa,...
...ration specifying the data type contained in the npvariant. value the value contained in the npvariant structure. it may be a boolean, integer, double, string, or object, depending on the variant type. ...
... npvariant_is_null() evaluates to true if v is of type npvarianttype_null. npvariant_is_boolean() evaluates to true if v is of type npvarianttype_bool. npvariant_is_int32() evaluates to true if v is of type npvarianttype_int32. npvariant_is_double() evaluates to true if v is of ty...
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
isable the plugin. as of firefox 3 (and any gecko 1.9 based application) the use of install.js scripts is no longer supported and plugins must either be shipped as an executable installer or in a bundle as described here. bundle structure toolkit bundles can be used for all add-ons including extensions, themes and plugins. plugin packages should only need to package a small set of files in the following structure in the xpi file: install.rdf plugins/ pluginlib.dll plugintypes.xpt the install.rdf file contains an install manifest that describes the plugin to the user. the library and scripting interfaces are held in the plugins directory. platform-specific files gecko 1.9.2 (firefox 3.6) and earlier prior to gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1), it was possible to p...
...an install manifest that describes the plugin to the user. the library and scripting interfaces are held in the plugins directory. platform-specific files gecko 1.9.2 (firefox 3.6) and earlier prior to gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1), it was possible to package multiple plugin libraries for different operating systems into a single xpi bundle. in the xpi you can use the following structure: platform/ linux_x86-gcc3/ plugins/ libplugin.so darwin_ppc-gcc3/ plugins/ libplugin.dylib more specific information can be found in the platform-specific subdirectories documentation. gecko 2.0 (firefox 4) and later gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) removed support for platform-specific subdirectories. instead, y...
...inimum 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 allows a remote update file to be read periodically and an updated version of the plugin offered to the user or to mark the plugin as compatible with a wider range of applications. this is performed by including an updateurl in the install manifest. this should point to an update.rdf file on the internet which will include the updated versions and version information for the plugin. ...
Theme changes in Firefox 3 - Archive of obsolete content
e 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 figuring out the changes you need to make. all file list all platforms file description of change browser/themes/*/browser/browser.css the width of the drag and drop indicator is no longer calculated during the drag (tabbrowser.xml). instead a '-moz-margin-start' ...
...smaller. may or may not affect other mac themes that use it. browser/themes/pinstripe/browser/browser.css .tabbrowser-tab[first-tab="true"] > .tab-image-left no longer has a margin-left. instead .tabs-left now displayed and given the same width as the former margin-left. it was already done this way in winstripe. changes in browser --- changes in global all platforms the yellow background for the location bar has been deprecated; instead, themes should style the new #identity-box element depending on its verifieddomain/verifiedidentity class. the go button is now located inside the location bar, so the image for it (chrome://browser/skin/go-arrow.png) needs to be smaller. the rule that's needed to show and hide the go button and other location bar icons is: #urlbar[pa...
...utton is now located inside the location bar, so the image for it (chrome://browser/skin/go-arrow.png) needs to be smaller. the rule that's needed to show and hide the go button and other location bar icons is: #urlbar[pageproxystate="invalid"] > #urlbar-icons > :not(#go-button) , #urlbar[pageproxystate="valid"] > #urlbar-icons > #go-button { visibility: collapse; } images to add add the following images: chrome://global/skin/icons/information-16.png used when presenting information notices. chrome://global/skin/icons/warning-16.png used when displaying warnings. images to remove the following images were removed: chrome://mozapps/skin/extensions/question.png no longer used. mac os x mac os x themes for firefox 3 should add these two rules to the end of chrome://global/s...
Browser Feature Detection - Archive of obsolete content
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. browser sniffing via api name detection the following tables list the api names defined for specific w3c dom apis and lists the percentage of names that your browser actually defines followed by a list of each of the api names tested along with an indication of whether the name was defined for your browser. it is clear from these test results that netscape 7.0x and mozilla firefox have the greatest dom support although internet explorer, safari,...
... 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 pagebreakafter true true true pagebreakbefore true true true pagebreakinside true false true pause true false true pauseafter true false true pausebefore true false true pitch true false false pitchran...
...me: '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', 'supported': false}, {name: 'pagebreakbefore', 'supported': false}, {name: 'pagebreakinside', 'supported': false}, {name: 'pause', 'supported': false}, {name: 'pauseafter', 'supported': false}, {name: 'pausebefore', 'supported': false}, {name: 'pitch', 'supported': false}, {name: 'pitchrange', 's...
-ms-scrollbar-arrow-color - Archive of obsolete content
a-value>? ) | rgba( <number>#{3} , <alpha-value>? )<hsl()> = hsl( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsl( <hue>, <percentage>, <percentage>, <alpha-value>? )<hsla()> = hsla( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsla( <hue>, <percentage>, <percentage>, <alpha-value>? ...
...]? ) | hsla( <hue>, <percentage>, <percentage>, <alpha-value>? ...
... ...
::-ms-check - Archive of obsolete content
other properties are ignored. ...
...other properties are ignored. ...
...]::-ms-check { border-color: red; /* this will make the border red when the button is checked. */ color: red; /* this will make the circle red when the button is checked. */ } input[type=checkbox]::-ms-check { border-color: green; /* this will make the box green when the button is checked. */ color: green; /* this will make the checkmark green when the button is checked. */ } result below is an example for you to try. the screenshot to the left shows what will happen when you check the buttons if you don't have access to internet explorer or edge. screenshotlive sample specifications not part of any specification. browser compatibility historically supported in internet explorer and edge before version 79. ...
::-ms-fill-upper - Archive of obsolete content
other properties are ignored. ...
...other properties are ignored. ...
...d-position-y -ms-high-contrast-adjust opacity outline-color outline-style outline-width padding-bottom padding-left padding-right padding-top transform transform-origin visibility width syntax ::-ms-fill-upper specifications not part of any specification. browser compatibility historically supported in internet explorer and edge before version 79. see also ::-ms-fill-lower ::-ms-track ::-ms-thumb ::-moz-range-progress css-tricks: styling cross-browser compatible range inputs with css quirksmode: styling and scripting sliders ...
::-ms-thumb - Archive of obsolete content
other properties are ignored. ...
...other properties are ignored. ...
...-left margin-right margin-top -ms-background-position-x -ms-background-position-y -ms-high-contrast-adjust opacity outline-color outline-style outline-width padding-bottom padding-left padding-right padding-top transform transform-origin visibility width syntax ::-ms-thumb specifications not part of any specification. see also ::-ms-track ::-ms-fill-upper ::-ms-fill-lower ::-webkit-slider-thumb ::-moz-range-thumb css-tricks: styling cross-browser compatible range inputs with css quirksmode: styling and scripting sliders ...
Generator comprehensions - Archive of obsolete content
non-standard. do not use! the generator comprehensions syntax is non-standard and removed starting with firefox 58. for future-facing usages, consider using generator. the 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! syntax (for (x of iterable) x) (for (x of iterable) if (condition) x) (for (x of iterable) for (y of iterable) x + y) description inside generator comprehensions, these two kinds of components are allowed: for...of and if the for-of iteration is always the first component. multiple for-of iterations or if statements are allowed. a significant draw...
... comprehension, you would only have to loop over the 'obj' structure once, total, as opposed to once when comprehending the array, and again when iterating through it. ...
... example 1: simple generator. ...
Debug.writeln - Archive of obsolete content
if the script is not being debugged, the debug.writeln function has no effect. the debug.writeln function is almost identical to the debug.write function. the only difference is that the debug.write function does not send a newline character after sending the strings. ...
...if the script is not being debugged, the debug.writeln function has no effect. the debug.writeln function is almost identical to the debug.write function. the only difference is that the debug.write function does not send a newline character after sending the strings. ...
...ote: to run this example, you must have a script debugger installed and the script must run in debug mode. internet explorer 8 includes the javascript debugger. if you are using an earlier version of internet explorer, see how to: enable and start script debugging from internet explorer. var counter = 42; debug.writeln("the value of counter is " + counter); requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). applies to: debug ...
GetObject - Archive of obsolete content
lication associated with the specified pathname is started, and the object in the specified file is activated. if pathname is a zero-length string (""), getobject returns a new object instance of the specified type. if the pathnameargument is omitted, getobject returns a currently active object of the specified type. if no object of the specified type exists, an error occurs. some applications allow you to activate part of a file. to do so, add an exclamation point (!) to the end of the file name and follow it with a string that identifies the part of the file you want to activate. for information on how 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.
...of a file. to do so, add an exclamation point (!) to the end of the file name and follow it with a string that identifies the part of the file you want to activate. for information on how 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...
...xobject object. if an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times activexobject is executed. with a single-instance object, getobject always returns the same instance when called with the zero-length string ("") syntax, and it causes an error if the pathname argument is omitted. requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, and internet explorer 8 standards. ...
VBArray - Archive of obsolete content
lue before being passed to the vbarray constructor. this can only be done by retrieving the value from an existing activex or other object. vbarrays can have multiple dimensions. the indices of each dimension can be different. the dimensions method retrieves the number of dimensions in the array; the lbound and ubound methods retrieve the range of indices used by each dimension. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that converts the visual basic safe array to a javascript array. 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/vbscr...
...0; i < 9; i++) { document.writeln(b[i]); } } --> </script> </head> <body> <script type="text/javascript"> <!-- vbarraytest(createvbarray()); --> </script> </body> properties the vbarray object has no properties. methods vbarray.dimensions returns the number of dimensions in a vbarray. vbarray.getitem returns the item at the specified location. ...
...er of dimensions in a vbarray. vbarray.getitem returns the item at the specified location. vbarray.lbound returns the lowest index value used in the specified dimension of a vbarray. vbarray.toarray returns a standard javascript array converted from a vbarray. vbarray.ubound returns the highest index value used in the specified dimension of the vbarray. requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards. not supported in windows 8.x store apps. ...
New in JavaScript 1.3 - Archive of obsolete content
javascript versions netscape communicator and navigator 4.06 and 4.5 executes javascript language versions up to 1.3. ...
...e found on archive.org. netscape navigator 4.5 was released on october 19, 1998. the most significant change in javascript 1.3 was compliance with ecma-262 and unicode by removing inconsistencies between javascript 1.2 and the new ecma standard (which was published in june 1997). additional features of version 1.2, at the time not specified by ecma-262 were kept in the javascript language (see below for a list of differences). javascript versions netscape communicator and navigator 4.06 and 4.5 executes javascript language versions up to 1.3. note that communicator and navigator 4.0-4.05 and earlier ignored scripts with the language attribute set to "javascript1.3" and higher. <script language="javascript1.2"> <!-- javascript for navigator 4.0. --> <script language="javascript1.3"> <!-- j...
... the splice method returned the element removed, if only one element was removed (howmany parameter is 1). in javascript 1.3, splice always returns an array containing the removed elements. if one element is removed, an array of one element is returned. changes to string.prototype.replace(). changes to the boolean object. changes to tostring(). non-ecma-262 features of javascript 1.3 the following is a comparison between the june 1998 version of ecma-262 and javascript 1.3. the following features were not part of the standard at that time, but implemented in javascript 1.3. keywords and operators strict equality operators vertical tab (\v or \u000b) as an escape sequence. statements label switch do...while export import built-in objects regexp methods of built-in ob...
New in JavaScript 1.8.5 - Archive of obsolete content
this version was included in firefox 4. new features in javascript 1.8.5 new functions function description object.create() creates a new object with the specified prototype object and properties. bug 492840 object.defineproperty() adds the named property described by a given descriptor to an object. object.defineproperties() adds the named properties described by the given descriptors to an object. ...
...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 change any properties. bug 492844 ...
...n() returns a json format string for a date object. function.prototype.bind() creates a new function that, when called, itself calls this function in the context provided (with a given sequence of arguments). bug 429507 new ecmascript5 features get and set operators now allows the identifier to be numeric or a string. bug 520696 function.apply() can accept any array-like object as the arguments list, instead of only true arrays. strict mode support array.tostring() now works even on non-arrays by either returning the result of calling its join() method if one is available or by calling its tostring() method. other st...
Object.prototype.__noSuchMethod__ - Archive of obsolete content
some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. the __nosuchmethod__ property used to reference a function to be executed when a non-existent method is called on an object, but this function is no longer available. while __nosuchmethod__ has been dropped, the ecmascript 2015 specification has the proxy object, with which you can achieve the below (and more). syntax obj.__nosuchmethod__ = fun parameters fun a function that takes the form function (id, args) { . . . } id the name of the non-existent method that was called args an array of the arguments passed to the method description by default, an attempt to call a method that doesn't exist on an object results in a typeerror being thrown. this behavior can be ...
... __nosuchmethod__ var o = { __nosuchmethod__: function(id, args) { console.log(id, '(' + args.join(', ') + ')'); } }; o.foo(1, 2, 3); o.bar(4, 5); o.baz(); // output // foo (1, 2, 3) // bar (4, 5) // baz () using __nosuchmethod__ to simulate multiple inheritance an example of code that implements a primitive form of multiple inheritance is shown below. // doesn't work with multiple inheritance objects as parents function nomethod(name, args) { var parents = this.__parents_; // go through all parents for (var i = 0; i < parents.length; i++) { // if we find a function on the parent, we call it if (typeof parents[i][name] == 'function') { return parents[i][name].apply(this, args); } } // if we get here, the method h...
... // if we get here, the method hasn't been found throw new typeerror; } // used to add a parent for multiple inheritance function addparent(obj, parent) { // if the object isn't initialized, initialize it if (!obj.__parents_) { obj.__parents_ = []; obj.__nosuchmethod__ = nomethod; } // add the parent obj.__parents_.push(parent); } an example of using this idea is shown below. // example base class 1 function namedthing(name) { this.name = name; } namedthing.prototype = { getname: function() { return this.name; }, setname: function(newname) { this.name = newname; } } // example base class 2 function agedthing(age) { this.age = age; } agedthing.prototype = { getage: function() { return this.age; }, setage: function(age) { this.age = age; } } // child c...
handler.enumerate() - Archive of obsolete content
the handler.enumerate() method used to be a trap for for...in statements, but has been removed from the ecmascript standard in es2016 and is deprecated in browsers. syntax var p = new proxy(target, { enumerate(target) { } }); parameters the following parameter is passed to the enumerate method. this is bound to the handler. target the target object. return value an iterator object. description the handler.enumerate method is a trap for for...in statements. ...
...e following parameter is passed to the enumerate method. this is bound to the handler. target the target object. return value an iterator object. description the handler.enumerate method is a trap for for...in statements. interceptions this trap can intercept these operations: property enumeration / for...in: for (var name in proxy) {...} reflect.enumerate() invariants if the following invariants are violated, the proxy will throw a typeerror: the enumerate method must return an object. examples the following code traps for...in statements. var p = new proxy({}, { enumerate(target) { console.log('called'); return ['a', 'b', 'c'][symbol.iterator](); } }); for (var x in p) { // "called" console.log(x); // "a" } // "b" ...
...re violated, the proxy will throw a typeerror: the enumerate method must return an object. examples the following code traps for...in statements. var p = new proxy({}, { enumerate(target) { console.log('called'); return ['a', 'b', 'c'][symbol.iterator](); } }); for (var x in p) { // "called" console.log(x); // "a" } // "b" // "c" the following code violates the invariant. var p = new proxy({}, { enumerate(target) { return 1; } }); for (var x in p) {} // typeerror is thrown note: both examples make use of the shorthand syntax for method definitions. specifications not part of any standard. ...
Archived JavaScript Reference - Archive of obsolete content
however, it has been removed from the standard and the firefox implementation. ...
...t'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()the handler.enumerate() method used to be a trap for for...in statements, but has been removed from the ecmascript standard in es2016 and is deprecated in browsers.legacy generator functionthe legac...
...it provided a stream of changes in the order in which they occur. however, this api has been deprecated and removed from browsers. you can use the more general proxy object instead.object.prototype.__count__...
JSObject - Archive of obsolete content
summary the public final class netscape.javascript.jsobject extends object. java.lang.object | +----netscape.javascript.jsobject description javascript objects are wrapped in an instance of the class 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 java...
... 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 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 ja...
...avascript 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 javascript object. setslot sets the value of an array element of a javascript object. 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.obje...
JavaArray - Archive of obsolete content
e used by java code. see the core javascript 1.5 guide for more information about data type conversions. in javascript 1.4 and later, the methods of java.lang.object are inherited by javaarray. backward compatibility javascript 1.3 and earlier the methods of java.lang.object are not inherited by javaarray. in addition, the tostring method is inherited from the object object and returns the following value: [object javaarray] you must specify a class object, such as one returned by java.lang.object.forname, for the componenttype parameter of newinstance when you use this method to create an array. you cannot use a javaclass object for the componenttype parameter. properties length: the number of elements in the java array represented by javaarray. methods tostring: in javascript 1.4...
...y bytearray is created by the java.lang.string.getbytes method, which returns an array. ...
... javascript with the newinstance method in javascript 1.4, you can use a javaclass object as the argument for the newinstance method which creates the array, as shown in the following code: var dogs = java.lang.reflect.array.newinstance(java.lang.string, 5); in javascript 1.1, use a class object returned by java.lang.class.forname as the argument for the newinstance method, as shown in the following code: var datatype = java.lang.class.forname("java.lang.string"); var dogs = java.lang.reflect.array.newinstance(datatype, 5); ...
Packages - Archive of obsolete content
d. description the packages object lets you access the public methods and fields of an arbitrary java class from within javascript. the java, netscape, and sun properties represent the packages java.*, netscape.*, and sun.* respectively. use standard java dot notation to access the classes, methods, and fields in these packages. ...
...you must use the packages object to access classes outside the netscape, sun, and java packages. ...
...the netscape, sun, and java packages. properties classname: the fully qualified name of a java class in a package other than netscape, java, or sun that is available to javascript. java: any class in the java package java.*. netscape: any class in the java package netscape.*. sun: any class in the java package sun.*. examples example: javascript function to create a java dialog box the following javascript function creates a java dialog box: function createwindow() { var theowner = new packages.java.awt.frame(); var thewindow = new packages.java.awt.dialog(theowner); thewindow.setsize(350, 200); thewindow.settitle("hello, world"); thewindow.setvisible(true); } in the previous example, the function instantiates thewindow as a new packages object. the setsize, settitle...
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
in order to make the fish cam page as agile as the fish themselves, it was necessary to strip out all of the tables, font tags, and other non-validating stuff. at the end of it, there were a series of div elements that contained a picture of the fish, the name of the fish, and one or more paragraphs of text about the fish. here's a typical (and short) example. <div class="card"> <img src="thumb_clown_trigger.jpg" alt="clown trigger" border="0" width="150" height="115"> <h3>clown trigger</h3> <p> our clown trigger is a bold little fish, though for a few weeks he slept a lot and didn't look well in general. he's much better now. </p> </div> basically, that's all that was needed. the reason for the class value being card is that the original idea was to style each fish's description like a t...
... will take up 98% the width of the parent element. this leaves out 2% as "wasted space," so to speak. i did it that way because it's a lot less likely to trigger a situation where rounding errors force the two floats to total more than 100% the width of the parent, as could happen if the floats' element boxes were made to total 50%. unfortunately, a few browsers don't get this right, and end up flowing the cards as a single vertical column instead of putting the fish side by side. after a bit of fiddling to try to fix this, i decided that trying to overcome this error in document flow wasn't worth the effort. the layout wasn't bad if the fish weren't laid out next to each other, so i moved on. floating fish with the cards set up to float, the next step was to place the images appropriately...
...v.card img {float: left; border: 1px solid #339;} that done, it was time to style the fish names. these are enclosed in h3 elements, so the field was pretty wide open in terms of what we could do. since the image was floated, any background or border we set on the h3 would "slide under" the image; this is an expected effect with floated elements. rather than try to fight it or push the image below the h3's element box, i let the image mostly overlap the h3, but with a slight offset. i then set up a thicker double border on the left, a one-pixel border the rest of the way around, and set the background to match the rest of the design. thus: div.card {float: left; width: 45%; margin: 1em 2% 0 2%;} div.card img {float: left; margin: 4px 0 0 0; border: 1px solid #339;} div.card h3 {border: ...
Writing JavaScript for XHTML - Archive of obsolete content
l environment. this article shows some of the reasons alongside with strategies to remedy the problems. it will encourage web authors to use more xml features and make their javascript interoperable with real xhtml applications. (note that xhtml documents which behave correctly in both application/xhtml+xml and text/html environments are sometimes known as 'polyglot' documents.) to test the following examples locally, use firefox's extension switch. just write an ordinary (x)html file and save it once as test.html and once as test.xhtml. problem: nothing works after switching the mime type suddenly no inline script works anymore. even the plain old alert() method is gone. the code looks something like this: <script type="text/javascript"> //<!-- window.alert("hello world!"); //...
... see this document for more on the issues related to application/xhtml+xml and text/html (at least as far as xhtml 1.* and html 4; html5 addresses many of these problems). problem: names in xhtml and html are represented in different cases scripts that used getelementsbytagname() with an upper case html name no longer work, and attributes like nodename or tagname return upper case in html and lower case in xhtml. solution: use or convert to lower case for methods like getelementsbytagname(), passing the name in lower case will work in both html and xhtml. for name comparisons, first convert to lower case before doing the comparison (e.g., "el.nodename.tolowercase() === 'html'"). this will ensure that documents in html will compare correctly and will do no harm in xhtml where the names a...
... problem: my cookie isn't saved! we found out already, that the document object in xml files is different from the ones in html files. now we take a look at one widly used property that is missing in xml files. in xml documents there is no document.cookie. ...
Building Mozilla XForms - Archive of obsolete content
ial starting with firefox 3.5. during cvs times, the mozilla repository contained both extensions. since the switch to mercurial, the extensions live in separate repositories. before you can start building the xforms extension, you should check your mozilla build environment by doing a regular firefox build. have a look at the build instructions for detailed information for your platform. ...
...ith firefox 3.5, you need to do two more mercurial checkouts: cd extensions hg clone http://hg.mozilla.org/xforms hg clone http://hg.mozilla.org/schema-validation that's it, you now have everything you need to get started. configure your build: the .mozconfig file mozilla uses a file called .mozconfig in your home directory to store the build configuration. for xforms, you will need to add the following line: ac_add_options --enable-extensions="default,xforms" # if you're using a mozilla source before 2010-11-06 (e.g. an old firefox 3.6 release) use this instead (see bug 601570 for details): ac_add_options --enable-extensions="default,xforms,schema-validation" a complete .mozconfig file for a release build might look like that: . $topsrcdir/browser/config/mozconfig mk_add_options moz_co_pr...
...s, 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. 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. ...
RFE to the Custom Controls Interfaces - Archive of obsolete content
introduction this page contains requests for enhancement to the custom control interfaces. you can refer to custom controls page to get familiar with custom controls mechanism. ...
...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 ...
...nsixformsdelegate - used to obtain the nsixformsaccessors interface nsixformsuiwidget - used by the xforms processor to update the value/state of an xforms element when its bound node's value/state is changed our current mechanism that allows authors to build custom controls assumes that the controls will be bound to instance nodes of simple content type. 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
you can also contact the xforms team about your request. you can do so by posting a message on the xforms newsgroup or file a new bug in the 'xforms' component of the 'core' product. ...
...e of the outstanding features of xforms is that it can work with any xml host language. natively, the mozilla xforms implementation supports xforms elements being hosted in xhtml and xul documents. but a form author is not restricted to only those xml languages that gecko knows. a lot of the xforms capabilities are reachable by using our custom controls interfaces. our custom control interfaces allows for the exchange of data between any xml element and and an xforms model. this means that an author can write powerful mozilla-based applications by using xforms. if previously you was forced to use ajax for this then now xforms makes this for you automatically. custom controls interfaces this section contains rfe to the custom control interfaces. if you find that you can't create a custom co...
... limitations in our interfaces or the functionality of our controls, then this is the right place to pass along your requirements. custom controls if you have a custom control that you believe will help fulfill the needs of form authors or other custom controls authors, please file it here. this section could be of particular interest to people using custom controls in xul documents for the following reasons: xul, in many cases, is much better suited for application development than xhtml. therefore the control set may need to be more extensive to address the wider spectrum of requirements that a xul application will have on its controls. xul is a feature of mozilla only and custom control authors should be aware their controls won't work on other browser platforms. enhancements of xf...
XForms Select1 Element - Archive of obsolete content
introduction allows the user to choose a single value from a list of pre-defined values (see the spec). the list of pre-defined items can be specified by either item (see the spec) or itemset (see the spec) elements. you can visually group these pre-defined items by using the choices (see the spec) element to contain them. note, some representations of the select1 element do not support visual grouping. attributes ui common appearance - the value of this attribute gives a hint to the xforms processor as to which type of widget(s) to use to represent this control. accesskey - used to specify the keyboard shortcut for focusing this control. single-node binding special selection - this attribute, when set to 'open', allows the user to provide free entry to the list. possible values ...
...r if the attribute is supported for every representation). incremental - supported, default value is true properties selection - see corresponding attribute incremental - see corresponding attribute type restrictions the select1 element can be bound to a node containing simple content. ...
...element is used, which allows the available choices to be obtained from an xforms model. the relaxation happens when the itemset element specifies the item value using a copy (see spec) element. this is because a copy element can be used to add a subtree of nodes underneath the element that the select1 control is bound to. representations the xforms select1 element can be represented by the following widgets for the specified appearance attribute values: combobox - default representation (xhtml/xul) listbox - used when appearance = 'compact' (xhtml/xul) radio group - used when appearance = 'full' (xhtml/xul) combobox displaying a combobox is the default representation (xhtml/xul). xhtml widget characteristics analogous widgets is <html:select/> visual grouping by choices element ...
Describing microformats in JavaScript - Archive of obsolete content
for firefox 3, this should be set to 0.8. mfobject the javascript object that implements the microformat. classname a string specifying the name of the microformat's class as referenced in html (class="classname"). ...
...address tel a telephone number html html including tags float a floating-point number microformat a microformat microformat_property a specific property within the microformat specified by microformat. custom custom data a simple example the hcard microformat for defining contact information makes use of the adr microformat to define an address. ...
...ss" : { plural: true }, "extended-address" : { }, "locality" : { }, "region" : { }, "postal-code" : { }, "country-name" : { } } }; the properties are quite simple here. the type property indicates the type of address represented by the object (work, home, and so forth). since the plural property is true, multiple types can be specified. this allows an address to be marked as being, for example, a work address for receiving parcels. the street-address property is plural as well. this allows multiple lines of address information to be contained in the street-address array. the microformat is registered with the microformat api by calling microformats.add(), like this: microformats.add("adr", adr_definition); note: to be clear: since the...
Game distribution - Game development
you've followed a tutorial or two and created an html5 game — that's great! this article covers all you need to know about the ways in which you can distribute your newly created game into the wild. this includes hosting it yourself online, submitting it to open marketplaces, and submitting it to closed ones like google play or the ios app store. benefits of html5 over native building games with html5 gives you extra advantages, such as: multiplatform bliss the technology itself is multiplatform, so you can write the code once and target multiple devices. this can range from low-end smartphones or tablets, through laptops and desktop computers, to smart tvs, watches or even a fridge if it can handle a modern enough browser. you don't need to have separate teams to work on the same tit...
...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, 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, an...
...atform issues yourself by uploading separate versions for different platforms. after you've covered steam, there's plenty of buzz around initiatives like humble bundle where the most popular indie games get presented to a broader audience. it's more like an excellent promotional opportunity than a way to earn a lot of money, however, as the prices paid for the games in a bundle are usually quite low. packaging games the web is the first and the best choice for html5 games, but if you want to reach a broader audience and distribute your game in a closed ecosystem, you still can do that by packaging it. the good thing is that you don't need a few separate teams working on the same game for different platforms — you can build it once and use tools like phonegap or cocoonio to package the ga...
GLSL Shaders - Game development
ally do, have additional properties. the 3d coordinate system defines space and the vertices help define shapes in that space. shader types a shader is essentially a function required to draw something on the screen. shaders run on a gpu (graphics processing unit), which is optimized for such operations. using a gpu to deal with shaders offloads some of the number crunching from the cpu. this allows the cpu to focus its processing power on other tasks, like executing code. vertex shaders vertex shaders manipulate coordinates in a 3d space and are called once per vertex. the purpose of the vertex shader is to set up the gl_position variable — this is a special, global, and built-in glsl variable. gl_position is used to store the position of the current vertex. the void main() function i...
... we will set the cube's color and position using shaders. go to the cube.html file on github, copy all the javascript code from inside the second <script> element, and paste it into the third <script> element of the current example. save and load index.html in your browser — you should see a blue cube. the vertex shader code let's continue by writing a simple vertex shader — add the code below inside the body's first <script> tag: void main() { gl_position = projectionmatrix * modelviewmatrix * vec4(position.x+10.0, position.y, position.z+5.0, 1.0); } the resulting gl_position is calculated by multiplying the model-view and the projection matrices by each vector to get the final vertex position, in each case. note: you can learn more about model, view, and projection transformati...
...which results in the original cube moving 10 units along the x axis and 5 units along the z axis, translated via a shader. we can ignore the fourth parameter and leave it with the default 1.0 value; this is used to manipulate the clipping of the vertex position in the 3d space, but we don't need in our case. the texture shader code now we'll add the texture shader to the code — add the code below to the body's second <script> tag: void main() { gl_fragcolor = vec4(0.0, 0.58, 0.86, 1.0); } this will set an rgba color to recreate the current light blue one — the first three float values (ranging from 0.0 to 1.0) represent the red, green, and blue channels while the fourth one is the alpha transparency (ranging from 0.0 — fully transparent — to 1.0 — fully opaque). applying the ...
Desktop gamepad controls - Game development
buttons: { layout: [], cache: [], status: [], pressed: function(button, state) {} } axes: { status: [] } }; the controller variable stores the information about the connected gamepad, and there's an active boolean variable we can use to know if the controller is connected or not. the connect() and disconnect() functions are bound to the following events: window.addeventlistener("gamepadconnected", gamepadapi.connect); window.addeventlistener("gamepaddisconnected", gamepadapi.disconnect); they are fired when the gamepad is connected and disconnected respectively. the next function is update(), which updates the information about the pressed buttons and axes. the buttons variable contains the layout of a given controller (for example ...
...controls explained — if the y button is pressed and held, the help becomes visible; when it is released the help diappears. on-screen instructions when the game is started, some introductory text is shown that shows you available controls — we are already detecting if the game is launched on desktop or mobile then showing a relevant message for the device, but we can go even further, to allow for the presence of a gamepad: create() { // ... if(this.game.device.desktop) { if(gamepadapi.active) { movetext = 'dpad or left stick\nto move'; shoottext = 'a to shoot,\ny for controls'; } else { movetext = 'arrow keys\nor wasd to move'; shoottext = 'x or space\nto shoot'; } } else { movetex...
...the same goes for when the game is paused: the start button unpauses the game...
Square tilemaps implementation: Scrolling maps - Game development
included in our tilemaps introduction article. this article also builds upon implementing static square tilemaps — you should read that too if you've not done so already. the camera the camera is an object that holds information about which section of the game world or level is currently being shown. cameras can either be free-form, controlled by the player (such as in strategy games) or follow an object (such as the main character in platform games.) regardless of the type of camera, we would always need information regarding its current position, 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 vi...
... 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 rendering scrolling maps vs. static maps: partial tiles might be shown. in static maps, usually the rendering starts at the top left corner of a tile situated at the top left corner of a view...
... ...
Create the Canvas and draw on it - Game development
riting the game's functionality, we need to create a basic structure to render the game inside. this can be done using html and the <canvas> element. the game's html the html document structure is quite simple, as the game will be rendered entirely on the <canvas> element. ...
... id="mycanvas" width="480" height="320"></canvas> <script> // javascript code goes here </script> </body> </html> we have a charset defined, <title> and some basic css in the header. the body contains <canvas> and <script> elements — we will render the game inside the first one and write the javascript code that controls it in the second one. the <canvas> element has an id of mycanvas to allow us to easily grab a reference to it, and it is 480 pixels wide and 320 pixels high. all the javascript code we will write in this tutorial will go between the opening <script> and closing </script> tags. canvas basics to actually be able to render graphics on the <canvas> element, first we have to grab a reference to it in javascript. add the following below your opening <script> tag. var canv...
...pening <script> tag. var canvas = document.getelementbyid("mycanvas"); var ctx = canvas.getcontext("2d"); here we're storing a reference to the <canvas> element to the canvas variable. then we're creating the ctx variable to store the 2d rendering context — the actual tool we can use to paint on the canvas. let's see an example piece of code that prints a red square on the canvas. add this below your previous lines of javascript, then load your index.html in a browser to try it out. ctx.beginpath(); ctx.rect(20, 40, 50, 50); ctx.fillstyle = "#ff0000"; ctx.fill(); ctx.closepath(); all the instructions are between the beginpath() and closepath() methods. we are defining a rectangle using rect(): the first two values specify the coordinates of the top left corner of the rectangle on the c...
Game over - Game development
et it reach the bottom edge of the screen, then it's game over. implementing game over let's try to implement game over in our game. here's the piece of code from the third lesson where we made the ball bounce off the walls: if(x + dx > canvas.width-ballradius || x + dx < ballradius) { dx = -dx; } if(y + dy > canvas.height-ballradius || y + dy < ballradius) { dy = -dy; } instead of allowing the ball to bounce off all four walls, let's only allow three now — left, top and right. hitting the bottom wall will end the game. we'll edit the second if block so it's an if else block that will trigger our "game over" state upon the ball colliding with the bottom edge of the canvas. for now we'll keep it simple, showing an alert message and restarting the game by reloading the page. fir...
...f else block that will trigger our "game over" state upon the ball colliding with the bottom edge of the canvas. for now we'll keep it simple, showing an alert message and restarting the game by reloading the page. ...
...me to end game } letting the paddle hit the ball the last thing to do in this lesson is to create some kind of collision detection between the ball and the paddle, so it can bounce off it and get back into the play area. the easiest thing to do is to check whether the center of the ball is between the left and right edges of the paddle. update the last bit of code you modified again, to the following: if(y + dy < ballradius) { dy = -dy; } else if(y + dy > canvas.height-ballradius) { if(x > paddlex && x < paddlex + paddlewidth) { dy = -dy; } else { alert("game over"); document.location.reload(); clearinterval(interval); } } if the ball hits the bottom edge of the canvas we need to check whether it hits the paddle . if yes, then it bounce...
Bounce off the walls - Game development
as walls and not let the ball move past them. in phaser this can be easily accomplished using the collideworldsbound property. add this line right after the existing game.physics.enable() method call: ball.body.collideworldbounds = true; now the ball will stop at the edge of the screen instead of disappearing, but it doesn't bounce. to make this occur we have to set its bounciness. ...
...not let the ball move past them. in phaser this can be easily accomplished using the collideworldsbound property. add this line right after the existing game.physics.enable() method call: ball.body.collideworldbounds = true; now the ball will stop at the edge of the screen instead of disappearing, but it doesn't bounce. to make this occur we have to set its bounciness. ...
... of the screen instead of disappearing, but it doesn't bounce. to make this occur we have to set its bounciness. add the following line below the previous one: ball.body.bounce.set(1); try reloading index.html again — now you should see the ball bouncing off all the walls and moving inside the canvas area. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps this is starting to look more like a game now, but we can't control it in any way — it's high time we introduced the player paddle and controls. « previousnext » ...
Collision detection - Game development
e physics engine to check collisions not only between single objects (like the ball and the paddle), but also between an object and the group. brick/ball collision detection the physics engine makes everything a lot easier — we just need to add two simple pieces of code. first, add a new line inside your update() function that checks for collision detection between ball and bricks, as shown below: function update() { game.physics.arcade.collide(ball, paddle); game.physics.arcade.collide(ball, bricks, ballhitbrick); paddle.x = game.input.x || game.world.width*0.5; } the ball's position is calculated against the positions of all the bricks in the group. the third, optional parameter is the function executed when a collision occurs — ballhitbrick(). create this new function ...
... game.physics.arcade.collide(ball, bricks, ballhitbrick); paddle.x = game.input.x || game.world.width*0.5; } the ball's position is calculated against the positions of all the bricks in the group. the third, optional parameter is the function executed when a collision occurs — ballhitbrick(). create this new function as the bottom of your code, just before the closing </script> tag, as follows: function ballhitbrick(ball, brick) { brick.kill(); } and that's it! reload your code and you should see the new collision detection working just as required. thanks to phaser there are two parameters passed to the function — the first one is the ball, which we explicitly defined in the collide method, and the second one is the single brick from the bricks group that the ball is collid...
...he kill() method on it. you would expect to have to write a lot more calculations of your own to implement collision detection when using pure javascript. that's the beauty of using the framework — you can leave a lot of boring code to phaser, and focus on the most fun and interesting parts of making a game. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps we can hit the bricks and remove them, which is a nice addition to the gameplay already. it would be even better to count the destroyed bricks increment the score as a result. « previousnext » ...
Game over - Game development
should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson08.html. to make the game more interesting we can introduce the ability to lose — if you don't hit the ball before it reaches the bottom edge of the screen it will be game over. how to lose to provide the ability to lose, we will disable the ball's collision with the bottom edge of the screen. ...
...screen. add the code below inside the create() function; just after you define the ball's attributes is fine: game.physics.arcade.checkcollision.down = false; this will make the three walls (top, left and right) bounce the ball back, but the fourth (bottom) will disappear, letting the ball fall off the screen if the paddle misses it. we need a way to detect this and act accordingly. add the following lines just below the previous new one: ball.checkworldbounds = true; ball.events.onoutofbounds.add(function(){ alert('game over!'); location.reload(); }, this); adding those lines will make the ball check the world (in our case canvas) bounds and execute the function bound to the onoutofbounds event. when you click on the resulting alert, the page will be reloaded so you can play ag...
...fbounds.add(function(){ alert('game over!'); location.reload(); }, this); adding those lines will make the ball check the world (in our case canvas) bounds and execute the function bound to the onoutofbounds event. when you click on the resulting alert, the page will be reloaded so you can play again. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps now the basic gameplay is in place let's make it more interesting by introducing bricks to smash — it's time to build the brick field. « previousnext » ...
Move the ball - Game development
tml. we have our blue ball printed on screen, but it's doing nothing — it would be cool to make it move somehow. this article covers how to do just that. updating the ball's position on each frame remember the update() function and its definition? the code inside it is executed on every frame, so it's a perfect place to put the code that will update the ball's position on screen. ...
...d the following new lines of the code inside update(), as shown: function update() { ball.x += 1; ball.y += 1; } the code above adds 1 to the x and y properties representing the the ball coordinates on the canvas, on each frame. reload index.html and you should see the ball rolling across the screen. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps the next step is to add some basic collision detection, so our ball can bounce off the walls. ...
... in any case, before we do all that we will first introduce phaser's physics engines, and do some setup work. ...
Randomizing gameplay - Game development
le game. this means that every game is quite similar. to fix this and improve playability we should make the rebound angles more random, and in this article we'll look at how. making rebounds more random we can change the ball's velocity depending on the exact spot it hits the paddle, by modifying the x velocity each time the ballhitpaddle() function is run using a line along the lines of the below. 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 valu...
...he 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 more interesting. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: summary you've finished all the lessons — congratulations! by this point you would have learnt the basics of phaser and the logic behind simple 2d games. exercises to follow you can do a lot more in the game — add whatever you feel would be best to make it more fun and interesting. it's a basic intro scratching the surface of the coun...
... change the color of the background on every hit. change the images and use your own. ...
Scaling - Game development
sson02.html. scaling refers to how the game canvas will scale on different screen sizes. we can make the game scale to fit on any screen size automatically during the preload stage, so we don't have to worry about it later. the phaser scale object there's a special scale object available in phaser with a few handy methods and properties available. update your existing preload() function as follows: function preload() { game.scale.scalemode = phaser.scalemanager.show_all; game.scale.pagealignhorizontally = true; game.scale.pagealignvertically = true; } scalemode has a few different options available for how the canvas can be scaled: no_scale — nothing is scaled. exact_fit — scale the canvas to fill all the available space both vertically and horizontally, without pre...
...ales the canvas, but keeps the aspect ratio untouched, so images won't be skewed like in the previous mode. there might be black stripes visible on the edges of the screen, but we can live with that. resize — creates the canvas with the same size as the available width and height, so you have to place the objects inside your game dynamically; this is more of an advanced mode. user_scale — allows you to have custom dynamic scaling, calculating the size, scale and ratio on your own; again, this is more of an advanced mode the other two lines of code in the preload() function are responsible for aligning the canvas element horizontally and vertically, so it is always centered on screen regardless of size. adding a custom canvas background colour we can also add a custom background colo...
...oad() function are responsible for aligning the canvas element horizontally and vertically, so it is always centered on screen regardless of size. adding a custom canvas background colour we can also add a custom background color to our canvas, so it won't stay black. the stage object has a backgroundcolor property for this purpose, which we can set using css color definition syntax. add the following line below the other three you added earlier: game.stage.backgroundcolor = '#eee'; compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps now we've set up the scaling for our game, let's continue to the third lesson and work out how to load the assets and print them on screen. « pre...
CORS - MDN Web Docs Glossary: Definitions of Web-related terms
cors (cross-origin resource sharing) is a system, consisting of transmitting http headers, that determines whether browsers block frontend javascript code from accessing responses for cross-origin requests. 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. ...
...rom accessing responses for cross-origin requests. 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. access-control-allow-credentials indicates whether or not the response to the request can be exposed when the credentials flag is true. ...
...n 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. access-control-allow-credentials indicates whether or not the response to the request can be exposed when the credentials flag is true. access-control-allow-headers used in response to a preflight request to indicate which http headers can be used when making the actual request. access-control-allow-methods specifies the method or methods allowed when accessing the resource in response to a preflight request. access-control-expose-headers indicates which headers can be exposed as part of the response by listing their names. access-control-max-a...
MVC - MDN Web Docs Glossary: Definitions of Web-related terms
logic. it emphasizes a separation between the software’s business logic and display. this "separation of concerns" provides for a better division of labor and improved maintenance. some other design patterns are based on mvc, such as mvvm (model-view-viewmodel), mvp (model-view-presenter), and mvw (model-view-whatever). the three parts of the mvc software-design pattern can be described as follows: model: manages data and business logic. view: handles layout and display. controller: routes commands to the model and view parts. model view controller example imagine a simple shopping list app. all we want is a list of the name, quantity and price of each item we need to buy this week. below we'll describe how we could implement some of this functionality using mvc. the model the...
...the view defines how the app's data should be displayed. in our shopping list app, the view would define how the list is presented to the user, and receive the data to display from the model. the controller the controller contains logic that updates the model and/or view in response to input from the users of the app. so for example, our shopping list could have input forms and buttons that allow us to add or delete items. these actions require the model to be updated, so the input is sent to the controller, which then manipulates the model as appropriate, which then sends updated data to the view. you might however also want to just update the view to display the data in a different format, e.g., change the item order to alphabetical, or lowest to highest price. in this case the control...
... it before. your data model is probably contained in some kind of database (be it a traditional server-side database like mysql, or a client-side solution such as indexeddb [en-us].) your app's controlling code is probably written in html/javascript, and your user interface is probably written using html/css/whatever else you like. this sounds very much like mvc, but mvc makes these components follow a more rigid pattern. in the early days of the web, mvc architecture was mostly implemented on the server-side, with the client requesting updates via forms or links, and receiving updated views back to display in the browser. however, these days, more of the logic is pushed to the client with the advent of client-side data stores, and xmlhttprequest allowing partial page updates as required. w...
Preflight request - MDN Web Docs Glossary: Definitions of Web-related terms
est headers: access-control-request-method, access-control-request-headers, and the origin header. a preflight request is automatically issued by a browser and in normal cases, front-end developers don't need to craft such requests themselves. it appears when request is qualified as "to be preflighted" and omitted for simple requests. ...
...appears when request is qualified as "to be preflighted" and omitted for simple requests. ...
...requests. for example, a client might be asking a server if it would allow a delete request, before sending a delete request, by using a preflight request: options /resource/foo access-control-request-method: delete access-control-request-headers: origin, x-requested-with origin: https://foo.bar.org if the server allows it, then it will respond to the preflight request with an access-control-allow-methods response header, which lists delete: http/1.1 204 no content connection: keep-alive access-control-allow-origin: https://foo.bar.org access-control-allow-methods: post, get, options, delete access-control-max-age: 86400 the preflight response can be optionally cached for the requests created in the same url using access-control-max-age header like in the above example. ...
Thread - MDN Web Docs Glossary: Definitions of Web-related terms
thread in computer science is the execution of running multiple tasks or programs at the same time. each unit capable of executing code is called a thread. the main thread is the one used by the browser to handle user events, render and paint the display, and to run the majority of the code that comprises a typical web page or app. because these things are all happening in one thread, a slow website or app script slows down the entire browser; worse, if a site or app script enters an infinite loop, the entire browser will hang. this results in a frustrating, sluggish (or worse) user experience. however, modern javascript offers ways to create additional threads, each executing independently while possibly communicating between one another. this is done using technologies such as web...
...ill hang. this results in a frustrating, sluggish (or worse) user experience. however, modern javascript offers ways to create additional threads, each executing independently while possibly communicating between one another. this is done using technologies such as web workers, which can be used to spin off a sub-program which runs concurrently with the main thread in a thread of its own. this allows slow, complex, or long-running tasks to be executed independently of the main thread, preserving the overall performance of the site or app—as well as that of the browser overall. this also allows individuals to take advantage of modern multi-core processors. a special type of worker, called a service worker, can be created which can be left behind by a site—with the user's permission—to ...
... ...
Baseline - MDN Web Docs Glossary: Definitions of Web-related terms
east asian scripts have no baseline. ...
... east asian scripts have no baseline. ...
... east asian scripts have no baseline. ...
MDN Web Docs Glossary: Definitions of Web-related terms
r 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 cryptography csp csrf css css object model (cssom) css pixel ...
... proxy server pseudo-class pseudo-element pseudocode public-key cryptography python q quality values quaternion quic r rail random number generator raster image rdf real user monitoring (rum) recursion reference reflow regular expression rendering engine repo reporting directive request header resource timing response header responsive web design rest rgb ril robots.txt round trip time (rtt) routers rss rtcp (rtp control protocol) rtf rtl (right to lef...
... statement static method static typing strict mode string stun style origin stylesheet svg svn symbol symmetric-key cryptography synchronous syntax syntax error synthetic monitoring t tag tcp tcp handshake tcp slow start telnet texel thread three js time to first byte time to interactive tld tofu transmission control protocol (tcp) transport layer security (tls) tree shaking trident truthy ttl turn type type coercion type conversion u ...
Test your skills: CSS and JavaScript accessibility - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. css accessibility 1 in the first task you are presented with a list of links. ...
... is no way to really tell that they are links, or to tell which one the user is focussed on. we'd like you to assume that the existing ruleset with the a selector is supplied by some cms, and that you can't change it — instead, you need to create new rules to make the links look and behave like links, and for the user to be able to tell where they are in the 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. css accessibility 2 in this next task you are presented with a simple bit of content — just headings and paragraphs. there are accessibility issues with the colors and sizing of the text; we'd like you to: 1. explain what the problems are, and what the guidelin...
...problems are, and what the guidelines are that state the acceptable values for color and sizing. 2. select new values for the color and font-size that fix the problem. 3. update the css with these new values to fix the problem. 4. test the code to make sure the problem is now fixed. explain what tools or methods you used to select the new values and test the code. 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. javascript accessibility 1 in our final task here, you have some javascripting to do. we have a simple app that presents a list of animal names. clicking one of the animal names causes a further description of that animal to appear in a box below the list. but it ...
Test your skills: Images and Form elements - Learn web development
the aim of this task is to help you check your understanding of some of the values and units that we looked at in the lesson on images, media and form elements. note: you can try out solutions in the interactive 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. 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, do...
... make the form field and button use the same text size as the rest of the form. give the form field and button 10 px of padding. ...
...ng changes to the way this form looks: use attribute selectors to target the search field and button inside .myform. make the form field and button use the same text size as the rest of the form. give the form field and button 10 px of padding. give the button a purple background (i used rebeccapurple), white foreground, no border and rounded corners of 5px. try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors mentioned above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an o...
Test your skills: backgrounds and borders - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...ers 1 in this task we want you to add a background, border, and some simple styling to a page header: give the box a 5px black solid border, with rounded corners of 10px. add a background image (use the url balloons.jpg) and size it so that it covers the box. give the <h2> a semi-transparent black background color, and make the text white. the finished example should look like the image below. 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. backgrounds and borders 2 in this task we want you to add background images, a border, and some other styling to a decorative box: give the box a 5px lightblue border, and round the top left corner 20px and the bottom right c...
...x and the bottom right corner 40px the heading uses the star.png image as a background image, with a single centered star on the left and a repeating pattern of stars on the right. make sure that the heading text does not overlay the image, and that it is centered — you will need to use techniques learned in previous lessons to achieve this. the finished example should look like the image below: try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as ...
Test your skills: position - Learn web development
the aim of this task is to get you working with the css position property and values covered in our lesson on position. you will be working through two small tasks which use different elements of the material you have just covered. note: you can try out solutions in the interactive 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. ...
...load 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. positioning one in this task you need to position the item with a class of target to the top and right of the container, which has the 5px grey border. try updating the live code below to recreate the finished example: as an extra challenge, can you change the target to display underneath the text? for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. position two in the below example if you scroll the box the sidebar scrolls with the content. change it so that the sidebar stays in place and...
..., can you change the target to display underneath the text? for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. position two in the below example if you scroll the box the sidebar scrolls with the content. change it so that the sidebar stays in place and only the content scrolls. 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. 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 want to ask for help: put your work into an online shareable e...
Use CSS to solve common problems - Learn web development
Learn › CSS › Howto
the following links provide solutions to common problems you may face when working with css. ...
... how to use background-clip to control how much of the box your background image covers. how to change the box model completely using box-sizing how to control backgrounds how to control ...
... block, and inline-block? how to create fancy boxes (also see the styling boxes module, generally). how to use background-clip to control how much of the box your background image covers. how to change the box model completely using box-sizing how to control backgrounds how to control borders how to style an html table how to add shadows to boxes uncommon and advanced techniques css allows some advanced design techniques. these articles help demystify some of the more complicated use cases. general how to calculate specificity of a css selector how to control inheritance in css advanced effects how to use filters in css how to use blend modes in css layout using css flexible boxes using css multi-column layouts using css generated content ...
Typesetting a community school homepage - Learn web development
head of the document. 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 you have been provided with some raw html for the homepage of an imaginary community college, plus some css that styles the page into a three column layout and provides some other rudimentary styling. you are to write your css additions below the comment at the bottom of the css file, to make sure it is easy to mark the bits you have done. don't worry if some of the selectors are repetitious; we'll let you off in this instance. fonts: first of all, download a couple of free-to-use fonts. because this is a college, the fonts should be chosen to give the page a fairly serious, formal, trustworthy feel — a serif site-wide font for ...
...and your heading font to your headings. general text styling: give the page a site-wide font-size of 10px. give your headings and other element types appropriate font-sizes defined using a suitable relative unit. give your body text a suitable line-height. center your top level heading on the page. give your headings a little bit of letter-spacing to make them not too too squashed, and allow the letters to breathe a bit. give your body text some letter-spacing and word-spacing, as appropriate. give the first paragraph after each heading in the <section> a little bit of text-indentation, say 20px. links: give the link, visited, focus, and hover states some colors that go with the color of the horizontal bars at the top and bottom of the page. make it so that links are underlin...
...on menu so that it has an appropriate look for the look and feel for the page. hints and tips you don't need to edit the html in any way for this exercise. you don't necessarily have to make the nav menu look like buttons, but it needs to be a bit taller so that it doesn't look silly on the side of the page; also remember that you need to make this one a vertical nav menu. example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a ...
How do you make sure your website works properly? - Learn web development
agnose and resolve some basic issues you can run into with your website. so you've published your website online? very good! but are you sure it works properly? a distant web server often behaves quite differently from a local one, so it's a good idea to test your website once it's online. you might be surprised at how many problems come up: images don't show up, pages don't load or load slowly, and so on. most of the time it's no big deal, just a simple mistake or an issue with your web hosting configuration. let's see how to diagnose and solve those problems. active learning there is no active learning available yet. dig deeper test in your browser if you want to know whether your website works correctly, the first thing to do is fire up your browser and go to the page you wan...
... location. you won't see this much in your browser, but it's good to know about "301" since search engines use this information a lot to update their indexes. 304: not modified the file has not changed since the last time you asked for it, so your browser can display the version from its cache, resulting in faster response times and more efficient use of bandwidth. 403: forbidden you aren't allowed to display the resource. usually it has to do with a configuration mistake (e.g. your hosting provider forgot to give you access rights to a directory). 404: not found self-explanatory. we'll discuss how to solve this below. 500: internal server error something went wrong on the server. for instance, maybe the server-side language (php, .net, etc.) stopped working, or the web server itself ...
...t (we will cover javascript in another series of articles). more things to check we have listed a few simple ways to check that your website works properly, as well as the most common errors you may run across and how to fix them. you can also test if your page meets these criteria: how's the performance? does the page load fast enough? resources like webpagetest.org or browser add-ons like yslow can tell you a few interesting things: grades go from a to f. our page is just small and meets most criteria. but we can already note it would have been better to use a cdn. that doesn't matter very much when we're only serving one image, but it would be critical for a high-bandwidth website serving many thousands of images. is the server responsive enough? ping is a useful shell tool that t...
How can we design for all types of users? - Learn web development
ini does not support font sizing in rem. it will end up setting its own font size, so don't bother feeding it font units. why would i want to use proportional units? because you don't know when a browser is going to come around and refuse to zoom up text whose size is expressed in pixels. also, check your website's statistics: you may receive visits from older browsers. we would advise the following: describe fonts in rem units, most browsers will be very happy with them; let older browsers display fonts with their own internal engine. browser's engines will ignore any property or value in the css if they can't cope with them, so that your website is still usable if not true to your designer's vision. older browsers are on the way out anyway. note: your mileage may vary. if you hav...
...>[lengthly text that spans many lines]</p> </div> </body> </html> we have a div with class container. we can style the div either to set its width (using the width property) or its maximum width so that it never gets too large (using the max-width property). if you want an elastic/responsive website, and you don't know what the browser's default width is, you can use the max-width property to allow up to 70 characters per line and no more: div.container { max-width:70em; } alternative content for images, audio, and video websites often include stuff besides plain text. images images can be either decorative or informative, but there's no guarantee that your users can see them. for example, visually impaired users rely on a screen reader, which can only handle text. your readers may...
...n text. images images can be either decorative or informative, but there's no guarantee that your users can see them. for example, visually impaired users rely on a screen reader, which can only handle text. your readers may be using a very strict intranet that blocks images originating from a cdn. your readers may have disabled images to save bandwidth, especially on mobile devices (see below). decorative images they're just for decoration and don't convey any real information. they could most often be replaced by a background image. make sure they feature an empty alt attribute: <img src="deco.gif" alt=""> so they don't clog up the text. informative images they are used to convey information, hence their name. they can, for instance, feature a graph, or show a person's gesture...
Example 3 - Learn web development
<span class="value">cherry</span> <ul class="optlist hidden"> <li class="option">cherry</li> <li class="option">lemon</li> <li class="option">banana</li> <li class="option">strawberry</li> <li class="option">apple</li> </ul> </div> </form> css content .widget select, .no-widget .select { position : absolute; left : -5000em; height : 0; overflow : hidden; } /* --------------- */ /* required styles */ /* --------------- */ .select { position: relative; display : inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline: none; } .select .optlist { position: absolute; top : 100%; left : 0; } .select .optlist.hidden { max-height: 0; visibility: hidden; } /* ------------ */ /* fanc...
... 100px */ border : 0.2em solid #000; /* 2px */ border-radius : 0.4em; /* 4px */ box-shadow : 0 0.1em 0.2em rgba(0,0,0,.45); /* 0 1px 2px */ background : #f0f0f0; background : -webkit-linear-gradient(90deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); background : linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display : inline-block; width : 100%; overflow : hidden; white-space : nowrap; text-overflow : ellipsis; vertical-align: top; } .select:after { content : "▼"; position: absolute; z-index : 1; height : 100%; width : 2em; /* 20px */ top : 0; right : 0; padding-top : .1em; -moz-box-sizing : border-box; box-sizing : border-box; text-align : center; border-left : .2em solid #000; border-radius: 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 definitions // // -------------------- // function deac...
Example 4 - Learn web development
<span class="value">cherry</span> <ul class="optlist hidden"> <li class="option">cherry</li> <li class="option">lemon</li> <li class="option">banana</li> <li class="option">strawberry</li> <li class="option">apple</li> </ul> </div> </form> css content .widget select, .no-widget .select { position : absolute; left : -5000em; height : 0; overflow : hidden; } /* --------------- */ /* required styles */ /* --------------- */ .select { position: relative; display : inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline: none; } .select .optlist { position: absolute; top : 100%; left : 0; } .select .optlist.hidden { max-height: 0; visibility: hidden; } /* ------------ */ /* fanc...
... 100px */ border : 0.2em solid #000; /* 2px */ border-radius : 0.4em; /* 4px */ box-shadow : 0 0.1em 0.2em rgba(0,0,0,.45); /* 0 1px 2px */ background : #f0f0f0; background : -webkit-linear-gradient(90deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); background : linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display : inline-block; width : 100%; overflow : hidden; white-space : nowrap; text-overflow : ellipsis; vertical-align: top; } .select:after { content : "▼"; position: absolute; z-index : 1; height : 100%; width : 2em; /* 20px */ top : 0; right : 0; padding-top : .1em; -moz-box-sizing : border-box; box-sizing : border-box; text-align : center; border-left : .2em solid #000; border-radius: 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 definitions // // -------------------- // function deac...
Example 5 - Learn web development
role="option" aria-selected="true">cherry</li> <li class="option" role="option">lemon</li> <li class="option" role="option">banana</li> <li class="option" role="option">strawberry</li> <li class="option" role="option">apple</li> </ul> </div> </form> css content .widget select, .no-widget .select { position : absolute; left : -5000em; height : 0; overflow : hidden; } /* --------------- */ /* required styles */ /* --------------- */ .select { position: relative; display : inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline: none; } .select .optlist { position: absolute; top : 100%; left : 0; } .select .optlist.hidden { max-height: 0; visibility: hidden; } /* ------------ */ /* fanc...
... 100px */ border : 0.2em solid #000; /* 2px */ border-radius : 0.4em; /* 4px */ box-shadow : 0 0.1em 0.2em rgba(0,0,0,.45); /* 0 1px 2px */ background : #f0f0f0; background : -webkit-linear-gradient(90deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); background : linear-gradient(0deg, #e3e3e3, #fcfcfc 50%, #f0f0f0); } .select .value { display : inline-block; width : 100%; overflow : hidden; white-space : nowrap; text-overflow : ellipsis; vertical-align: top; } .select:after { content : "▼"; position: absolute; z-index : 1; height : 100%; width : 2em; /* 20px */ top : 0; right : 0; padding-top : .1em; -moz-box-sizing : border-box; box-sizing : border-box; text-align : center; border-left : .2em solid #000; border-radius: 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 definitions // // -------------------- // function deac...
Test your skills: Advanced styling - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...ox is a magnifying glass icon. we've made one available in the same directory as our html files — see search-24px.png — plus a <div> element after the search input to help you attach it, should you need it. can you figure out a sensible way to attach it, and can you use some css to get it to sit to the right of the search box, and be lined up vertically as well? 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. advanced form styling 2 in our next task we provide you with a set of three radio buttons. we want you to give them custom styling. we've already provided you with a basic reset to build upon. first of all, get rid of their default styling. next, give the radi...
...a reasonable base style — the style they have when the page first loads. this can be anything you like, but you probably want to set a width and height (of somewhere between about 18 and 24 pixels), and a subtle border and/or background color. now give the radio buttons a different style for when they are selected. align the radio buttons nicely with the labels. 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. advanced form styling 3 in our final task for this assessment series, we provide you with a feedback form that is already nicely-styled — you've already seen something similar if you've worked through our ui pseudo-classes article, and now we want you to come up ...
Test your skills: Form validation - Learn web development
number" fields to make the browser apply some more specific validation suitable for the data being asked for. give the "user name" field a required length of between 5 and 20 characters, the "phone number" field a maximum length of 15 characters, and the "comment" field a maximum length of 200 characters. try submitting your form — it should refuse to submit until the above constaints are followed, and give suitable error messages. to help, you might want to consider adding some simple css to show when a form field is valid or invalid. download the starting point for this task to work in your own editor or in an online editor. form validation 2 now we want you to take the same form you saw in the previous task (use your previous answer if you want to), and add some more specific pat...
... download the starting point for this task to work in your own editor or in an online editor. form validation 2 now we want you to take the same form you saw in the previous task (use your previous answer if you want to), and add some more specific pattern validation to the first three fields using regular expressions. all of the user names in our application consist of a single letter, followed by a dot, followed by three or more letters or numbers. all letters should be lowercase. all of the email addresses for our users consist of one or more letters (lower or upper case) or numbers, followed by "@bigcorp.eu". remove the length validation from the phone number field if it is present, and set it so that it accepts 10 digits — either 10 digits in a row, or a pattern of three digit...
...n of three digits, three digits, then four digits, separated by either spaces, dashes, or dots. note: regular expressions are really challenging if you are new to them, but don't despair — have a go and see where you get to; there is no shame in asking for some help. you can find everything you need to answer these questions at our regular expression reference, and by searching on stack overflow. again, to help you might want to consider adding some simple css to show when a form field is valid or invalid. download the starting point for this task to work in your own 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...
Test your skills: HTML5 controls - Learn web development
this aim of this skill test is to assess whether you've understood our the html5 input types article. note: you can try out solutions in the interactive 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. html5 controls 1 first let's explore some of the new html5 input types. create appropriate inputs for a user to update their details for: email website phone number favourite color 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 w...
... implement a basic slider control to go along with the provided label. ...
...ve 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 recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can...
Dealing with files - Learn web development
ojects. inside your chosen place, create a new folder called web-projects (or similar). this is where all your website projects will live. inside this first folder, create another folder to store your first website in. call it test-site (or something more imaginative). an aside on casing and spacing you'll notice that 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 i...
...g in all your links being broken. it's better to separate words with dashes, rather than underscores: my-file.html vs. my_file.html. the short answer is that you should use a hyphen for your file names. the google search engine treats a hyphen as a word separator but does not regard an underscore that way. for these reasons, it is best to get into the habit of writing your folder and file names lowercase with no spaces and with words separated by dashes, at least until you know what you're doing. that way you'll bump into fewer problems later down the road. what structure should your website have? next, let's look at what structure our test site should have. the most common things we'll have on any website project we create are an index html file and folders to contain images, style files...
...nother, you have to provide a file path between them — basically a route, so one file knows where another one is. to demonstrate this, we will insert a little bit of html into our index.html file, and make it display the image you chose in the article "what will your website look like?" copy the image you chose earlier into your images folder. open up your index.html file, and insert the following code into the file exactly as shown. don't worry about what it all means for now — we'll look at the structures in more detail later in the series. <!doctype html> <html> <head> <meta charset="utf-8"> <title>my test page</title> </head> <body> <img src="" alt="my test image"> </body> </html> the line <img src="" alt="my test image"> is the html code that inserts an ...
Publishing your website - Learn web development
program shows you your local files and the web server's files in two windows, and provides a way for you to transfer files back and forth. tips for finding hosting and domains mdn does not promote specific commercial hosting companies or domain name registrars. to find hosting companies and registrars, just search for "web hosting" and "domain names". all registrars will have a feature to allow you to check if the domain name you want is available. your home or office internet service provider may provide some limited hosting for a small website. the available feature set will be limited, but it might be perfect for your first experiments. there are also free services available like neocities, blogger, and wordpress. sometimes you get what you pay for, but sometimes these resources a...
...t experiments. there are also free services available like neocities, blogger, and wordpress. sometimes you get what you pay for, but sometimes these resources are good enough for your initial experiments. many companies provide hosting and domains. using an online tool like github or google app engine some tools let you publish your website online: github is a "social coding" site. it allows you to upload code repositories for storage in the git version control system. you can then collaborate on code projects, and the system is open-source by default, meaning that anyone in the world can find your github code, use it, learn from it, and improve on it. github has a very useful feature called github pages, which allows you to expose website code live on the web. google app engine is...
...gle’s infrastructure — whether you need to build a multi-tiered web application from scratch or host a static website. see how do you host your website on google app engine? for more information. these options are usually free, but you may outgrow the limited feature-set. using a web-based ide such as codepen there are a number of web apps that emulate a website development environment, allowing you to enter html, css and javascript, and then display the result of that code as a website — all in one browser tab. generally speaking, these tools are relatively easy, great for learning, good for sharing code (for example, if you want to share a technique with or ask for debugging help from colleagues in a different office), and free (for basic features). they host your rendered page at...
Define terms with HTML - Learn web development
e just what they claim to be: a list of terms and their matching descriptions (e.g., definition lists, dictionary entries, faqs, and key-value pairs). description lists are not suitable for marking up dialogue, because conversation does not directly describe the speakers. here are recommendations for marking up dialogue. the terms described go inside <dt> elements. the matching description follows immediately, contained within one or more <dd> elements. enclose the whole description list with a <dl> element. a simple example here's a simple example describing kinds of food and drink: <dl> <dt>jambalaya</dt> <dd> rice-based entree typically containing chicken, sausage, seafood, and spices </dd> <dt>sukiyaki</dt> <dd> japanese specialty consisting of th...
...es </dd> <dt>sukiyaki</dt> <dd> japanese specialty consisting of thinly sliced meat, vegetables, and noodles, cooked in sake and soy sauce </dd> <dt>chianti</dt> <dd> dry italian red wine originating in tuscany </dd> </dl> the basic pattern, as you can see, is to alternate <dt> terms with <dd> descriptions. if two or more terms occur in a row, the following description applies to all of them. if two or more descriptions occur in a row, they all apply to the last given term. improving the visual output here's how a graphical browser displays the foregoing list: if you want the keywords to stand out better, you could try bolding them. remember, html is not a visual medium; we need css for all visual effects. the css font-weight property is wh...
...to the last given term. ...
Structuring a page of content - Learn web development
ject, your task is to take the content for the homepage of a bird watching website and add structural elements to it so it can have a page layout applied to it. it needs to have: a header spanning the full width of the site containing the main title for the page, the site logo, and the navigation menu. the title and logo appear side by side once styling is applied, and the navigation appears below those two items. a main content area containing two columns — a main block to contain the welcome text, and a sidebar to contain image thumbnails. a footer containing copyright information and credits. you need to add a suitable wrapper for: the header the navigation menu the main content the welcome text the image sidebar the footer you should also: apply the provided css to t...
...g two columns — a main block to contain the welcome text, and a sidebar to contain image thumbnails. a footer containing copyright information and credits. you need to add a suitable wrapper for: the header the navigation menu the main content the welcome text the image sidebar the footer you should also: apply the provided css to the page by adding another <link> element just below the existing one provided at the start. hints and tips use the w3c nu html checker to catch unintended mistakes in your html, css, and svg — mistakes you might have otherwise missed — so that you can fix them. you don't need to know any css to do this assessment; you just need to put the provided css inside an html element. the provided css is designed so that when the correct structur...
... inside an html element. the provided css is designed so that when the correct structural elements are added to the markup, they will appear green in the rendered page. if you are getting stuck and can't envisage what elements to put where, draw out a simple block diagram of the page layout, and write on the elements you think should wrap each block. this is extremely helpful. example the following screenshot shows an example of what the homepage might look like after being marked up. assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should in...
Test your skills: Advanced HTML text - Learn web development
the aim of this skill test is to assess whether you've understood our advanced text formatting article. note: you can try out solutions in the interactive 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. advanced html text 1 in this task we want you to turn the provided animals and their definitions into a description 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. advanced html text 2 in this task we want you to add some semantics to the provided html as...
... semantically mark up "html" and "css" as acronyms, providing expansions as tooltips. ...
... quote, and semantically indicate that the quote is taken from accessibility. semantically mark up "html" and "css" as acronyms, providing expansions as tooltips. semantically associate machine-readable dates with the dates in the text. use subscript and superscript to provide correct semantics for the chemical formulae and dates, and make them display correctly. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can...
Test your skills: HTML text basics - Learn web development
this aim of this skill test is to assess whether you've understood our html text fundamentals article. note: you can try out solutions in the interactive 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. html text basics 1 in this task we want you to mark up the provided html using semantic heading and paragraph elements. 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. html text basics 2 in this task we want you to turn the first un-marked up list into an unorder...
...vided html using semantic heading and paragraph elements. 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. html text basics 2 in this task we want you to turn the first un-marked up list into an unordered list, and the second one into an ordered 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. ...
... assessment or further help you can practice these examples in the interactive editors above. ...
Multimedia and Embedding - Learn web development
ously covered in introduction to html. if you've not worked through this module (or something similar), work through it first, then come back! 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 this module contains the following articles which will take you through all the fundamentals of embedding multimedia on webpages. images in html there are other types of multimedia to consider, but it is logical to start with the humble <img> element used to embed a simple image in a webpage. in this article we'll look at how to use it in more depth, including basics, annotating it with captions using <figure>, and how it r...
... the html5 <video> and <audio> elements to embed video and audio on our pages, including basics, providing access to different file formats to different browsers, adding captions and subtitles, and how to add fallbacks for older browsers. from <object> to <iframe> — other embedding technologies at this point we'd like to take somewhat of a sideways step, looking at a couple of elements that allow you to embed a wide variety of content types into your webpages: the <iframe>, <embed> and <object> elements. <iframe>s are for embedding other web pages, and the other two allow you to embed pdfs, svg, and even flash — a technology on its way out, but which you may still see semi-regularly. adding vector graphics to the web vector graphics can be very useful in certain situations. unlike reg...
...ll learn about the concept of responsive images — images that work well on devices with widely differing screen sizes, resolutions, and other such features — and look at what tools html provides to help implement them. this helps to improve performance across different devices. ...
Image gallery - Learn web development
ey are clicked, the corresponding image is displayed in the displayed-img <img> element. attach an onclick handler to the <button> so that when it is clicked, a darken effect is applied to the full-size image. when it is clicked again, the darken effect is removed again. ...
... 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. ...
...this by using getattribute(). if the class name is "dark", changes the <button> class to "light" (using setattribute()), its text content to "lighten", and the background-color of the overlay <div> to "rgba(0,0,0,0.5)". if the class name not "dark", changes the <button> class to "dark", its text content back to "darken", and the background-color of the overlay <div> to "rgba(0,0,0,0)". the following lines provide a basis for achieving the changes stipulated in points 2 and 3 above. btn.setattribute('class', xxx); btn.textcontent = xxx; overlay.style.backgroundcolor = xxx; hints and tips you don't need to edit the html or css in any way. assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable ...
Test your skills: Loops - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...in an online tool such as codepen, jsfiddle, or glitch, then working on the tasks. we didn't provide live editable versions of these tasks because of the risk of creating infinite loops and crashing the assessment page! if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript. we haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into wh...
...f 0; intended to be used as an iterator. name — contains a name to search for para — contains a reference to a paragraph, which will be used to report the results. you should use a type of loop that you've not used in the previous task. download the starting point for this task to work in your own editor or in an online editor. loops 3 in this final task, you are provided with the following: i — starts off with a value of 500; intended to be used as an iterator. para — contains a reference to a paragraph, which will be used to report the results. isprime() — a function that, when passed a number, returns true if the number is a prime number, and false if not. you need to use a loop to go through the numbers 2 to 500 backwards (1 is not counted as a prime number), and...
Test your skills: Math - Learn web development
this aim of this skill test is to assess whether you've understood our basic math in javascript — numbers and operators article. note: you can try out solutions in the interactive 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. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). math 1 let's start out by testing your knowledge of basic math operators. you will have to create four nu...
...oadable version). math 1 let's start out by testing your knowledge of basic math operators. you will have to create four numeric values, then add the first two together, then subtract the fourth from the third, then multiply the two secondary results together to get a result of 48. finally, we need to write a test that proves that this value is an even number. so, try updating the live code below to recreate the finished example, following these steps: create four variables that contain numbers. call the variables something sensible. add the first two variables together and store the result in another variable. subtract the fourth variable from the third and store the result in another variable. multiply the results from the last two steps together, storing the result in a variable ...
...k you are already provided with two calculations, with the results stored in the variables result and result2. but these results aren't what we want; you'll need to take the calculations and change them to give us what we want. what do we want? after multiplying the two results together and formatting the result to 2 decimal places, the final result should be 10.42. try updating the live code below to recreate the finished example, following these steps: write a calculation that multiplies result and result2 together and assigns the result back to result. this will require assignment shorthand. write a line of code that takes result and formats it to 2 decimal places, storing the result of this in a variable called finalresult. check the data type of finalresult using typeof; you'll pr...
Test your skills: JSON - Learn web development
json 1 the one and only task in this article concerns accessing json data and using it in your page. ...
... json 1 the one and only task in this article concerns accessing json data and using it in your page. ...
...tring. the last mother cat name should have an "and" before it, and a full stop after it. how do you make sure this can work, no matter how many cats are in the json? why are the para1.textcontent = motherinfo; and para2.textcontent = kitteninfo; lines inside the displaycatinfo() function, and not at the end of the script? this has something to do with async code. try updating the live code below to recreate the finished example: warning: to answer this question, you'll need to write your code into the live code window above. the example won't work locally, or in an environment like codepen or jsfiddle, because of something called cross-origin security. this basically means that you can't request a file from one origin using code on a different origin. in the live code editor above, b...
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. ...
...r 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. 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 t...
...dules: 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 answer some fundamental questions such as "what is javascript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing javascript. after that, we discuss some key javascript features in detail, ...
What is web performance? - Learn web development
a loading spinner)? are scrolling and animations smooth? this article provides a brief introduction to objective, measureable web performance*, looking at what technologies, techniques, and tools are involved in web optimization. prerequisites: basic computer literacy, basic software installed, and basic knowledge of client-side web technologies. ...
...sic software installed, and basic knowledge of client-side web technologies. objective: to gain basic familiarity of what is involved with web performance. * versus subjective, perceived performance, covered in the next article what is web performance? web performance is the objective measurement and perceived user experience of a web site or application. this includes the following major areas: reducing overall load time: how long does it take the files required to render the web site to download on to the user's computer? this tends to be affected by latency, how big your files are, how many files there are, and other factors besides. a general strategy is to make your files as small as possible, reduce the number of http requests made as much as possible, and employ...
...ked to from the index file is generally sequential, based on source order, but this can be manipulated and should definitely be optimized, realizing that some resources block additional downloads until their content is parsed and executed. the critical path. this is the process that the browser uses to construct the web document once the files have been downloaded from the server. the browser follows a well-defined set of steps, and optimizing the critical rendering path to prioritize the display of content that relates to the current user action will lead to significant improvements in content rendering time. see critical rendering path for more information. the document object model. the document object model, or dom, is a tree structure that represents the content and elements of your ht...
Properly configuring server MIME types - Learn web development
re correct mime types important? if the web server or application reports an incorrect mime type for content, a web browser has no 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 import...
... 2.0 will no longer do this for stylesheets loaded from a different origin than the requesting document. if your stylesheet comes from a different origin than the document, you must serve it with the correct mime type (text/css). ...
...y heuristic that allows the load if the first line in the style sheet appears to be a well-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.
Rendering a list of Vue components - Learn web development
-do items. to do that, we’ll add a data property to the app.vue component object, containing a todoitems field whose value is an array of todo items. while we'll eventually add a mechanism to add new todo items, we can start with some mock to do items. each to-do item will be represented by an object with a name and a done property. add a few sample to-do items, along the lines of those seen below. this way you have some data available for rendering using v-for. export default { name: 'app', components: { todoitem }, data() { return { todoitems: [ { label: 'learn vue', done: false }, { label: 'create a vue project with the cli', done: true }, { label: 'have fun', done: true }, { label: 'create a to-do list', done: false } ] }...
...tax. this is really useful, as we want our todo items to display their label properties as their label, not a static label of "my todo item". in addition, we want their checked status to reflect their done properties, not always be set to done="false". update the label="my todo item" attribute to :label="item.label", and the :done="false" attribute to :done="item.done", as seen in context below: <ul> <li v-for="item in todoitems" :key="item.id"> <to-do-item :label="item.label" :done="item.done"></to-do-item> </li> </ul> now when you look at your running app, it'll show the todo items with their proper names, and if you inspect the source code you'll see that the inputs all have unique ids, taken from the object in the app component. chance for a slight refactor there...
...now means that our id is being taken from the data inside app.vue and passed into todoitem as a prop, just like everything else, so things are now more logical and consistent. summary and that brings us to the end of another article. we now have sample data in place, and a loop that takes each bit of data and renders it inside a todoitem in our app. what we really need next is the ability to allow our 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. we'll get to these in the next article. previous overview: client-side javascript frameworks next in this module introduction to client-side f...
Index
675 creating an appealing add-on listing add-ons, beginner, guide, webextension, publishing there are two essential steps to getting people to use your add-on: they need to discover your add-on and open the listing page, then the listing page needs to encourage them to click the add to firefox button. ...
......
.... 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 and feel of the user interface and personalize it to your tastes. learn how to create and share themes! 685 obsolete add-ons, archive, look & feel, obsolete, themes this page contains theme documents and resources that we don't expect will ever be updated, but which we're keeping for the time being as potential source material for updated docs. 6...
Application cache implementation overview
t that is associated the nsiapplicationcache object during the “cache selection algorithm” in nscontentsink::processofflinemanifest() described in “associating the top level document with offline cache” chapter above. nsiapplicationcachecontainer is then queried for nsiapplicationcache object. if found, the channel is then using that nsiapplicationcache object to load entries from. the following loading process decisions are then the same as for the top level load with one addition: when the entry is neither found in the cache nor matches any namespace in that cache we fail the resource load with document_not_found. falling back on a resource load failure when a resource previously matching a fallback namespace failed to load from the network, we perform fallback to the previously rem...
...n argument. when found, this update is processing an “update” and this cache is used as a cache to satisfy each manifest item and the manifest it self load from. otherwise, this is “first download”. then creates a new nsiapplicationcache for the given manifest url using nsiapplicationcacheservice::createapplicationcache(). this new cache version is now pending to be activated after all following long and complicated download process passes. until that it is not used for loading resources from. after these steps the update is in initialized state waiting to be scheduled. when the update is about to actually start, the scheduling service calls nsofflinecacheupdate::begin() method, that switches the update to checking state (+invokes onchecking event) and starts fetch of the manifest fil...
...“update”). during the load, manifest is parsed according the “parsing the cache manifest” html5 spec, and lists of entries and namespaces are collected. after the manifest fetch is done, nsofflinecacheupdate::loadcompleted() is called. nsofflinecacheupdate::loadcompleted() is called for each finished entry load, including the manifest and is the main place handling each update state as following: on checking state, a state the update is at after manifest parsing has been done, loadcompleted checks whether the new hash, i.e. the manifest content, differs or this is just “first download”. if so, the update switches to downloading state and fetches in parallel items listed in the manifest by call to nsofflinecacheupdate::processnexturi(). if the new hash is identical, upd...
Benchmarking
debug builds debug builds (--enable-debug) and non-optimized builds (--disable-optimize) are much slower. any performance metrics gathered by such builds are largely unrelated to what would be found in a release browser. rust optimization level local optimized builds are compiled with rust optimization level 1 by default, unlike nightly builds, which use rust optimization level 2. this setting reduces build times significantly but comes with a serious hit to runtime performance for any rust code (for example stylo and webrender). ...
...ilds are largely unrelated to what would be found in a release browser. rust optimization level local optimized builds are compiled with rust optimization level 1 by default, unlike nightly builds, which use rust optimization level 2. this setting reduces build times significantly but comes with a serious hit to runtime performance for any rust code (for example stylo and webrender). add the following to your mozconfig in order to build with level 2: ac_add_options rustc_opt_level=2 gc poisoning many firefox builds have a diagnostic tool that causes crashes to happen sooner and produce much more actionable information, but also slow down regular usage substantially. in particular, "gc poisoning" is used in all debug builds, and in optimized nightly builds (but not opt developer edition o...
...ls currently the gecko profiler has limitations in the ui for inverted call stack top function analysis which is very useful for finding heavy functions that call into a whole bunch of code. currently such functions may be easy to miss looking at a profile, so feel free to also use your favorite native profiler. it also lacks features such as instruction level profiling which can be helpful in low level profiling, or finding the hot loop inside a large function, etc. some example tools include instruments on osx (part of xcode), rotateright zoom on linux (uses perf underneath), and intel vtune on windows or linux. ...
Testopia
though it is designed with software testing in mind, it can be used to track testing on virtually anything in the engineering process. 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. ...
...port of test plans and children support csv export of test cases and results. new reports: worst offender and case roll-up set priorities on indidual case-runs new clone options uses the latest extjs 3.0 library converts testopia into a true bugzilla extension numerous bug fixes integration points testopia integrates with bugzilla products, components, versions, and milestones to allow a single management interface for high level objects. testopia allows users to login to one tool and uses bugzilla group permissions to limit access to modifying test objects. testopia allows users to attach bugs to test case run results for centralized management of the software engineering process. requirements as our development has moved forward, we have decided to try to kee...
...ugs to test case run results for centralized management of the software engineering process. requirements as our development has moved forward, we have decided to try to keep abreast of the latest stable release from bugzilla (currently 5.0). this gives us a stable code base to work from. developing plugins or extensions for any software is like trying to hit a moving target. this decision allows us to focus our time more on releasing new features often and early rather than back porting. however, this means that most major feature will not be back ported to earlier versions unless and until we have time to do so. anyone wishing to help in this effort is more than welcome. bugzilla 4.x mysql 5.0 or postgresql 8.3 mozilla compatible browser ;-) additional perl modu...
Building SpiderMonkey with UBSan
1. compile a recent version of llvm & clang. 2. save the following bash script, fixing llvm_root to point to your installation. #! /bin/sh if [ -z $1 ] ; then echo "usage: $0 <dirname>" elif [ -d $1 ] ; then echo "directory $1 already exists" else autoconf2.13 autoconf213 mkdir $1 cd $1 llvm_root="$home/llvm" sanflag="-fsanitize=undefined -fno-sanitize=alignment,float-cast-overflow,float-divide-by-zero,vptr -dxmalloc=myxmalloc" \ cc="$llvm_root/build/release+asserts/bin/clang" \ cxx="$llvm_root/build/release+asserts/bin/clang++" \ cflags="$sanflag" \ cxxflags="$sanflag" \ moz_llvm_hacks=1 \ ../configure --enable-debug --disable-optimize make -j 8 fi 3. use the script to compile spidermonkey. this enables all the chea...
...cxx="$llvm_root/build/release+asserts/bin/clang++" \ cflags="$sanflag" \ cxxflags="$sanflag" \ moz_llvm_hacks=1 \ ../configure --enable-debug --disable-optimize make -j 8 fi 3. use the script to compile spidermonkey. this enables all the cheap undefined behavior checks other than: alignment, which hits known bugs in spidermonkey, and is more implementation-defined (slow on x86 / crash on arm) than undefined behavior float-cast-overflow, which hits known bugs in spidermonkey, and isn't exploited by today's compilers float-divide-by-zero, which jesse doesn't think is actually undefined behavior (aside from the question of whether cpu overflow flags are set) vptr, a check that requires rtti, which is disabled by default in spidermonkey 4. when you hit a bug ...
... ...
Continuous Integration
lem and closing the tree (i.e., preventing any additional commits). results in treeherder are ordered by mercurial pushes. each taskcluster job is represented by a colored label; green means a job has succeeded, while other colors represent different kinds of problems. the label text indicates the job type. for a full list of job types, see the help menu in treeherder's upper-right corner. below is a list of the most common. builds b - normal build jobs; these jobs perform compilation and some compiled-code tests (e.g., 'make check'). be - b2g build jobs for engineering builds; user builds are denoted with b, the same as for desktop and android builds. n and ne - nightly build jobs; these jobs are similar to b and be jobs, but are triggered on a periodic basis instead of being trig...
...es run even if a build job fails, if the build job failed during 'make check'. talos performance tests all performance tests displayed in treeherder are run using the talos framework, and denoted by the letter t. these jobs are scheduled at the same time as the correctness jobs. talos is used to execute several suites for desktop firefox and firefox for android; these suites are denoted using lower-case letters, e.g., t(c d g1 o s tp). the talos indicators in treeherder appear green if the job successfully completed; to see the performance data generated by the jobs, click on the performance tab of the job details panel that pops up when you click on a job in treeherder. each talos suite contains a set of tests or pages, some of these in turn have sub-tests. each test is executed multi...
...accessible via the perfherder interface. other performance systems autophone (android) autophone is a test harness which runs a set of performance tests on a variety of real android phones. it reports to a custom dashboard known as phonedash. tests currently run are primarily startup tests. games benchmarking (firefox) under development, the games benchmarking harness (aka mozbench) will allow a number of games-related benchmarks to be run against firefox and chrome. eventually, the system will likely be expanded with support for android. post-job analysis and alerts there is some analysis of test data that occurs out-of-band after jobs complete. perfherder alerts we track changes to talos and other performance frameworks inside perfherder, and try to automatically alert when ther...
Debugging JavaScript
ole = (cu.import("resource://gre/modules/console.jsm", {})).console; console.log("hello from firefox code"); error console this is obsolete and is no longer enabled in firefox by default. use the web console or the browser console instead. browser debugger (built-in) on firefox 19 or later, it's possible to use the built-in js debugger on the browser itself. go to about:config and set the following two prefs: devtools.chrome.enabled: true devtools.debugger.remote-enabled: true after you restart the browser, you can access the browser debugger through tools > web developer > browser toolbox. (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 disa...
... are not errors). console.log in browser console you can dump variables in the browser console from addon code, by adding this line to import the console utility: const { console } = components.utils.import("resource://gre/modules/devtools/console.jsm", {}); this has an advantage over dump in that you can list out properties of an object logged with console.log. ...
... log.jsm (formerly log4moz) this is a partial implementation of the log4* interfaces (for example, see log4j or log4net). ...
Simple Instantbird build
steps needed to build a bleeding-edge, development version of instantbird. for additional, more detailed information, see the build documentation. this should be kept in sync with simple thunderbird build, you might want to take a look at that page too. build prerequisites hardware requirements: while you can build instantbird on older hardware it can take quite a bit of time to compile on slower machines, and having 8gb of ram is recommended (though you can probably still get away with 4gb). good internet connection for the initial source download. setup: depending on your operating system you will need to carry out a different process to prepare your machine. so firstly complete the instructions for your os and then continue following these build instructions. windows build pre...
...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, or just add the ac_add_options -...
...ueze.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, or just add the ac_add_options --enable-extensions=purple line to your .mozconfig with your favorite editor. then just re-run the mach command above (you may need to clobber (see below), or you can do the addition before running make for the first time). running to run your build, you can use ./mozilla/mach run there are various command line parameters you can add, e.g. to specify a profile. various temporary files, libraries, and the instantbird executable will be found in your object directory (under comm-central/), which is prefixed with obj-. the exact name depends on ...
Communicating with frame scripts
space, so to avoid conflicts with other code, you'll need to ensure that the names you use are unique. if you're using the message manager in an add-on, a good way to do that is to prefix messages with your add-on's id. after the name, you can pass detailed data as a string or a json-serializable object, and after that you can pass any objects it wants to pass to content as cpows. ...
...ion (event) { sendasyncmessage("my-addon@me.org:my-e10s-extension-message", { details : "they clicked", tag : event.target.tagname }, { target : event.target }); }, false); to receive messages from content, a chrome script needs to add a message listener using the message manager's addmessagelistener() api. the message passed to the listener is an object containing the following properties: name string containing the message name. sync boolean declaring whether the message was send synchronously or aynchronously. data the json object passed as the second parameter to sendasyncmessage(). target the xul <browser> element from which this message was sent. objects an object whose properties are any cpows exposed...
... boolean declaring whether the message was send synchronously or aynchronously. data the json object passed as the second parameter to sendasyncmessage(). target the xul <browser> element from which this message was sent. ...
Process scripts
s must be registered in the content process, but if you do this in a frame script, and the frame script is loaded more than once, then you will get multiple notifications for that event. the solution in these cases is to use a process script instead of a frame script. you can load a process script by accessing a parent process message manager and calling its loadprocessscript() function. the following code uses the global parent process message manager, which will load the script into the the chrome process and any child processes: // chrome code let ppmm = cc["@mozilla.org/parentprocessmessagemanager;1"] .getservice(ci.nsiprocessscriptloader); ppmm.loadprocessscript("chrome://whatever/process-script.js", true); ppmm.addmessagelistener("hello", function(msg) { ... }); the process script...
...cessmessagemanager sendasyncmessage("hello"); in this example, the dump() statement will run once in each content process as well as in the main process. this example also figures out whether it is running in the chrome or in a content process by looking at the process type in services.appinfo. in just about every respect, using process scripts is like using frame scripts: you can pass the allowdelayedload to loadprocessscript(). if you do, you must call removedelayedprocessscript() when your extension is disabled or removed the message-passing apis are the same: sendasyncmessage() is available in both directions, while sendsyncmessage() is available from content to chrome only process scripts are system-privileged, and have access to the components object. however, process scripts are...
...cript contains a content document or window it can be useful to not use talk through the child/parent process message managers but through the window's content frame message manager, e.g. if responses should be processed by a frame script instead of the process script. ...
Message manager overview
e more general sense of a web browser. global message manager the global message manager operates on every <browser> (that is, every open content tab). loadframescript() loads the given script into every <browser> in every browser window. broadcastasyncmessage() sends the message to every <browser> in every browser window. ...
... the window message manager is associated with a specific browser window, and operates on every <browser> (that is, every content tab) loaded into that window: loadframescript() loads the given script into every <browser> in that browser window broadcastasyncmessage() sends the message to every <browser> in that browser window. ...
...s the given script only into its <browser> sendasyncmessage() sends the message only to that <browser>. you can mix and match: so for example, you could load a script into every <browser> using the global message manager, but then send a message to the script instance loaded into a specific <browser> using the browser message manager. ...
Tracking Protection
the address bar to view information about the currently loaded page. the popup that appears will notify you when content has been blocked. you will also be able to disable tracking protection entirely if you choose by accessing the tracking settings. if tracking cookies were present, you would be able to view the list by clicking on "blocking tracking cookies" in the above image to view the following popup: you can click "manage content blocking" to change the blocking settings: how does firefox choose what to block? content is blocked based on the domain from which it is to be loaded. firefox ships with a list of sites which have been identified as engaging in cross-site tracking of users. when tracking protection is enabled, firefox blocks content from sites in the list. sites t...
...tising or analytics services that engage in tracking more subtly, if other parts of your site depend on trackers being loaded, then these parts will also be broken when tracking protection is enabled. for example, if your site includes a callback that runs when content from a tracking site is loaded, then the callback will not execute. ...
... ...
Security best practices for Firefox front-end engineers
s when developing front-end code for firefox. existing security controls sanitizing all strings that enter the dom through apis such as innerhtml when running system-privileged chrome code, we sanitize all html fragments that are created for chrome-privileged documents. this policy includes all dom apis that take a string and parse it into a dom tree. we use our built-in sanitizer with the following flags: sanitizerallowstyle sanitizerallowcomments sanitizerdropforms sanitizerlogremovals the sanitizer removes all scripts (script tags, event handlers) and form elements (form, input, keygen, option, optgroup, select, button, datalist). the canonical truth for the list of whitelisted elements is the source code. the last flag ensures that developers will identify and avoid the problems ea...
...(form, input, keygen, option, optgroup, select, button, datalist). the canonical truth for the list of whitelisted elements is the source code. the last flag ensures 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 co...
...ing literals that are hard coded in the source code, assuming benevolent developers. ...
Firefox UI considerations for web developers
take a look at how to influence the appearance of your site in firefox user interface elements such as the top sites box. top sites the top sites box lists a user-configurable number of rows of icons serving as quick links to sites the user commonly visits, or that the user has chosen to pin to the top sites list in order to have quick access to them. each site is represented by an icon and, below it, a name for the site. while both of these can be edited by the user, you may wish to ensure that your site provides a good icon to use in places like this. how an icon is selected the new tab page chooses icons to use for top sites by trying a series of methods until it obtains an icon to use: a global "top sites" list is checked. this list is created by a mozilla service called tippy top...
...ico"> in this code, the 128x128 pixel icon will be used by firefox, as it's the smallest icon which is larger than the 96-pixel size it requires. note: only "rich" icons (apple-touch-icon and fluid-icon) support the sizes attribute. you can't specify the size for rel="icon" using the sizes attribute. examples consider again the example top sites box shown at the top of the page, repeated below: let's look at some examples among the icons shown here (note that this discussion is based on the site designs as of early january, 2019). usa today the only icon provided by usa today is its classic favicon: <link rel="shortcut icon" href="https://www.gannett-cdn.com/sites/usatoday/images/favicon.png"> since no rich icon is available, firefox creates a screenshot of the home page rendere...
...ly icon provided by usa today is its classic favicon: <link rel="shortcut icon" href="https://www.gannett-cdn.com/sites/usatoday/images/favicon.png"> since no rich icon is available, firefox creates a screenshot of the home page rendered 560 pixels wide. the screenshot is then drawn in the icon box, which scales and crops the image as needed to fit. the favicon is rendered in a small box in the lower-right corner of the icon box to further identify the site. hootsuite the html on hootsuite's site looks roughly like this: <link rel="shortcut icon" href="/dist/images/icons/favicon.ico"> <link rel="apple-touch-icon-precomposed" href="/dist/images/icons/apple-touch-icon.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/dist/images/icons/apple-touch-icon_72.png"> <link rel="...
Roll your own browser: An embedding how-to
config. what bits do i need? one of the requirements of building a sdk is the ability to identify and package up required files. like that isn't totally obvious, nonetheless it has to be done. here is that effort. i have created a directory under embedding called config. contained within this directory are a couple of makefiles: basebrowser-unix basebrowser-win the xpinstall packager follows the same format. however in our case, we only have one named xpi package. after the build is done, you can change directory into mozilla/embedding/config, and do a make. this will produce a directory in dist named embed. it should include all of the base support that you need to get a web browser started up. included is the sample test application (gtkembed or winembed). what initializations ...
...lla source tree. linux external projects sashxb: ibm uses mozilla to implement part of their sash development/desktop environment. part of the gnome effort. activestate's komodo: development environment, based on mozilla's xul. (screenshot) light: very simple non-bloated gtk+ interface, familiar netscape 4.x keyboard shortcuts, context menus, etc. (screenshot) xparts: kde extension that allows mozilla to be embedded into the konqueror browser. uses gtkmozembed widget, part of the kdebindings module and available from http://websvn.kde.org/trunk/kde/kdebindings/xparts/. (news release, screenshot) mozilla examples gtkmozembed widget: gtk widget wrapper for the mozilla gecko engine. testgtkembed: basic browser built with the gtkmozembed widget. url location field, menu bar, html ar...
...browser. activestate's komodo: development environment, based on mozilla's xul. (screenshot) macromedia homesite html editor: internal browser for the homesite studio application is implemented by embedding mozilla. (mozilla blurb) bradsoft's topstyle css builder: implements an internal browser using mozilla activex embedding control.obsolete since gecko 7.0 nxzilla: a set of libraries that allow mozilla to be used with a nanox server. activex control: an activex control allowing for embedding the gecko layout engine.obsolete since gecko 7.0 llmozlib & ubrowser: a static library that allows you to embed gecko and render pages to memory. includes test applications that illustrate how to use it. versions for windows and mac with linux to follow. mozilla examples mfcembed: standard mo...
Gecko SDK
es. you do have to get and distribute the newest gecko components (gklayout.dll etc.), though. downloading for gecko versions before 2.0, you should choose the gecko sdk version for the earliest version of mozilla you wish to target. for gecko versions 2.0 and higher, you must recompile your component for each release as cross-version compatibility is no longer supported. in addition to the below versions, you can find other versions (including beta) here: xulrunner releases (files include "sdk" in the name). the sdk follows the same release schedule as firefox/thunderbird. once the sdk enters beta, it is suitable for building extensions; your component should work with release builds of the sdk without any modifications. due to the rapid release process, it may be a good idea to targe...
... unfortunately, this is caused by a problem with the sdk build process which cannot currently be resolved (see bugzilla bug #430274). to get around it, you'll need to first install macports as outlined in the mac os x build prerequisites and install libidl with it. on 64-bit versions of mac os x, you'll need to install libidl with the +universal flag. once that's done, you should perform the following command: ln -s /opt/local/lib/libintl.8.dylib /opt/local/lib/libintl.3.dylib this should fix the problem. building the sdk to build the sdk, you should build xulrunner (the gecko sdk is built as part of the xulrunner build process, which is why it's sometimes called the xulrunner sdk). see the build documentation for complete details. after the xulrunner build is complete running make sdk ...
...ilding the sdk to build the sdk, you should build xulrunner (the gecko sdk is built as part of the xulrunner build process, which is why it's sometimes called the xulrunner sdk). see the build documentation for complete details. after the xulrunner build is complete running make sdk from your object directory will create a package of the sdk in dist. contents of the sdk the sdk contains the following: 1.9.2 idl files for frozen interfaces (under idl/) header files for frozen interfaces, xpcom functions, and nspr functions (under include/) import libraries or shared libraries (under lib/) static utility libraries (under lib/) various tools (under bin/) for more information about safely linking xpcom components using the xpcom "glue" library, see xpcom glue. using the mozilla buil...
How Mozilla determines MIME Types
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 library will be asked for the mime type giv...
...e file for "magic numbers"; this can currently detect pdf and postscript. if the file starts with <?xml, asks the externalhelperappservice for a mime type for the uri. this is done because the generic text/xml mime type does not work for xul files, and xhtml files get a different dom when interpreted as text/xml. the image library will be asked for the mime type given the content. this should allow reliable detection of all image types mozilla supports. checks whether the data is html by looking for some common html tags. the uri is handed to the externalhelperappservice for mime type guessing if all else fails, the buffer (i.e. the first few bytes of the file) is searched for embedded nulls; if none are found, text/plain will be used, otherwise application/octet-stream. externalhelper...
...in edit/preferences/helper applications) if that failed, a list of "extra" mime types is searched for an extension match. see line 507 for the complete list. if that also failed, the list of loaded plugins is checked for a plugin that can handle this extension, and is asked for the mime type if no plugin is registered, the ext-to-type-mapping xpcom category is searched for the extension. this allows extensions to register additional mappings. the key of the category entry is the extension without leading dot, the value is the mime type. the extension must be lowercase. if no ext-to-type-mapping category is found, the externalhelperappservice returns application/x-extension-ext, where ext is the extension of the file. helper applications a somewhat related issue are the helper applicatio...
Infallible memory allocation
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. ...
... 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. ...
...nt may grow bigger than you expect; people and pages do surprising things all the time! when instantiating objects, the new operator creates them infallibly by default. if you want to allocate them fallibly, use the syntax new (fallible) foo(). when in doubt, use the infallible allocator and don't null check. ns_alloc() is also infallible. explicitly infallible memory allocators the following memory allocators are explicitly infallible, and will remain so; they are guaranteed to return a valid memory pointer. p = moz_xmalloc(); p = moz_xcalloc(); p = moz_xrealloc(); p = moz_xstrdup(); f = new foo(); farray = new foo[]; n = ::operator new(...); narray = ::operator new[](...); explicitly fallible memory allocators these memory allocators are explicitly fallible, and will rema...
JavaScript-DOM Prototypes in Mozilla
s to expose to xpconnect 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 ...
...if such objects are provided, they are not guaranteed by any specifica...
...if such objects are provided, they are not guaranteed by any specification to have any effect on the environment. results in other browsers is not guaranteed. so ...
FxAccountsOAuthClient.jsm
the fxaccountsoauthclient.jsm javascript module provides a way for browser services to authenticate with the firefox accounts oauth server. components.utils.import("resource://gre/modules/fxaccountsoauthclient.jsm"); creating a new fxaccountsoauthclient new fxaccountsoauthclient(object options); method overview launchwebflow(); teardown(); attributes parameters object returns the set of parameters that initialized the firefox accounts oauth flow. oncomplete function gets called when the firefox accounts oauth flow successfully completes. first and only argument is an object that has "state" and "code" properties. constructor fxaccountsoauthclient() creates and returns a new fxaccountsoauthclient object. fxaccountsoauthclient fxacc...
...uth api server uri, versioned. example: "https://oauth.accounts.firefox.com/v1" content_uri - the fxa content server uri. example: "https://accounts.firefox.com" [optional] scope - a colon-separated list of scopes that the user has authorized. [optional] action - if provided, should be either "signup" or "signin". parameters set of parameters to initialize the firefox accounts oauth flow. authorizationendpoint optional optional authorization endpoint for the oauth server. default: /authorization return value a newly created fxaccountsoauthclient object implementing the methods described in this article. methods launchwebflow() opens a new tab at the firefox accounts oauth authorization url. registers a webchannel listener and sets up a callback if needed. parameters ...
...the fxaccountsoauthclient chrome code let parameters = { oauth_uri: oauth_server_endpoint, client_id: oauth_client_id, content_uri: content_server_url, state: oauth_state } let client = new fxaccountsoauthclient({ parameters: parameters }); client.oncomplete = function (tokendata) { // tokendata consists of two properties: "tokendata.state" and "tokendata.code" }; client.launchwebflow(); ...
Interfacing with the Add-on Repository
sion%/list/recommended/all/%max_results%/%os%/%version%?src=firefox"); prefsservice.savepreffile(null); } this fetches the value of the extensions.getaddons.recommended.url preference, 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 ver...
...ng 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 the repository to fetch up to 10 add-ons, using the object this as the target for callbacks. the callback object needs to implement the searchcallback interface, providing the methods that get called when a search either fails or completes successfully. handling failed requests the callback ...
...nce being incorrect) is if there is already a pending request, since only one request can be in progress at a time. for example: searchfailed: function() { this.shownotification("i have no recommendations for you right now!", "oh noes!", null); }, here, we call a shownotification() method with some parameters that we'll look at shortly when we get to our shownotification() method below. the important thing to note is that this will handle the failure case. handling successful requests the callback object's searchsucceeded() method gets called when a search completes successfully. it receives a list of the matching addons, the number of add-ons returned, and the total number of add-ons that matched the query (in case the returned number is smaller than the requested number, fo...
Log.jsm
sarily "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: append(); doappend(); level: 0 basicformatter(); length: 1 keys of ...
... leveldesc logger(); length: 2 keys of prototype: addappender(); level logstructured(); name parent removeappender(); updateappenders(); and the methods mentioned below: logger methods loggerrepository(); length: 0 keys of prototype: getlogger(); rootlogger storagestreamappender(); length: 1 keys of prototype: doappend(); getinputstream(); newoutputstream(); outputstream ...
...m reset(); structuredformatter(); length: 0 keys of prototype: format(); method overview enumerateinterfaces(); length: 0 enumerateproperties(); length: 2 member fields variable type description level object contains the following fields: field name value all 0 config 30 debug 20 desc { 0: "all", 10: "trace", 20: "debug", 30: "config", 40: "info", 50: "warn", 60: "error", 70: "fatal" } error 30 fatal 70 ...
Examples
iple promises in function in pareallel, how return when last done? simple example user defined promise function 2 whenever you want to make a function a promise. always wrap that function in a try catch and make that catch return promise.reject(ex) otherwise it will not trigger the rejection function of the promise.then. this way if any error happens it will reject the promise. in the example below we try alerting an undefined variable. components.utils.import("resource://gre/modules/promise.jsm"); var mypromise = myuserdefinedpromise(); mypromise.then( function(asuccessreason) { alert('mypromise was succesful and reason was = "' + asuccessreason + '"'); }, function(arejectreason) { alert('mypromise failed for reason = "' + uneval(arejectreason) + '"'); } ); function myus...
.... 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. ...
...thatpromise.then has never been called), then we print a warning. note: this warning is generated some time after the error occurred, and may provide less information about the error location. it generally indicates the need to insert a proper error handler. when ...
Promise
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 handling errors and common pitfalls below. documentation conventions in documentation, the type of the fulfillment value is usually specified between angular brackets. for example, the os.file.exists function returns a promise that will eventually fulfill with a boolean: promise<boolean> exists(string path); the rejection reason may be specified separately in the function's documentation, and is considered to be an error object unl...
...led or rejected, will have no effect the second time, as the associated promise is already resolved to the pending promise. void resolve( avalue ); parameters avalue optional if this value is not a promise, including undefined, it becomes the fulfillment value of the associated promise. if this value is a promise, then the associated promise will be resolved to the passed promise, and follow the state as the provided promise (including any future transitions). reject() rejects the associated promise with the specified reason. if the promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. void reject( areason ); parameters areason optional the rejection reason for the associated promise. although the reason can be ...
...romise, the new promise will eventually assume the same state as the returned promise. catch() equivalent to then() with an undefined value for the onfulfill parameter. if you chain then( onfulfill ).catch( onreject ), exceptions thrown in onfulfill will be caught and passed to onreject, which is not the case when just passing onreject to then(). promise catch( function onreject ); the following calls are therefore identical: p.then(undefined, logerror); p.catch(logerror); debugging by design, the instant state and value of a promise cannot be inspected synchronously from code, without calling the then() method. to help with debugging, only when inspecting a promise object manually, you can see more information as special properties that are inaccessible from code (this, at prese...
JavaScript code modules
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 to interact with customizable buttons and items in firefox's main window ui. deferredtask.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 ...
... 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 strings. log.jsm (formerly log4moz) provides a log4j style api for logging, log messages to various endpoints, such as the browser console or a file on disk. netutil.jsm provides helpful networking utility functions, including the ab...
...yle api for logging, log messages to various endpoints, such as the browser console or a file on disk. netutil.jsm provides helpful networking utility functions, including the ability to easily copy data from an input stream to an output stream asynchronously. openlocationlasturl.jsm provides access to the last url opened using the "open location" option in the file menu. osfile.jsm allows routines to access files. to which can be read, write, rename, create directories,etc. perfmeasurement.jsm provides access to low-level hardware and os performance measurement tools. pluralform.jsm supplies an easy way to get the correct plural forms for the current locale, as well as ways to localize to a specific plural rule. popupnotifications.jsm gives an easy way to present non-modal ...
Encodings for localization files
er the windows installer can’t handle utf-8, but only the codepages provided by windows. this is tricky to hook up in the build process, so here it goes: file encoding notes toolkit/installer/windows/charset.mk ascii the win_installer_charset variable must be set to an encoding which matches toolkit/installer/windows/install.it charset= parameter. see the table below for appropriate values. toolkit/installer/windows/install.it a windows codepage. this must match the charset= parameter in this file, and the win_installer_charset parameter in charset.mk the fontname/fontsize/charset parameters in this file must be set to good values. for most western scripts, ‘ms sans serif’ and ‘8’ are good defaults for the font settings. eastern scripts...
...depage. this must match the charset= parameter in this file, and the win_installer_charset parameter in charset.mk the fontname/fontsize/charset parameters in this file must be set to good values. for most western scripts, ‘ms sans serif’ and ‘8’ are good defaults for the font settings. eastern scripts will need to choose appropriate fonts that are shipped with windows. ...
...t western scripts, ‘ms sans serif’ and ‘8’ are good defaults for the font settings. eastern scripts will need to choose appropriate fonts that are shipped with windows. see the table below for appropriate values for the charset= parameter. ...
Mozilla Content Localized in Your Language
you are free to add, edit, remove, and localize everything in this section according to how the localization team for your language agrees. all we ask is that you name this page according to this example, "mozilla content in spanish (es-mx)" and add your locale code tag at the bottom. ...
...es-mx)" and add your locale code tag at the bottom. enjoy developing your style guide! your language's style guide abbreviations how are abbreviations expressed in your language? numerals and metrics how are numerals and metrics expressed in your language? formal and informal forms, and separators (, or .) date format what are the date formats for weeks and months are expressed in the following forms: 1)fully spelled out, 2). 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...
...ogy 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 the total available line space. this allows localization text to expand and not be truncated or resolved through ellipsis. title on the final page (meaning no more click through) should allow enough room to display full text. buttons capitalize the first letter of each word. limit to one or two words. use verbs that precisely describe the button's action. for example, "cancel", "clear history", "add email", "s...
Patching a Localization
say you have found a problem with an existing localization. more specifically, it's a problem with an already released localization. what do you do now? well, you have come to the right place! this page will walk you through creating a patch for an existing localization. the steps below are fairly generic; for the most part they apply to creating l10n patches for firefox, thunderbird, seamonkey, or calendar. i'll use firefox in the example below to help you understand the general steps to creating a l10n patch. prerequisites if you are to the point that you are patching existing localizations, we assume that you have the basic set of tools listed on the l10n prerequisites wiki page. if you do not have these tools, take a few steps back, grab a cookie (because, let's face it, you deser...
...). whenever you see gl in blue text, replace it with the locale code for your language. next thing you need to know is which localization version you want to patch. all of our localizations work on the aurora branch. the repository for this version is releases/l10n/mozilla-aurora. for more information about branches see l10n:branches. now let's get a little more detailed. start bash and do the following: create a clean directory for your work. for example, create a directory like localization-workdir (in this example it is located in your home directory): mkdir ~/localization-workdir navigate to the directory you just created. cd ~/localization-workdir clone the localization repository for your locale and for the version you want to patch: hg clone http://hg.mozilla.org/r...
... your modifications through displaying the differences in a unified patch's files. these modifications are printed to stdout (standard output). visually inspect your modifications. a good patch only contains those changes that you intended to make. if it contains more, you'll likely regress something else. alternatively, you can select specific files for diff to evaluate and print (see below). the command will only print the differences found in the selected files. hg diff browser/chrome/browser/browser.dtd attach the patch to an existing bug for reference or review or create a new one if one doesn't currently exist. hg diff > path/to/patchfile ...
Initial setup
curial is the revision control environment that houses the main mozilla source code as well as localized code for each official mozilla localization. you will need this for localizing mozilla applications. hg commit access is not necessary to begin localizing. after you have some experience with hg, you may want to get commit access. at that point, you must visit the mozilla committer page and follow the process outlined there. here is an example bug that illustrates the process well. use this bug template when filing your hg account registration bug. add a request about creating your locale's repository to the new locales newsgroup. svn svn is a revision control environment that mozilla uses to house mozilla source websites and their localizations for each official mozilla localization. se...
... another python script that helps you check your work without running an application. install instructions are located here. autoconf 2.13 autoconf is a utility that is vital to manually 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...
...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-ons for mozilla applications. either one is necessary to enable you to see your work within a mozilla application. you can install either by searching for them in firefox's add-ons manager or following these links. a solid, unicode-based, text editor here are some suggestions: windows: notepad++ or notepad2 gnu/linux: vim, gedit or kate mac os x: textwrangler gnu make make is a tool which controls the generation of executables. you can find version 3.79.1 or higher here. unfortunately, other varieties of make won't do. end of initial setup now that you've finished your ini...
Localization sign-off reviews
this article presents an overview of why we do sign-off reviews of localizations, the details on the criteria used for the sign-off reviews, and the process for requesting a review and for following its progress. the sign-off review process has been notoriously shrouded in mystery. we use 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 don...
...time testing your work and making sure all strings have been localized and that your changes are relatively functional. your review request symbolically represents that you have worked on your localization, tested it successfully, and found it to represent the best of your work. so before you request your sign-off review, be sure that it is as ready as it can be. there is a specific process to follow in bugzilla for requesting these reviews: file a bug requesting the review. attach your files to the bug. once attached, open the attachment details. in the attachment details, select the ? from the dropdown menu next to the appropriate approval flags (see image). this will display a text box to assign the review to someone. enter :pike as the requestee. once you have made the formal reques...
...es to the bug. once attached, open the attachment details. in the attachment details, select the ? from the dropdown menu next to the appropriate approval flags (see image). this will display a text box to assign the review to someone. enter :pike as the requestee. once you have made the formal request in bugzilla and you have pushed your work into your l10n repo, refer to the dashboards to follow your review's progress. sign-off dashboards to the right, you'll see the current sign-offs page for a german localization. sign-offs are approved using the buttons in the farthest column to the right. you can work with the l10n-drivers to track the progress of your review and correlate your review/sign-off's approval progress with specific bugzilla bugs. as your work is approved, you'll see a gr...
What every Mozilla translator should know
s mozilla.dev.planning, .planning in short. the mozilla project discusses general planning and schedule questions here. discussions of interest to the general mozilla developer community are at least notified here. translate the mozilla web or mozilla.dev.l10n.web, we moved announcements and discussions about the translation of the mozilla web pages to this group. all these groups are pretty low traffic. to keep the track of what's going on, it's also a good idea to read the planet mozilla l10n when you have a problem use the above mailing lists the person in charge of the mozilla l10n is axel hecht (l10n at mozilla.com), pike on irc another interesting way of getting help is the irc channel #l10n at irc.mozilla.org useful tools the l10n dashboard pontoon narro translate t...
...e default branch) -> firefox/thunderbird 3.0.x branch mozilla_1_8_branch -> firefox/thunderbird 2.0 branch mozilla cross-reference mozilla cross-reference is a web site mirroring the content of the hg server. here we can easily have a look into other languages translations. ...
...s translations. bugzilla, the bug-tracking system you do need an account in bugzilla you should configure the account to watch the following addresses: firefoxl10n@hotmail.com calendar-l10n@mozilla.bugs (specific for calendar related bugs) this way you will receive mail for bugs affecting many or even all locales. when you create a bug, if you want the person in charge of the l10n to follow up your bug you should cc: l10n@mozilla.com if you choose to make changes to your localization, you should make the changes local to your disk, push them to your hg repository on merucial, test the changes on a nightly/tinderbox build, fix any errors if some are found and test again, and send the new changeset id as your "opt-in" revisions to the l10-drivers. there is one exception to this proc...
MathML Demo: <mtable> - tables and matrices
as a visual aid, the examples deliberately draw attention to the math axis and the baseline: ----------------------- this is the math axis ..................... this is the baseline external vertical align is center ---... 1 22 333 4444 x 55555 666666 a b c 7777777 11 ...--- , cols arg is "|r|c|l|", \hline's above and below. when align="center" or align="baseline", the middle of the table coincides with the baseline. external vertical align is axis ---... 1 22 333 4444 x 55555 lim n→∞ f-1 ⋃ i=1 n ai rowspan=2 here xn + yn n columnspan=2 here 7777777 11 ...--- , columnlines="solid", rowlines="dashed solid dashed". by default -- when the align attribute is not set, or when align="ax...
...h align="axis2" to anchor the table externally w.r.t. the axis of the second row ---... ab α β abx yab γ δ ab ...--- , but this is subject to variances due to style changes, e.g., from the scriptlevel. ---... ab α β abx yab γ δ ab ...--- . anyway, this is buggy in mozilla because what you see above is a fallback to the rendering code used for the baseline case (see below). a table with align="baseline -1" to anchor the table externally w.r.t. the baseline of the last row ---... d+p ( α β γ δ ) ...--- , neat isn't it? this would be pretty hard to obtain otherwise. contrast it with the following which has align="bottom" ---... d+p ( α β γ δ ) ...--- , and with this one which has align="center -1" ---... d+p ( α β γ δ ) ...
...ter#rownumber"). these may sound like gimmicks until you want to get a damping effect such as this ---... ab ab ab ab ab ab , or perhaps the reverse ---... ab ab ab ab ab ab , modulo pixel roundoff errors. here 'a' and 'b' can be other combinations of possibly irregular boxes. and making floating elements do a multiplication such as the following one which is anchored at a baseline is made simple by using align="baseline1" on both tables [ a b c d ] [ a b c d ] to multiply a matrix a by a vector x, each row of the matrix has to be multiplied to the vector. so at the i-th step, it proceeds thus: i-th row [ a11 a12 a13 … a1n ⋮ ⋮ ⋮ … ⋮ ai1 ai2 ...
Using the viewport meta tag to control layout on mobile browsers
actly how to implement it in fennec. for example, safari's documentation says the content is a "comma-delimited list," but existing browsers and web pages use any mix of commas, semicolons, and spaces as separators. learn more about viewports in different mobile browsers in a tale of two viewports at quirksmode.org. viewport basics a typical mobile-optimized site contains something like the following: <meta name="viewport" content="width=device-width, initial-scale=1"> the width property controls the size of the viewport. it can be set to a specific number 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 tha...
... 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 generally have a 5-inch screens with resolutions upwards of 1920—1080 p...
... 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. these properties affect the initial scale and width, as well as limiting changes in zoom level. not all mobile b...
Mozilla Style System
css cascade. thus there is a single style rule processor for all user-agent css style sheets, a single style rule processor for all user css style sheets, and a single style rule processor for all author css style sheets. there is also a style rule processor for style attributes (which contain css declarations) and one for presentational attributes in html. the methods on nsistyleruleprocessor allow the front end to ask the back ends for the style data that applies to a given element or pseudo-element, 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 b...
...le (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. the style contexts then provide the api for computed style data by allowing retrieval of a set of style structs, each of which contains the computed values of a set of css properties. style structs the style structs are a set of structs, each of which holds computed values a group of properties. they all have names beginning with nsstyle*, and they should not be confused with the css structs (nscss*), which hold specified values. the grouping of properties into str...
...ieval of a set of style structs, each of which contains the computed values of a set of css properties. style structs the style structs are a set of structs, each of which holds computed values a group of properties. they all have names beginning with nsstyle*, and they should not be confused with the css structs (nscss*), which hold specified values. the grouping of properties into structs follows two rules: any properties in the same style struct must also be in the same css struct all of the properties in a style struct must be inherited or they must all be non-inherited (see inheritance for an explanation of the difference) the first of these rules is no longer important (in fact, the separation of the specified values into nscss* structs is no longer important). however, the sec...
turbostat
including numerous per-cpu measurements. this article provides an introduction to using it. 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. ...
...rovides an introduction to using it. 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. ...
... 3 3 702 19.14 3670 3398 0 8.39 3.09 2.03 67.36 39 3 7 648 17.67 3667 3398 0 9.85 the man page has good explanations of what each column measures. the various "watt" measurements come from the intel rapl msrs. ...
Performance
r. 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 continuous integration testing. refcount tracing and balancing refcount tracing and balancing are ways to track down leaks caused by incorrect uses of reference counting. they are slow and not particular easy to use, and thus most suitable for use by expert developers. gc and cc logs gc and cc logs can be generated and analyzed to in various ways. in particular, they can help you understand why a particular object is being kept alive. valgrind valgrind is a tool that detects various memory-related problems at runtime, including leaks. valgrind is used as par...
...c logs gc and cc logs can be generated and analyzed to in various ways. in particular, they can help you understand why a particular object is being kept alive. valgrind valgrind is a tool that detects various memory-related problems at runtime, including leaks. valgrind is used as part of mozilla's continuous integration testing, though the coverage is limited because valgrind is slow. leaksanitizer leaksanitizer (a.k.a. lsan) is similar to valgrind, but it runs faster because it uses static source code instrumentation. lsan is part of mozilla's continuous integration testing, with most tests running through it as part of the addresssanitizer (a.k.a. asan) test jobs. apple tools apple provides some tools for mac os x that report similar problems to those re...
...g 390944). leak gauge leak gauge is a tool that can be used to detect certain kinds of leaks in gecko, including those involving documents, window objects, and docshells. logalloc logalloc is a tool that dumps a log of memory allocations in gecko. that log can then be replayed against firefox's default memory allocator independently or through another replace-malloc library, allowing the testing of other allocators under the exact same workload. memory profiler the memory profiler samples allocation events and provides different views to analyze the allocation characteristic. see also the documentation on leak-hunting strategies and tips. profiling and performance tools profiling with the developer tools profiler the profiler...
A brief guide to Mozilla preferences
irefox being installed (nightly, aurora, beta, release) browser/defaults/preferences/firefox-l10n.js - defaults specific to the installed language of firefox. none of the other preference files contain locale-specific preferences. config. file a configuration file, usually with .cfg extension, may be called from a default pref file via the general.config.filename preference. this file allows preference locking via the lock_pref() function. details on the config file is beyond the scope of this document. user pref. files in the profile directory are two user pref files: prefs.js and user.js. prefs.js is automatically generated by the application and should not be edited manually, whereas user.js is an optional file the user can create to override preferences initialized by oth...
...iles in the profile directory are two user pref files: prefs.js and user.js. prefs.js is automatically generated by the application and should not be edited manually, whereas user.js is an optional file the user can create to override preferences initialized by other preferences files. preferences loading and resolution on application launch, the application loads preferences in the following order: load all default pref files. optionally 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 configuratio...
... optionally 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...
Patches and pushes
patchify search plugins are found in browser/searchplugins. each plugin is stored as an xml file, with list.txt containing the names of each plugin. here is an example search plugin file using french yahoo. ...
...for references on how each tag functions, visit the opensearch wiki page and the mozsearch wiki page. the pages are old (i mean, firefox 2???), but still accurate. each plugin has an icon image which is linked within the xml file as an uri id. upload your plugins icon image to data kitchen to obtain its uri id and add to the xml file within the image tag. in list.txt, add ...
...tchen to obtain its uri id and add to the xml file within the image tag. in list.txt, add the search plugin's xml filename (without extensions) on a new line and save. note that if your team selects a local version of an already default plugin (e.g., wikipedia), the xml filename should include the locale code (e.g., wikipedia-es). create a patch of the searchplugins directory by entering the following command in your command-line tool, where mypatch.diff is where you give your patch a name: $ hg add mozilla/browser/searchplugins/ $ hg diff mozilla/browser/searchplugins/ > mypatch.diff attach your patch file to the bug by clicking the "add an attachment" link. once attached and labeled as a patch, open the attachment details. in the attachment details, select the ? from the dropdown men...
Research and prep
t of the new product localization release process. it is your l10n team's responsibility to perform research and identify the most appropriate web services for your region and present them in your bug as your informed recommendations. if there's no existing collaboration with the site provider and mozilla, ask for permission from the site provider to include it. ensure that your suggestions follow these parameters: search there are typically five search plug-ins listed for firefox desktop (only four for firefox mobile): generic search the default option should expose the quickest path to the best result on the world wide web for the user (indexing a large portion of the global www). global search the second position can be used for the next best local language provider, m...
...the local language and/or locale (indexing a smaller portion of the www but producing better local language results). local search a good test is if you were to run a set of comparative queries; the secondary engine should produce the best local language results and the primary/default position should produce the best global results. e-commerce search these search engines should allow users to get connected to new and used products they want to buy as quickly and painlessly as possible in a "trusted" site -- for example, choosing the most popular auction, general shopping, or classified type sites that have the desired user experience are good choices. there should be no more than two. specific interest search where users are using popular search engines to search more...
...es, user experience should be taken into account and given preference for what is desired in that language/locale. if you have questions about what that means, please contact milos@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 pro...
Profile Manager
a copy of firefox 3.6.10, while profileb might be linked with a copy of firefox 3.5.3. when launched, profile manager will look in some default locations for installed versions of firefox (or other application you're using profile manager with). ...
......" button: each firefox version in the list has the following properties: path, version, and default. the default property indicates that this version of firefox will be used with profiles that don't have a specific application version associated with them. creating a profile to create a new profile, just click the new button from profile manager's toolbar. a dialog will appear that allows you to specify the profile's name, and optionally the profile's path, and the version of firefox (or other application) that will be used with this profile: launching firefox with a profile to launch firefox with a specific profile, select the profile in the main window, and hit the "start firefox" button: firefox will be launched with that profile, and profile manager will terminate. ...
...pted for a name and location for the archive. to create a profile from a profile archive: select "restore from->archive" from the toolbar's backup menu. you'll be prompted for the location of the archive, and then for the name of the profile you'd like to create from the archive. other operations context-clicking any profile in the profile list will cause a popup menu to appear with the following commands: copy - makes a copy of the profile using a name and location of your choice. delete - deletes the profile, and all files associated with it. properties - shows a dialog that displays the profile's path and last-modified date. rename - allows you to specify a new name for the profile. version - allows you change the default application version to be used with the profile. f...
L20n HTML Bindings
izable. <p data-l10n-id="about"></p> notice that you don't have to put the text content in the html anymore (you still can if you want to). all content lives in the localization resources. a safe subset of html elements (e.g. em, sup), attributes (e.g. title) and entities can be used in translations. in addition to the pre-defined whitelists, any element found in the original source html is allowed in the translation as well. consider the following source html: <p data-l10n-id="save"> <input type="submit"> <a href="/main" class="btn-cancel"></a> </p> assume the following malicious translation: <save """ <input value="save" type="text"> or <a href="http://myevilwebsite.com" onclick="alert('pwnd!')" title="back to the homepage">cancel</a>. """> the result will be: <...
... <a href="http://myevilwebsite.com" onclick="alert('pwnd!')" title="back to the homepage">cancel</a>. """> the result will be: <p data-l10n-id="back"> <input value="save" type="submit"> or <a href="/main" class="btn-cancel" title="back to the homepage">cancel</a>. </p> the input element is not on the default whitelist but since it's present in the source html, it is also allowed in the translation. the value attribute is allowed on input elements, but type is not. similarly, href and onclick attributes are not allowed in translations and they are not inserted in the final dom. however, the title attribute is safe. it is important to note that applying translations doesn't replace dom elements, but only modifies their text nodes and their attributes. this makes it poss...
...e localization context in form of context data. <script type="application/l10n-data+json"> { "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 l2...
Leak And Bloat Tests
total memory usage (aka bloat). provide a consistent number from build to build where no source code has changed. provide reasonable coverage for the normal activities that a user performs. method current method: measure leaks and bloats, in a similar way to firefox (using xpcom_mem_leak_log and --trace-malloc). ...
... on tinderbox output, these consist of: mail rlk reference count leaks mail lk total bytes malloc'ed and not free'd mail mh maximum heap size mail a allocations - number of calls to malloc and friends. there are currently no graphs for these results. manually running tests setting up build set up build thunderbird or seamonkey with your standard mozconfig file, but with the following options set: ac_add_options --enable-debug ac_add_options --enable-trace-malloc running the tests in your <objdir> run the following command: make mailbloat this will run the tests and produce some result files. see debugging memory leaks for more information on what to do with this data. todo: add more information on processing output. code locations the files specific to leak and bloat te...
...entral/source/mailnews/test/performance these files consist of: overlays (used to provide the hooks for the javascript): bloat/bloataddroverlay.xul bloat/bloatcomposeoverlay.xul bloat/bloatmainoverlay.xul javascript files (used to drive the tests): bloat/bloataddroverlay.js bloat/bloatcomposeoverlay.js bloat/bloatmainoverlay.js preference settings (used to provide a defined profile, see below): common/mailnewstestprefs.js python scripts (used to set up the profile and run the test): bloat/setupbloattest.py bloat/runtest.py common/setupcommonmailnews.py pre-defined profile initial setup: one pop3 account (mails tbd) one identity one smtp server defined (not used) future requirements/possibilities: one address book where pab has ~1000 entries large message folders imap nntp ...
Midas editor module security preferences
default settings when you're done! changing the preferences in firefox quit firefox. if you have quick launch running (on windows, this is an icon in the toolbar), quit that too. find your firefox profile directory. open the user.js file from that directory in a text editor. if there's no user.js file, create one. add these lines to user.js: user_pref("capability.policy.policynames", "allowclipboard"); user_pref("capability.policy.allowclipboard.sites", "https://www-archive.mozilla.org"); user_pref("capability.policy.allowclipboard.clipboard.cutcopy", "allaccess"); user_pref("capability.policy.allowclipboard.clipboard.paste", "allaccess"); change the url https://www.mozilla.org to the site for which you want to enable this function. save the file and restart firefox. the clipbo...
...lity.policy.allowclipboard.clipboard.paste", "allaccess"); change the url https://www.mozilla.org to the site for which you want to enable this function. save the file and restart firefox. the clipboard buttons in the demo, or similar buttons on the sites you listed, should now function. note: the preference is site as well as protocol specific. for example: user_pref("capability.policy.allowclipboard.sites", "http://www-archive.mozilla.org") is not the same as: user_pref("capability.policy.allowclipboard.sites", "https://www-archive.mozilla.org") this is because the first uses http while the second uses https. if you want to allow multiple urls to access the paste operation, separate the urls with a space. ...
...ref("capability.policy.allowclipboard.sites", "http://www-archive.mozilla.org") is not the same as: user_pref("capability.policy.allowclipboard.sites", "https://www-archive.mozilla.org") this is because the first uses http while the second uses https. if you want to allow multiple urls to access the paste operation, separate the urls with a space. for example: user_pref("capability.policy.allowclipboard.sites", "https://www-archive.mozilla.org https://developer.mozilla.org") again, keep in mind the security risks involved here and be sure to remove permission to access the clipboard once you no longer need it enabled. ...
NSPR Contributor Guide
ive us something you snatched from somewhere else;. it must be your own invention, free and clear of encumberment of anyone or anything else; pay close attention to the rights of your "day-job" employer. if you snatched it from somewhere else, tell us where; show us where the right to incorporate it into nspr exists. license under mpl or gpl when you contribute material to nspr, you agree to allow your contribution to be licensed under the mpl or gpl. bugfixes use bugzilla to track bugs. document the bug or use an existing report. be verbose in describing what you are doing and why. include your changes as diffs in an attachment to the bugzilla report. use a coding style consistent with the source file you are changing. new features for purposes of this paper, a "new feature" is defi...
...w features for purposes of this paper, a "new feature" is defined as some api addition that goes into the core nspr library, for example: libnspr4.dll nspr is mostly complete. new apis are driven mostly by the os vendors as they add new features. should you decide that there's something that nspr does not cover that should be covered, let's talk. your proposed api should encapsulate a relatively low level capability as would be found in a system call or libc. your new feature must be implemented on all platforms supported by nspr. when you consider a new api for nspr ask yourself if your proposed feature can implement it across all platforms supported by nspr. if several platforms cannot be made to implement your api, then it is not a good candidate for inclusion in nspr. before you begin wh...
...pis that you may add to nspr. header file descriptions. provide header file descriptions that fully document your public typedefs, enums, macros and functions. see: prshm.h as an example of how your header file(s) should be documented. source file descriptions. provide descriptive documentation in your source (*.c) files. alas, we have no source files documented as we think they should be. the following are some general guidelines to use when implementing new features: don't export global variables your code must be thread safe you must provide test cases that test all apis you are adding. see: [#testcases test cases] new libraries all the guidelines applicable to [#newfeatures new features] applies to new libraries. for purposes of this paper, a "new library" is defined as a libary un...
NSPR LOG MODULES
this environment variable specifies which log modules have logging enabled. syntax modulename:level[, modulename:level]* modulename is the name specified in a pr_newlogmodule call or one of the handy magic names listed below. level is a numeric value between 0 and 5, with the values having the following meanings: 0 = pr_log_none: nothing should be logged 1 = pr_log_always: important; intended to always be logged 2 = pr_log_error: errors 3 = pr_log_warning: warnings 4 = pr_log_debug: debug messages, notices 5: everything! description specify a modulename that is associated with the name argument in a call to pr_newlogmodule and a non-zero level value to enable logging for the named modulename. special log module names are provided for controlling nspr's log service at execut...
...l value to enable logging for the named modulename. special log module names are provided for controlling nspr's log service at execution time. these controls should be set in the nspr_log_modules environment variable at execution time to affect nspr's log service for your application. all the name all enables all log modules. to enable all log module calls to pr_log, set the variable as follows: set nspr_log_modules=all:5 timestamp including timestamp results in a timestamp of the form "2015-01-15 21:24:26.049906 utc - " prefixing every logged line. append including append results in log entries being appended to the existing contents of the file referenced by nspr_log_file. if not specified, the existing contents of nspr_log_file will be lost as a new file is created with the...
... append including append results in log entries being appended to the existing contents of the file referenced by nspr_log_file. if not specified, the existing contents of nspr_log_file will be lost as a new file is created with the same filename. sync the name sync enables unbuffered logging. this ensures that all log messages are flushed to the operating system as they are written, but may slow the program down. bufsize:size the name bufsize:size sets the log buffer to size. examples log everything from the toolkit::storage component that happens, prefixing each line with the timestamp when it was logged to the file /tmp/foo.log (which will be replaced each time the executable is run). set nspr_log_modules=timestamp,mozstorage:5 set nspr_log_file=/tmp/foo.log logging with try ser...
PRIntervalTime
ine 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 for interval times are allowed to overflow. since the sampling of the counter used to define an arbitrary epoch may have any 32-bit value, some care must be taken in the use of interval times. the proper coding style to test the expiration of an interval is as follows: if ((printervaltime)(now - epoch) > interval) <... interval has expired ...> as long as the interval and the elapsed time (now - epoch) do not exceed hal...
...nce the sampling of the counter used to define an arbitrary epoch may have any 32-bit value, some care must be taken in the use of interval times. the proper coding style to test the expiration of an interval is as follows: if ((printervaltime)(now - epoch) > interval) <... interval has expired ...> as long as the interval and the elapsed time (now - epoch) do not exceed half the namespace allowed by a printervaltime (231-1), the expression shown above provides the expected result even if the signs of now and epoch differ. the resolution of a printervaltime object is defined by the api. nspr guarantees that there will be at least 1000 ticks per second and not more than 100000. at the maximum resolution of 10000 ticks per second, each tick represents 1/100000 of a second. at that rate, a...
...-1), the expression shown above provides the expected result even if the signs of now and epoch differ. the resolution of a printervaltime object is defined by the api. nspr guarantees that there will be at least 1000 ticks per second and not more than 100000. at the maximum resolution of 10000 ticks per second, each tick represents 1/100000 of a second. at that rate, a 32-bit register will overflow in approximately 28 hours, making the maximum useful interval approximately 6 hours. waiting on events more than half a day in the future must therefore be based on a calendar time. ...
PR_CreateFileMap
read-only access. pr_prot_readwrite. readable, and write is shared. pr_prot_writecopy. ...
...o.h> prfilemap* pr_createfilemap( prfiledesc *fd, print64 size, prfilemapprotect prot); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing the file that is to be mapped to memory. size size of the file specified by fd. prot protection option for read and write accesses of a file mapping. this parameter consists of one of the following options: pr_prot_readonly. read-only access. pr_prot_readwrite. readable, and write is shared. pr_prot_writecopy. readable, and write is private (copy-on-write). returns if successful, a file mapping of type prfilemap. if unsuccessful, null. ...
...the returned file-mapping object must be passed to pr_memmap to actually map a section of the file to memory. ...
PR_Interrupt
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. ...
... 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. ...
...nterrupted thread returns pr_failure (-1) with an error code (see pr_geterror) for blocking operations that return a prstatus (such as i/o operations, monitor waits, or waiting on a condition). to check whether the thread was interrupted, compare the result of pr_geterror with pr_pending_interrupt_error. pr_interrupt may itself fail if the target thread is invalid. bugs pr_interrupt has the following limitations and known bugs: there can be a delay for a thread to be interrupted from a blocking i/o function. in all nspr implementations, the maximum delay is at most five seconds. in the pthreads-based implementation on unix, the maximum delay is 0.1 seconds. file i/o is considered instantaneous, so file i/o functions cannot be interrupted. unfortunately the standard input, output, and e...
PR_Poll
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. ...
...t the caller is interested in. on successful return, the out_flags field of the prpolldesc data structure is set to indicate what kind of i/o is ready on the respective descriptor. pr_poll uses the out_flags fields as scratch variables during the call. if pr_poll returns 0 or -1, the out_flags fields do not contain meaningful values and must not be used. the prpolldesc structure is defined as follows: struct prpolldesc { prfiledesc* fd; print16 in_flags; print16 out_flags; }; typedef struct prpolldesc prpolldesc; the structure has the following fields: fd a pointer to a prfiledesc object representing a socket or a pollable event. this field can be set to null to indicate to pr_poll that this prfiledesc object should be ignored. on unix, the fd field can be set to a pointer to ...
...his prfiledesc object should be ignored. on unix, the fd field can be set to a pointer to any prfiledesc object, including one representing a file or a pipe. cross-platform applications should only set the fd field to a pointer to a prfiledesc object representing a socket or a pollable event because on windows the select function can only be used with sockets. in_flags a bitwise or of the following bit flags: pr_poll_read: fd is readable. pr_poll_write: fd is writable. pr_poll_except: fd has an exception condition. out_flags a bitwise or of the following bit flags: pr_poll_read pr_poll_write pr_poll_except pr_poll_err: fd has an error. pr_poll_nval: fd is bad. note that the pr_poll_err and pr_poll_nval flags are used only in out_flags. the pr_poll_err and pr_poll_n...
PR_ReadDir
do not skip any files. pr_skip_dot. skip the directory entry "." representing the current directory. pr_skip_dot_dot. skip the directory entry ".." representing the parent directory. pr_skip_both. skip both "." and ".." pr_skip_hidden. ...
...do not skip any files. pr_skip_dot. skip the directory entry "." representing the current directory. pr_skip_dot_dot. skip the directory entry ".." representing the parent directory. pr_skip_both. skip both "." and ".." pr_skip_hidden. ...
... whose names begin with a period ("."). returns a pointer to the next entry in the directory. if the end of the directory is reached or an error occurs, null. the reason can be retrieved via pr_geterror. description pr_readdir returns a pointer to a directory entry structure: struct prdirentry { const char *name; }; typedef struct prdirentry prdirentry; the structure has the following field: name name of entry, relative to directory name. the flags parameter is an enum of type prdirflags: typedef enum prdirflags { pr_skip_none = 0x0, pr_skip_dot = 0x1, pr_skip_dot_dot = 0x2, pr_skip_both = 0x3, pr_skip_hidden = 0x4 } prdirflags; the memory associated with the returned prdirentry structure is managed by nspr. the caller must not free the prdiren...
Building NSS
u must first install the windows prerequisites, including mozillabuild. you can also build nss on the windows subsystem for linux, but the resulting binaries aren't usable by other windows applications. get the source nss and nspr use mercurial for source control like other mozilla projects. to check out the latest sources for nss and nspr--which may not be part of a stable release--use the following commands: hg clone https://hg.mozilla.org/projects/nspr hg clone https://hg.mozilla.org/projects/nss to get the source of a specific release, see nss releases. build build nss using our build script: nss/build.sh this builds both nspr and nss. build with make alternatively, there is a make target called "nss_build_all", which produces a similar result. this supports some ...
...lla.org/projects/nspr hg clone https://hg.mozilla.org/projects/nss to get the source of a specific release, see nss releases. build build nss using our build script: nss/build.sh this builds both nspr and nss. build with make alternatively, there is a make target called "nss_build_all", which produces a similar result. this supports some alternative options, but can be a lot slower. make -c nss nss_build_all use_64=1 the make-based build system for nss uses a variety of variables to control the build. below are some of the variables, along with possible values they may be set to. build_opt 0 build a debug (non-optimized) version of nss. this is the default. 1 build an optimized (non-debug) version of nss. use_64 0 build for a 32-bit environm...
...ration nss tests are configured using environment variables. the scripts will attempt to infer values for host and domsuf, but can fail. replace localhost and localdomain with the hostname and domain suffix for your host. you need to be able to connect to $host.$domsuf. if you don't have a domain suffix you can add an entry to /etc/hosts (on windows, c:\windows\system32\drivers\etc\hosts) as follows: 127.0.0.1 localhost.localdomain validate this opening a command shell and typing: ping localhost.localdomain. remove the use_64=1 override if using a 32-bit build. test results running all tests can take a considerable amount of time. test output is stored in tests_results/security/$host.$number/. the file results.html summarizes the results, output.log captures all the test output. oth...
FIPS Mode - an explanation
or software, that device will have all the cryptographic engines in it, and also will stores keys and perhaps certificates inside. the device must have a way for users to authenticate to it (to "login" to it), to prove to it that they are authorized to use the cryptographic engines and keys it contains. it may not do any cryptographic operations that involve the use of cryptographic keys, nor allow any of the keys or certificates it holds to be seen or used, except when a user has successfully authenticated to it. if users authenticate to it with a password, it must ensure that their passwords are strong passwords. it must implement the us government standard algorithms (also specified in other fips documents) such as aes, triple-des, sha-1 and sha-256, that are needed to do whatever job ...
... a password, it must ensure that their passwords are strong passwords. it must implement the us government standard algorithms (also specified in other fips documents) such as aes, triple-des, sha-1 and sha-256, that are needed to do whatever job the application wants it to perform. it must generate or derive cryptographic keys and store them internally. except for "public keys", it must not allow any keys to leave it (to get outside of it) unless they are encrypted ("wrapped") in a special way. this makes it difficult to move keys from one device to another, and consequently, all crypto engines and key storage must be in a single device rather than being split up into several devices. how does this affect firefox users? these requirements have several implications for users. in fips m...
...own as "tls", and not the older ssl 2 or ssl 3.0 protocols, and firefox can only talk to those servers that use fips standard encryption algorithms such as aes or triple-des. servers that can only use non-fips-approved encryption, such as rc4, cannot be used in fips mode. how is fips mode different from normal non-fips mode? in normal non-fips mode, the "master password" is optional and is allowed to be a weak short password. the user is only required to enter his master password to use his own private keys (if he has any) or to access his stored web-site passwords. the user is not required to enter the master password to visit ordinary https servers, nor to view certificates he has previously stored. in non-fips mode, nss is willing and able to use popular non-fips approved cryptogra...
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. ...
...is standardized by the ietf. if an application depends on renegotiation feature, it can be enabled by setting the environment variable nss_ssl_enable_renegotiation to 1. by setting this environmental variable, the fix provided by these patches will have no effect and the application may become vulnerable to the issue. this default setting can also be changed within the application by using the following jss methods: sslserversocket.enablerenegotiation(int mode) sslsocket.enablerenegotiation(int mode) sslsocket.enablerenegotiationdefault(int mode) the mode of renegotiation that the peer must use can be set to the following: sslsocket.ssl_renegotiate_never - never renegotiate at all. (default) sslsocket.ssl_renegotiate_unrestricted - renegotiate without restriction, whether or not the pee...
...a jni library we provide the jss4.jar but expect you to build the jss's matching jni shared library. we provide the jss4.jar in case you do not want to obtain your own jce code signing certificate. jss is a jce provider and therefore the jss4.jar must be signed. ftp://ftp.mozilla.org/pub/mozilla.org/security/jss/releases/jss_4_3_1_rtm. documentation documentation for jss 4.3.1 is available as follows: build instructions for jss 4.3.1 javadoc [online] [zipped] read the instructions on using jss. source may be viewed with a browser (via the mxr tool) at http://mxr.mozilla.org/mozilla/source/security/jss/ the run time behavior of jss can be affected by the nss environment variables. platform information you can check out the source from cvs by cvs co -r jss_4_3_1_rtm jss jss 4.3.1 work...
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. ...
...alert ssl_error_bad_cert_hash_value_alert new tls cipher suites (see http://mxr.mozilla.org/security/sour...sslsocket.java): tls_rsa_with_camellia_128_cbc_sha tls_dhe_dss_with_camellia_128_cbc_sha tls_dhe_rsa_with_camellia_128_cbc_sha tls_rsa_with_camellia_256_cbc_sha tls_dhe_dss_with_camellia_256_cbc_sha tls_dhe_rsa_with_camellia_256_cbc_sha note: the following tls cipher suites are declared but are not yet implemented: tls_dh_dss_with_camellia_128_cbc_sha tls_dh_rsa_with_camellia_128_cbc_sha tls_dh_anon_with_camellia_128_cbc_sha tls_dh_dss_with_camellia_256_cbc_sha tls_dh_rsa_with_camellia_256_cbc_sha tls_dh_anon_with_camellia_256_cbc_sha tls_ecdh_anon_with_null_sha tls_ecdh_anon_with_rc4_128_sha tls_ecdh_anon_w...
...jss is a jni library we provide the jss4.jar but expect you to build the jss's matching jni shared library. we provide the jss4.jar in case you do not want to obtain your own jce code signing certificate. jss is a jce provider and therefore the jss4.jar must be signed. https://archive.mozilla.org/pub/security/jss/releases/jss_4_3_rtm/ documentation documentation for jss 4.3 is available as follows: build instructions for jss 4.3 javadoc [online] [zipped] read the instructions on using jss. source may be viewed with a browser (via the mxr tool) at http://mxr.mozilla.org/mozilla/source/security/jss/ the run time behavior of jss can be affected by the nss environment variables. platform information jss 4.3 works with jdk versions 4 or higher we suggest the latest. jss 4.3 requ...
NSS_3.11.10_release_notes.html
8-12-10 newsgroup: <ahref="news: mozilla.dev.tech.crypto"="" news.mozilla.org="">mozilla.dev.tech.crypto</ahref="news:> contents introduction distribution information bugs fixed documentation compatibility feedback introduction network security services (nss) 3.11.10 is a patch release for nss 3.11. the bug fixes in nss 3.11.10 are described in the "bugs fixed" section below. distribution information the cvs tag for the nss 3.11.10 release is nss_3_11_10_rtm. nss 3.11.10 requires nspr 4.7.1. see the documentation section for the build instructions. nss 3.11.10 source and binary distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_11_10_rtm/src/. ...
...hree subdirectories: include - nss header files lib - nss shared libraries bin - nss tools and test programs you also need to download the nspr 4.7.1 binary distributions to get the nspr 4.7.1 header files and shared libraries, which nss 3.11.10 requires. nspr 4.7.1 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.7.1/. bugs fixed the following bugs have been fixed in nss 3.11.10. bug 291384: certutil -k behavior doesn't match usage bug 374247: modutil -disable command not disabling modules' slots bug 384459: certification path validation fails when authority key identifier extension contains key identifier bug 385946: can't import certificate into cert database in fips mode (certutil). bug 387892: add entrust root ca cert...
...bug 443045: fix pk11_generatekeypair for ecc keys on the 3.11 branch bug 444850: nss misbehaves badly in the presence of a disabled pkcs#11 slot bug 462948: lint warnings for source files that include keythi.h 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.9 include the following: build instructions for nss 3.11.4 and above compatibility nss 3.11.10 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.11.10 shared libraries without recompiling or relinking. furthermore, applications that restrict their use of nss apis to the functions listed in nss public func...
NSS_3.12.1_release_notes.html
nss 3.12.1 release notes 2008-09-05 newsgroup: mozilla.dev.tech.crypto contents introduction distribution information new in nss 3.12.1 bugs fixed documentation compatibility feedback introduction network security services (nss) 3.12.1 is a patch release for nss 3.12. the bug fixes in nss 3.12.1 are described in the "bugs fixed" section below. nss 3.12.1 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1. distribution information the cvs tag for the nss 3.12.1 release is nss_3_12_1_rtm. nss 3.12.1 requires nspr 4.7.1. see the documentation section for the build instructions. nss 3.12.1 source and binary distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/...
...pk11_getallslotsforcert returns all the slots that a given certificate exists on, since it's possible for a cert to exist on more than one pkcs#11 token. levels of standards conformance strictness for cert_nametoasciiinvertible (see certt.h) cert_n2a_readable (maximum human readability) cert_n2a_strict (strict rfc compliance) cert_n2a_invertible (maximum invertibility) bugs fixed the following bugs have been fixed in nss 3.12.1. bug 67890: create self-signed cert with existing key that signed csr bug 129303: nss needs to expose interfaces to deal with multiple token sources of certs. bug 311432: ecc's ecl_use_fp code (for linux x86) fails pairwise consistency test bug 330622: certutil's usage messages incorrectly document certain options bug 330628: coreconf/linux.mk shou...
...hecker returns incorrect error code on request with invalid signing cert bug 449146: remove dead libsec function declarations bug 453227: installation of pem-encoded certificate without trailing newline fails 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 for nss 3.11.4 and above nss shared db compatibility nss 3.12.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.12.1 shared libraries without recompiling or relinking. furthermore, applications that restrict their use of nss apis to the functions listed in n...
NSS_3.12.2_release_notes.html
nss 3.12.2 release notes 2008-10-20 newsgroup: mozilla.dev.tech.crypto contents introduction distribution information new in nss 3.12.2 bugs fixed documentation compatibility feedback introduction network security services (nss) 3.12.2 is a patch release for nss 3.12. the bug fixes in nss 3.12.2 are described in the "bugs fixed" section below. nss 3.12.2 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1. distribution information the cvs tag for the nss 3.12.2 release is nss_3_12_2_rtm. nss 3.12.2 requires nspr 4.7.1. see the documentation section for the build instructions. nss 3.12.2 source and binary distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/securit...
...ibraries, which nss 3.12.2 requires. nspr 4.7.1 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.7.1/. new in nss 3.12.2 new functions in the nss shared library: sec_pkcs12addcertorchainandkey (see p12.h) new pkcs11 errors (see secerr.h) sec_error_pkcs11_general_error sec_error_pkcs11_function_failed sec_error_pkcs11_device_error bugs fixed the following bugs have been fixed in nss 3.12.2. bug 200704: pkcs11: invalid session handle 0 bug 205434: fully implement new libpkix cert verification api from bug 294531 bug 302670: use the installed libz.so where available bug 305693: shlibsign generates pqg for every run bug 311483: exposing includecertchain as a parameter to sec_pkcs12addcertandkey bug 390527: get rid of pkixerrormsg vari...
...leak in cert fetching - aia extension. bug 459248: support intel aes extensions. bug 459359: forwardbuilderstate object is leaked when aia path incorrect bug 459481: nss build problem with gcc 3.4.6 on os/2 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 for nss 3.11.4 and above nss shared db compatibility nss 3.12.2 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.12.2 shared libraries without recompiling or relinking. furthermore, applications that restrict their use of nss apis to the functions listed in n...
NSS 3.12.9 release notes
nss 3.12.9 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1. distribution information the cvs tag for the nss 3.12.9 release is nss_3.12.9_rtm. nss 3.12.9 requires nspr 4.8.7. see the documentation section for the build instructions. ...
.../nss/releases/nss_3.12.9_rtm/src/. you also need to download the nspr 4.8.7 binary distributions to get the nspr 4.8.7 header files and shared libraries, which nss 3.12.9 requires. nspr 4.8.7 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.8.7/. new in nss 3.12.9 removed functions new ssl options new error codes bugs fixed the following bugs have been fixed in nss 3.12.9. bug 609068: implement j-pake in freebl bug 607058: crash [@ nss_cms_decoder_work_data] bug 613394: november/december 2010 batch of nss root ca changes bug 610843: need way to recover softoken in child after fork() bug 617492: add pk11_keygenwithtemplate function to pk11wrap (for firefox sync) bug 610162: sha-512 and sha-384 hashes are incorrect...
... 337433: need cert_findcertbynicknameoremailaddrbyusage bug 592939: expired cas in certdata.txt documentation <for a="" class="new " documentation="" href="/en/index.html#documentation" list="" nss="" of="" pages="" primary="" rel="internal" see="" the="" title="en/index.html#documentation">nss documentation. new and revised documents available since the release of nss 3.11 include the following:</for> build instructions for nss 3.11.4 and above nss shared db compatibility nss 3.12.9 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.12.9 shared libraries without recompiling or relinking. furthermore, applications that restrict their use of nss apis to the functions li...
NSS 3.14.3 release notes
distribution information the cvs tag is nss_3_14_3_rtm. nss 3.14.3 requires nspr 4.9.5 or newer. nss 3.14.3 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_3_rtm/src/ new in nss 3.14.3 new functionality no new major functionality is introduced in this release. this release is a patch release to address cve-2013-1620. ...
...ing a padded, mac-then-encrypted 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...
... bug 840714 - "certutil -a" was not correctly producing ascii output as requested. bug 837799 - nss 3.14.2 broke compilation with older versions of sqlite that lacked the sqlite_fcntl_tempfilename file control. nss 3.14.3 now properly compiles when used with older versions of sqlite. acknowledgements the nss development team would like to thank nadhem alfardan and kenny patterson (royal holloway, university of london) for responsibly disclosing the issue by providing advance copies of their research. in addition, thanks to adam langley (google) for the development of a mitigation for the issues raised in the paper, along with emilia kasper and bodo möller (google) for assisting in the review and improvements to the initial patches. bugs fixed in nss 3.14.3 https://bugzilla.mozilla.
NSS 3.17.3 release notes
introduction network security services (nss) 3.17.3 is a patch release for nss 3.17. the bug fixes in nss 3.17.3 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_17_3_rtm. nss 3.17.3 requires nspr 4.10.7 or newer. nss 3.17.3 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_3_rtm/src/ new in nss 3.17.3 new functionality support for tls_fallback_scsv has been added to the ssltap and tstclnt utilities. ...
...s 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_3_rtm/src/ new in nss 3.17.3 new functionality support for tls_fallback_scsv has been added to the ssltap and tstclnt utilities. notable changes in nss 3.17.3 the quickder decoder now decodes lengths robustly (cve-2014-1569). ...
... fingerprint: 62:7f:8d:78:27:65:63:99:d2:7d:7f:90:44:c9:fe:b3:f3:3e:fa:9a cn = america online root certification authority 1 sha-1 fingerprint: 39:21:c1:15:c1:5d:0e:ca:5c:cb:5b:c4:f0:7d:21:d8:05:0b:56:6a cn = america online root certification authority 2 sha-1 fingerprint: 85:b5:ff:67:9b:0c:79:96:1f:c8:6e:44:22:00:46:13:db:17:92:84 the following ca certificates had the websites and code signing trust bits turned off ou = class 3 public primary certification authority - g2 sha1 fingerprint: 85:37:1c:a6:e5:50:14:3d:ce:28:03:47:1b:de:3a:09:e8:f8:77:0f cn = equifax secure ebusiness ca-1 sha1 fingerprint: da:40:18:8b:91:89:a3:ed:ee:ae:da:97:fe:2f:9d:f5:b7:d1:8a:41 the following ca cert...
NSS 3.19.2.4 release notes
introduction network security services (nss) 3.19.2.4 is a security patch release for nss 3.19.2. the bug fixed in nss 3.19.2.4 have been described in the "security fixes" section below. (current users of nss 3.19.3, nss 3.19.4 or nss 3.20.x are advised to update to nss 3.21.1, nss 3.22.2 or a later release.) distribution information the hg tag is nss_3_19_2_4_rtm. nss 3.19.2.4 requires nspr 4.10.10 or newer. ...
...3_19_2_4_rtm. nss 3.19.2.4 requires nspr 4.10.10 or newer. nss 3.19.2.4 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_4_rtm/src/ new in nss 3.19.2.4 new functionality no new functionality has been introduced in this release. ...
..._2_4_rtm/src/ new in nss 3.19.2.4 new functionality no new functionality has been introduced in this release. security fixes in nss 3.19.2.4 the following security fixes from nss 3.21 have been backported to nss 3.19.2.4: bug 1185033 / cve-2016-1979 - use-after-free during processing of der encoded keys in nss bug 1209546 / cve-2016-1978 - use-after-free in nss during ssl connections in low memory bug 1190248 / cve-2016-1938 - errors in mp_div and mp_exptmod cryptographic functions in nss compatibility nss 3.19.2.4 shared libraries are 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.19.2.4 shared libraries without recompiling or relinking. furthermore, applications that restrict the use of nss...
NSS 3.19.3 release notes
introduction network security services (nss) 3.19.3 is a patch release for nss 3.19. the bug fixes in nss 3.19.3 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_19_3_rtm. nss 3.19.3 requires nspr 4.10.8 or newer. nss 3.19.3 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_3_rtm/src/ new in nss 3.19.3 no new functionality is introduced in this release. this is a patch release to update the list of root ca certificates. ...
...spr 4.10.8 or newer. nss 3.19.3 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_3_rtm/src/ new in nss 3.19.3 no new functionality is introduced in this release. this is a patch release to update the list of root ca certificates. ...
...st services racine sha1 fingerprint: 0c:62:8f:5c:55:70:b1:c9:57:fa:fd:38:3f:b0:3d:7b:7d:d7:b9:c6 cn = tc trustcenter universal ca i sha-1 fingerprint: 6b:2f:34:ad:89:58:be:62:fd:b0:6b:5c:ce:bb:9d:d9:4f:4e:39:f3 cn = tc trustcenter class 2 ca ii sha-1 fingerprint: ae:50:83:ed:7c:f4:5c:bc:8f:61:c6:21:fe:68:5d:79:42:21:15:6e the following ca certificate had the websites trust bit turned off cn = comsign secured ca sha1 fingerprint: f9:cd:0e:2c:da:76:24:c1:8f:bd:f0:f0:ab:b6:45:b8:f7:fe:d5:7a the following ca certificates were added cn = tÜrktrust elektronik sertifika hizmet sağlayıcısı h5 sha1 fingerprint: c4:18:f6:4d:46:d1:df:00:3d:27:30:13:72:43:a9:12:11:c6:75:fb ...
NSS 3.20 release notes
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. 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.
...backward compatibility reasons, the server side implementation of the tls library keeps all dhe ciphersuites disabled by default. they can be enabled with the new socket option ssl_enable_server_dhe and the ssl_optionset or the ssl_optionsetdefault api. the server side implementation of the tls does not support session tickets while using a dhe ciphersuite (see bug 1174677). support for the following ciphersuites has been added: tls_dhe_dss_with_aes_128_gcm_sha256 tls_dhe_dss_with_aes_128_cbc_sha256 tls_dhe_dss_with_aes_256_cbc_sha256 by default, the server side tls implementation will use dhe parameters with a size of 2048 bits when using dhe ciphersuites. nss embeds fixed dhe parameters sized 2048, 3072, 4096, 6144 and 8192 bits, which were copied from version 08 of th...
...default, the server side tls implementation will use dhe parameters with a size of 2048 bits when using dhe ciphersuites. nss embeds fixed dhe parameters sized 2048, 3072, 4096, 6144 and 8192 bits, which were copied from version 08 of the internet-draft "negotiated finite field diffie-hellman ephemeral parameters for tls", appendix a. a new api ssl_dhegroupprefset has been added to nss, which allows a server application to select one or multiple of the embedded dhe parameters as the preferred parameters. the current implementation of nss will always use the first entry in the array that is passed as a parameter to the ssl_dhegroupprefset api. in future versions of the tls implementation, a tls client might show a preference for certain dhe parameters, and the nss tls server side implementat...
NSS 3.21 release notes
nfo_cipher_suite - used with sslpreliminarychannelinfo to indicate that a tls cipher suite has been selected ssl_preinfo_all - used with sslpreliminarychannelinfo to indicate that all preliminary information has been set notable changes in nss 3.21 nss now builds with elliptic curve ciphers enabled by default (bug 1205688) nss now builds with warnings as errors (bug 1182667) the following ca certificates were removed cn = verisign class 4 public primary certification authority - g3 sha1 fingerprint: c8:ec:8c:87:92:69:cb:4b:ab:39:e9:8d:7e:57:67:f3:14:95:73:9d cn = utn-userfirst-network applications sha1 fingerprint: 5d:98:9c:db:15:96:11:36:51:65:64:1b:56:0f:db:ea:2a:c2:3e:f1 cn = tc trustcenter universal ca iii sha1 fin...
...t: ab:48:f3:33:db:04:ab:b9:c0:72:da:5b:0c:c1:d0:57:f0:36:9b:46 cn = utn - datacorp sgc sha-1 fingerprint: 58:11:9f:0e:12:82:87:ea:50:fd:d9:87:45:6f:4f:78:dc:fa:d6:d4 o = tÜrktrust bilgi İletişim ve bilişim güvenliği hizmetleri a.Ş. ...
... İletişim ve bilişim güvenliği hizmetleri a.Ş. ...
NSS 3.23 release notes
s extensions sent in the tls handshake has been reordered to increase compatibility of the extended master secret with servers (bug 1243641) the build time environment variable nss_enable_zlib has been renamed to nss_ssl_enable_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. ...
...4f:a3:29:c2:cc:f0:e2:fa:1b:14:03:05 friendly name: verisign class 3 public pca – g2 sha-256 fingerprint: 83:ce:3c:12:29:68:8a:59:3d:48:5f:81:97:3c:0f:91:95:43:1e:da:37:cc:5e:36:43:0e:79:c7:a8:88:63:8b cn = ca disig sha-256 fingerprint: 92:bf:51:19:ab:ec:ca:d0:b1:33:2d:c4:e1:d0:5f:ba:75:b5:67:90:44:ee:0c:a2:6e:93:1f:74:4f:2f:33:cf the following ca certificates were added cn = szafir root ca2 sha-256 fingerprint: a1:33:9d:33:28:1a:0b:56:e5:57:d3:d3:2b:1c:e7:f9:36:7e:b0:94:bd:5f:a7:2a:7e:50:04:c8:de:d7:ca:fe cn = certum trusted network ca 2 sha-256 fingerprint: b6:76:f2:ed:da:e8:77:5c:d3:6c:b0:f6:3c:d1:d4:60:39:61:f4:9e:62:65:ba:01:3a:2f:03:07:b6:d0:b8:04 the following ca certificate...
...an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user. ...
NSS 3.28.1 release notes
introduction network security services (nss) 3.28.1 is a patch release for nss 3.28. the bug fixes in nss 3.28.1 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_28_1_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. ...
...re 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. ...
...9:b0:2f:69:7e:c7:10:fc:5f:ea:fb:5e:38 cn = root ca generalitat valenciana sha-256 fingerprint: 8c:4e:df:d0:43:48:f3:22:96:9e:7e:29:a4:cd:4d:ca:00:46:55:06:1c:16:e1:b0:76:42:2e:f3:42:ad:63:0e ou = rsa security 2048 v3 sha-256 fingerprint: af:8b:67:62:a1:e5:28:22:81:61:a9:5d:5c:55:9e:e2:66:27:8f:75:d7:9e:83:01:89:a5:03:50:6a:bd:6b:4c the following ca certificates were added ou = ac raiz fnmt-rcm sha-256 fingerprint: eb:c5:57:0c:29:01:8c:4d:67:b1:aa:12:7b:af:12:f7:03:b4:61:1e:bc:17:b7:da:b5:57:38:94:17:9b:93:fa cn = amazon root ca 1 sha-256 fingerprint: 8e:cd:e6:88:4f:3d:87:b1:12:5b:a3:1a:c3:fc:b1:3d:70:16:de:7f:57:cc:90:4f:e1:cb:97:c6:ae:98:19:6e cn = amazon root ca 2 sha-256 f...
NSS 3.28.5 release notes
introduction network security services (nss) 3.28.5 is a patch release for nss 3.28. the bug fixes in nss 3.28.5 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_28_5_rtm. nss 3.28.5 requires nspr 4.13.1 or newer. nss 3.28.5 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_5_rtm/src/ new in nss 3.28.5 no new functionality is introduced in this release. this is a patch release to update the list of root ca certificates. ...
...zilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_28_5_rtm/src/ new in nss 3.28.5 no new functionality is introduced in this release. this is a patch release to update the list of root ca certificates. it backports the changes that were initially released in nss version 3.30.2. ...
...:58:33:cd:43 cn=tÜrktrust elektronik sertifika hizmet sağlayıcısı h6 sha-256 fingerprint: 8d:e7:86:55:e1:be:7f:78:47:80:0b:93:f6:94:d2:1d:36:8c:c0:6e:03:3e:7f:ab:04:bb:5e:b9:9d:a6:b7:00 cn=microsec e-szigno root sha-256 fingerprint: 32:7a:3d:76:1a:ba:de:a0:34:eb:99:84:06:27:5c:b1:a4:77:6e:fd:ae:2f:df:6d:01:68:ea:1c:4f:55:67:d0 the following ca certificates were added: cn = d-trust root ca 3 2013 sha-256 fingerprint: a1:a8:6d:04:12:1e:b8:7f:02:7c:66:f5:33:03:c2:8e:57:39:f9:43:fc:84:b3:8a:d6:af:00:90:35:dd:94:57 trust flags: email cn = tubitak kamu sm ssl kok sertifikasi - surum 1 sha-256 fingerprint: 46:ed:c3:68:90:46:d5:3a:45:3f:b3:10:4a:b8:0d:ca:ec:65:8b:26:60:ea:16:29:dd:7e:86:79:90:64...
NSS 3.30.2 release notes
introduction network security services (nss) 3.30.2 is a patch release for nss 3.30. the bug fixes in nss 3.30.2 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_30_2_rtm. nss 3.30.2 requires nspr 4.14 or newer. nss 3.30.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_30_2_rtm/src/ new in nss 3.30.2 no new functionality is introduced in this release. this is a patch release to update the list of root ca certificates. ...
... nspr 4.14 or newer. nss 3.30.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_30_2_rtm/src/ new in nss 3.30.2 no new functionality is introduced in this release. this is a patch release to update the list of root ca certificates. ...
...:58:33:cd:43 cn=tÜrktrust elektronik sertifika hizmet sağlayıcısı h6 sha-256 fingerprint: 8d:e7:86:55:e1:be:7f:78:47:80:0b:93:f6:94:d2:1d:36:8c:c0:6e:03:3e:7f:ab:04:bb:5e:b9:9d:a6:b7:00 cn=microsec e-szigno root sha-256 fingerprint: 32:7a:3d:76:1a:ba:de:a0:34:eb:99:84:06:27:5c:b1:a4:77:6e:fd:ae:2f:df:6d:01:68:ea:1c:4f:55:67:d0 the following ca certificates were added: cn = d-trust root ca 3 2013 sha-256 fingerprint: a1:a8:6d:04:12:1e:b8:7f:02:7c:66:f5:33:03:c2:8e:57:39:f9:43:fc:84:b3:8a:d6:af:00:90:35:dd:94:57 trust flags: email cn = tubitak kamu sm ssl kok sertifikasi - surum 1 sha-256 fingerprint: 46:ed:c3:68:90:46:d5:3a:45:3f:b3:10:4a:b8:0d:ca:ec:65:8b:26:60:ea:16:29:dd:7e:86:79:90:64...
NSS 3.39 release notes
ss accepted an rsa pkcs#1 v1.5 signature where the digestinfo structure was missing the null parameter. starting with version 3.39, nss requires the encoding to contain the null parameter. the tstclnt and selfserv test utilities no longer accept the -z parameter, as support for tls compression was removed in a previous nss version. the ca certificates list was updated to version 2.26. ...
...on. the ca certificates list was updated to version 2.26. ...
...eafe37d06ca22aba7391c0033d25982952c453647349763a3ab5ad6ccf69 cn = oiste wisekey global root gc ca sha-256 fingerprint: 8560f91c3624daba9570b5fea0dbe36ff11a8323be9486854fb3f34a5571198d the following ca certificate was removed: cn = comsign sha-256 fingerprint: ae4457b40d9eda96677b0d3c92d57b5177abd7ac1037958356d1e094518be5f2 the following ca certificates had the websites trust bit disabled: cn = certplus root ca g1 sha-256 fingerprint: 152a402bfcdf2cd548054d2275b39c7fca3ec0978078b0f0ea76e561a6c7433e cn = certplus root ca g2 sha-256 fingerprint: 6cc05041e6445e74696c4cfbc9f80f543b7eabbb44b4ce6f787c6a9971c42f17 cn = opentrust root ca g1 sha-256 fingerprint: 56c77128d98c18...
NSS 3.41 release notes
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. ...
...nality bug 1252891 - implemented eku handling for ipsec ike. bug 1423043 - enable half-closed states for tls. ...
... sha-256 fingerprint: a6c51e0da5ca0a9309d2e4c0e40c2af9107aae8203857fe198e3e769e343085c cn = certplus root ca g1 sha-256 fingerprint: 152a402bfcdf2cd548054d2275b39c7fca3ec0978078b0f0ea76e561a6c7433e cn = certplus root ca g2 sha-256 fingerprint: 6cc05041e6445e74696c4cfbc9f80f543b7eabbb44b4ce6f787c6...
NSS 3.43 release notes
able 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. ...
...ash_hashtype to type secoidtag in sslexp.h ssl_sendcertificaterequest - allow server to request post-handshake client authentication. to use this both peers need to enable the ssl_enable_post_handshake_auth option. ...
... cn = emsign root ca - c1 sha-256 fingerprint: 125609aa301da0a249b97a8239cb6a34216f44dcac9f3954b14292f2e8c8608f cn = emsign ecc root ca - c3 sha-256 fingerprint: bc4d809b15189d78db3e1d8cf4f9726a795da1643ca5f1358e1ddb0edc0d7eb3 cn = hongkong post root ca 3 sha-256 fingerprint: 5a2fc03f0c83b090bbfa40604b0988446c7636183df9846e17101a447fb8efd6 the following ca certificates were removed: none bugs fixed in nss 3.43 bug 1528669 and bug 1529308 - improve gyp build system handling bug 1529950 and bug 1521174 - improve nss s/mime tests for thunderbird bug 1530134 - if docker isn't installed, try running a local clang-format as a fallback bug 1531267 - enable fips mode automatically if the system fips mode flag is set bug 1528262 - add...
NSS 3.47 release notes
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. ...
...ys bug 1586456 - unnecessary conditional in pki3hack, pk11load and stanpcertdb bug 1576307 - check mechanism param and param length before casting to mechanism-specific structs bug 1577953 - support longer (up to rfc maximum) hkdf outputs bug 1508776 - remove refcounting from sftk_freesession (cve-2019-11756) bug 1494063 - support tls exporter in tstclnt and selfserv bug 1581024 - heap overflow in nss utility "derdump" bug 1582343 - soft token mac verification not constant time bug 1578238 - handle invald tag sizes for ckm_aes_gcm bug 1576295 - check all bounds when encrypting with seed_cbc bug 1580286 - nss rejects tls 1.2 records with large padding with sha384 hmac bug 1577448 - create additional nested s/mime test messages for thunderbird bug 1399095 - allow nss-try to be used ...
...mac verification not constant time bug 1578238 - handle invald tag sizes for ckm_aes_gcm bug 1576295 - check all bounds when encrypting with seed_cbc bug 1580286 - nss rejects tls 1.2 records with large padding with sha384 hmac bug 1577448 - create additional nested s/mime test messages for thunderbird bug 1399095 - allow nss-try to be used to test nspr changes bug 1267894 - libssl should allow selecting the order of cipher suites in clienthello bug 1581507 - fix unportable grep expression in test scripts bug 1234830 - [cid 1242894][cid 1242852] unused values bug 1580126 - fix build failure on aarch64_be while building freebl/gcm bug 1385039 - build nspr tests as part of nss continuous integration bug 1581391 - fix build on openbsd/arm64 after bug #1559012 bug 1581041 - mach-comma...
NSS Config Options
nss config options format the specified ciphers will be allowed by policy, but an application may allow more by policy 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 con...
...d, 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 they appear. future key words (not yet implemented): enable: turn on ciphersuites by default. disable: turn off ciphersuites by default without disallowing them by policy. ...
... policy-lock: turn off the ability for applications to change policy with the call nss_setalgorithmpolicy. ...
NSS Developer Tutorial
nss coding style formatting line length should not exceed 80 characters. indentation level is 4. tabs are used heavily in many nss source files. try to stay consistent when you modify existing code. the proper use of tabs has often been confusing for new nss developers, so in nss/lib/ssl, we're gradually removing the use of tabs. curly braces: both of the following styles are allowed: if (condition) { action1(); } else { action2(); } or: if (condition) { action1(); } else { action2(); } the former style is more common. when modifying existing code, try to stay consistent. in new code, prefer the former style, as it conserves vertical space. when a block of code consists of a single statement, nss doesn’t require curly braces, so both of these examples a...
..., try to stay consistent. in new code, prefer the former style, as it conserves vertical space. when a block of code consists of a single statement, nss doesn’t require curly braces, so both of these examples are fine: 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 lo...
...data buffer is usually represented as: unsigned char *data; unsigned int len; the buffer pointer is unsigned char *, as opposed to void *, so we can perform pointer arithmetic without casting. use char * only if the data is interpreted as text characters. for historical reasons, the buffer length is unsigned int, as opposed to size_t. unfortunately, this can be a source of integer overflow bugs on 64-bit systems. c features nss requires c99. however, not all features from c99 are equally available. variables can be declared, at the point they are first used. the inline keyword can be used. variadic macro arguments are permitted, but their use should be limited to using __va_args__. the exact-width integer types in nspr should be used, in preference to those declared in <st...
nss tech note4
cert); some info is readily available cert->subjectname (char*) cert->issuername (char*) cert->emailaddr (char*) or char *cert_getcertificateemailaddress(certcertificate *cert); cert->keyusage (unsigned int) to break the issuer and subject names into components pass &(cert->issuer) or &(cert->subject) to the following functions char *cert_getcommonname(certname *name); char *cert_getcertemailaddress(certname *name); char *cert_getcountryname(certname *name); char *cert_getlocalityname(certname *name); char *cert_getstatename(certname *name); char *cert_getorgname(certname *name); char *cert_getorgunitname(certname *name); char *cert_getdomaincomponentname(...
...tname *name); char *cert_getlocalityname(certname *name); char *cert_getstatename(certname *name); char *cert_getorgname(certname *name); char *cert_getorgunitname(certname *name); char *cert_getdomaincomponentname(certname *name); char *cert_getcertuid(certname *name); example code to illustrate access to the info is given below. background on cert extensions an extension has the following attributes object id (oid) : a unique oid represents an algorithm, a mechanism, a piece of information, etc. examples: x500 rsa encryption, certificate basic constraints, pkcs#7 digested data, etc. there is a long list of pre-defined oids, and new ones can be added dynamically by an application. the...
... /* free the secitem fields */ secitem_freeitem(&data.version, pr_false); secitem_freeitem(&data.streetaddress, pr_false); ...... secitem_freeitem(&data.maxusers, pr_false); } } some miscellaneous helper functions compare two secitems ...
Notes on TLS - SSL 3.0 Intolerant Servers
ve this problem. technical information the ssl 3.0 and tls (aka ssl 3.1) specs both contain a provision -- the same provision -- for detecting "version rollback attacks". it is designed to permit a server to detect a man-in-the-middle that is altering the ssl client hello (connection) requests as they pass from the client to the server, altering them by changing the protocol version number to a lower version number. this feature was kind of meaningless until tls (ssl 3.1) came along because there 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 th...
...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 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.
...rvers, please contact us using the feedback address at the top of this page. detecting intolerant servers because newer versions of netscape and mozilla have built-in workaround for the problem servers, it is now unlikely that you will experience this problem. but if you're running netscape 6.0/6.01/6.1 pr 1 or mozilla build (prior to 6/11/2001), you should look out for the symptom described below. you may also run this test with versions later than the older versions of netscape 6.x or mozilla -- just in case code changes in netscape 6.1/mozilla 0.9.2 or later may not catch all problem servers. when you find a secure site which simply does not display any page content or drops the connection, check to see if the preference option edit | preferences | privacy and security | ssl | enable...
Overview of NSS
s proven application security architecture if you want to add support for ssl, s/mime, or other internet security standards to your application, you can use network security services (nss) to implement all your security features. nss provides a complete open-source implementation of the crypto libraries used by aol, red hat, google, and other companies in a variety of products, including the following: mozilla products, including firefox, thunderbird, seamonkey, and firefox os. aol instant messenger (aim) open source client applications such as evolution, pidgin, apache openoffice, and libreoffice. server products from red hat: red hat directory server, red hat certificate system, and the mod_nss ssl module for the apache web server. server products from oracle (formerly sun java ent...
...nss makes use of netscape portable runtime (nspr), a platform-neutral open-source api for system functions designed to facilitate cross-platform development. like nss, nspr has been battle-tested in multiple products. for more information, see the nspr project page. interoperability and open standards you can use nss to support a range of security standards in your application, including the following: ssl v3. the secure sockets layer (ssl) protocol allows mutual authentication between a client and server and the establishment of an authenticated and encrypted connection. tls v1.3 (rfc 8446), tls v1.2 (rfc 5246), tls v1.1 (rfc 4346), tls v1 (rfc 2246). the transport layer security (tls) protocol from the ietf that supersedes ssl. pkcs #1. rsa standard that governs implementation of pub...
...ng, diagnostics, certificate and key management, cryptography module management, and other development tasks. nss comes with an extensive and growing set of documentation, including introductory material, api references, man pages for command-line tools, and sample code. nss is available as source and shared (dynamic) libraries. every nss release is backward compatible with previous releases, allowing nss users to upgrade to the new nss shared libraries without recompiling or relinking their applications. open-source licensing and distribution nss is available under the mozilla public license, version 2. the latest source code is available for free worldwide from https://www.mozilla.org and its mirror sites. ...
NSS tools : pk12util
(0x1) certificate: data: version: 3 (0x2) serial number: 13 (0xd) signature algorithm: pkcs #1 sha-1 with rsa encryption issuer: "e=personal-freemail@thawte.com,cn=thawte personal freemail c a,ou=certification services division,o=thawte consulting,l=cape t own,st=western cape,c=za" alternatively, the -r prints the certificates and then exports them into separate der binary files. this allows the certificates to be fed to another application that supports .p12 files. each certificate is written to a sequentially-number file, beginning with file0001.der and continuing through file000n.der, incrementing the number for every certificate: # pk12util -l test.p12 -r enter password for pkcs12 file: key(shrouded): friendly name: thawte freemail member's thawte consulting (pty) ltd. id...
...nss database types nss originally used berkeleydb databases to store security information. the last versions of these legacy databases are: o cert8.db for certificates o key3.db for keys o secmod.db for pkcs #11 module information berkeleydb has performance limitations, though, which prevent it from being easily used by multiple applications simultaneously. nss has some flexibility that allows applications to use their own, independent database engine while keeping a shared database and working around the access issues. still, nss requires more flexibility to provide a truly shared security database. in 2009, nss introduced a new set of databases that are sqlite databases rather than berkleydb. these new databases provide more accessibility and performance: o cert9.db for certi...
...s listing of all of the pkcs #11 modules contained in a new subdirectory in the security databases directory because the sqlite databases are designed to be shared, these are the shared database type. the shared database type is preferred; the legacy format is included for backward compatibility. by default, the tools (certutil, pk12util, modutil) assume that the given security databases follow the more common legacy type. using the sqlite databases must be manually specified by using the sql: prefix with the given security directory. for example: # pk12util -i /tmp/cert-files/users.p12 -d sql:/home/my/sharednssdb to set the shared database type as the default type for the tools, set the nss_default_db_type environment variable to sql: export nss_default_db_type="sql" this line c...
sslkey.html
dle. description nss_init opens the certificate, key, and security module databases that you specify for use with nss. seckeykeydbhandle returns a handle to the key database opened by nss_init. seckey_destroyprivatekey destroys a private key structure. ...
...when you call cert_destroycertificate or seckey_destroyprivatekey, the function decrements the reference count and, if the reference count reaches zero as a result, both frees the memory and sets all the bits to zero. ...
... ...
TLS Cipher Suite Discovery
stablishment algorithm (such as rsa, dh, or ecdh) peer authentication algorithm (such as rsa, dsa, ecdsa) bulk data encryption algorithm (such as rc4, des, aes) and key size digest algorithm for message authentication checking (sha1, sha256) there are numerous available choices for each of those categories, and the number of possible combinations of all those choices is large. tls does not allow all possible combinations of choices from those categories to be used. instead, tls allows only certain well-defined combinations of those choices, known as cipher suites, defined in the ietf rfc standards. each cipher suite is represented by a 16-bit number. the number of well-defined cipher suites grows with time, and no tls implementation offers all known cipher suites at all times. an implem...
...r. libssl offers a public table of well defined cipher suite numbers. the cipher suites are listed in the table in order of preference, from the most preferred cipher suite to the least preferred. the size of this table varies from release to release, and so libssl makes the number of entries in that table publicly available too. the table and the number of entries are declared in "ssl.h", as follows: /* constant table enumerating all implemented ssl 2 and 3 cipher suites. */ ssl_import const pruint16 ssl_implementedciphers[]; /* number of entries in the above table. */ ssl_import const pruint16 ssl_numimplementedciphers; of course, the raw integer numbers of the cipher suites are not likely to be known to most users, so libssl provides a function by which the application can obt...
...entedciphers[]; /* number of entries in the above table. */ ssl_import const pruint16 ssl_numimplementedciphers; of course, the raw integer numbers of the cipher suites are not likely to be known to most users, so libssl provides a function by which the application can obtain a wealth of information about any supported cipher suite, by its number. this function is declared in "ssl.h" as follows: ssl_import secstatus ssl_getciphersuiteinfo( pruint16 ciphersuite, sslciphersuiteinfo *info, pruintn len); the application provides the cipher suite number for which it wants information, the address of a block of memory allocated to receive that information, and the size in bytes of that block of memory. ssl_getciphersuiteinfo fills that caller-supplied memory ...
NSS tools : pk12util
l number: 13 (0xd) signature algorithm: pkcs #1 sha-1 with rsa encryption issuer: "e=personal-freemail@thawte.com,cn=thawte personal freemail c a,ou=certification services division,o=thawte consulting,l=cape t own,st=western cape,c=za" .... alternatively, the -r prints the certificates and then exports them into separate der binary files. this allows the certificates to be fed to another application that supports .p12 files. each certificate is written to a sequentially-number file, beginning with file0001.der and continuing through file000n.der, incrementing the number for every certificate: # pk12util -l test.p12 -r enter password for pkcs12 file: key(shrouded): friendly name: thawte freemail member's thawte consulting (p...
...originally used berkeleydb databases to store security information. the last versions of these legacy databases are: o cert8.db for certificates o key3.db for keys o secmod.db for pkcs #11 module information berkeleydb has performance limitations, though, which prevent it from being easily used by multiple applications simultaneously. nss has some flexibility that allows applications to use their own, independent database engine while keeping a shared database and working around the access issues. still, nss requires more flexibility to provide a truly shared security database. in 2009, nss introduced a new set of databases that are sqlite databases rather than berkleydb. these new databases provide more accessibility and performance: o ...
...f the pkcs #11 modules contained in a new subdirectory in the security databases directory because the sqlite databases are designed to be shared, these are the shared database type. the shared database type is preferred; the legacy format is included for backward compatibility. by default, the tools (certutil, pk12util, modutil) assume that the given security databases follow the more common legacy type. using the sqlite databases must be manually specified by using the sql: prefix with the given security directory. for example: # pk12util -i /tmp/cert-files/users.p12 -d sql:/home/my/sharednssdb to set the shared database type as the default type for the tools, set the nss_default_db_type environment variable to sql: export nss_default_db_type="sql" ...
Installing Pork
ould also work fairly well, but there may be 5 or so files that elsa can't parse. to make pork easy to use, you will want to install mcpp that integrates into gcc. you will probably want a separate gcc for this so you don't have to modify your standard system gcc. you can install gcc in the normal way in a special directory. build and install mcpp mcpp generates macro expansion comments that allow pork's elsa to undo macros, which is necessary in order to get exact position information. to tell mcpp which gcc installation to integrate itself with, place the selected gcc bin dir as the first element of your path: path=/bindir/of/my/gcc:$path if you want to use a gcc that has binaries named something other than "gcc" and "g++", or you use "ccache" for you main gcc installation and want mc...
...on and want mcpp to override a separate installation, you need to pass the options "cc=gccxxx cxx=g++xxx" to "./configure". but don't give absolute paths there: mcpp won't build right. instead, make sure the commands will be found on the path, as above. svn co https://mcpp.svn.sourceforge.net/svnroot/mcpp/trunk mcpp cd mcpp ./configure --enable-replace-cpp make sudo make install note: if you followed the dehydra installation instructions for linux and compiled your own gcc, then you should not need to "sudo" make install. if you run simply "make install" and see file permission errors, mcpp is likely trying to override your main gcc installation. make sure that (1) your "$path" is correct; (2) you passed the correct "cc=..." and "cxx=..." to "./configure". install the pork stack pork is a...
.... install the pork stack pork is a set of tools written at mozilla for refactoring c++. pork's aim is to simply doing c/c++ refactoring through elsa. ...
Tutorial: Embedding Rhino
xt and the current thread and is an essential cleanup action. there should be a call to exit for every call to enter. to make sure that it is called even if an exception is thrown, it is put into the finally block corresponding to the try block starting after context.enter(). expose java apis using java apis no additional code in the embedding needed! the javascript feature calledliveconnect allows javascript programs to interact with java objects: $ java runscript "java.lang.system.out.println(3)" 3.0 undefined implementing interfaces using rhino, javascript objects can implement arbitrary java interfaces. there's no java code to write -- it's part of rhino's liveconnect implementation. for example, we can see how to implement java.lang.runnable in a rhino shell session: js> obj = { ...
...ample adds the ability to print the value of variable x and the result of calling function f. both x and f are expected to be defined by the evaluated script. for example, $ java runscript3 "x = 7" x = 7 f is undefined or not a function. $ java runscript3 "function f(a) { return a; }" x is not defined. ...
... object result = f.call(cx, scope, scope, functionargs); string report = "f('my args') = " + context.tostring(result); system.out.println(report); } javascript host objects defining host objects custom host objects can implement special javascript features like dynamic properties. counter example the counter example is a simple host object. we'll go through it method by method below. it's easy to try out new host object classes in the shell using its built-in defineclass function. we'll see how to add it to runscript later. (note that because the java -jar option preempts the rest of the classpath, we can't use that and access the counter class.) $ java -cp "js.jar;examples" org.mozilla.javascript.tools.shell.main js> defineclass("counter") js> c = new counter(7) [object c...
Shumway
s. the whats and whys of shumway shumway is a renderer for adobe flash built entirely in web standards (javascript, webgl, and others). it is currently available as an extension and as a component in firefox's nightly builds that can be enabled through about:config (you need to find the shumway.disabled preference and set it to false). it is expected to be included in firefox at some point to allow plugin-free compatibility with swf-based games and animations. shumway has certain limitations compared to adobe flash player especially when unavoidable patents (such as those surrounding flash drm) get in the way. some of its current limitations are just temporary, however. there are a few situations where a user may use shumway to view your content: their platform does not support adobe fl...
... by adobe. to emphasize a point: the current behavior is that shumway works on any swf file unless (or until) the adobe flash player plugin is activated. shumway is made with the same constraints as any website. users who disable flash because of security or performance concerns can still see content through shumway because it cannot be forced to behave worse than javascript (and webgl, etc.) allows. users with shumway enabled will still see your flash content, if compatible with shumway, even if flash player is installed but blocked. testing and what to do in case of trouble the first step is to directly test your flash content. the simple method is to install the shumway extension (or run a browser version with shumway included and enabled) and browse to your flash content with adobe fl...
...d as "shockwave flash" under the plugins tab). this will be the experience met by your users who are running that version of shumway. hopefully, this displays your content with acceptable quality. the next step is to use the inspector included as one of shumway's examples. it can be run locally through a web server or you can use the version hosted on mozilla's github. several methods exist to allow inspector access to your swf file. once your flash content is loaded, you can see how shumway manages it in detail. several buttons are available at the bottom of the screen to enable or disable various shumway options. note: if your applet runs at an abnormal speed, try toggling "turbo" at the bottom of the inspector window. you may wish to do this before opening your swf file. limitations o...
Functions
if the engine weren't smart enough to avoid symbol table lookups.) general closures are the base case. when the function object is created, its parent is set to the first object on the scope chain. when a name is evaluated that doesn't refer to a local variable, the interpreter consults the scope chain to find the variable. when with or eval are used, we have to do this for correctness. this is slow, not only because walking the scope chain is a drag, but also because we'd rather avoid actually creating the scope chain at all, if possible. general closures force the interpreter to verify the whole scope chain. so we optimize this when we can. these optimizations depend on being sure that we will never have to walk the scope chain, so with and eval inhibit them all. null closures. if we can p...
...ck into reserved slots of the function object. to evaluate a name, instead of walking the scope chain, we just take the value from the reserved slot. the function object's parent is the global object. flat closures and null closures have been removed: https://bugzilla.mozilla.org/show_bug.cgi?id=730497 https://bugzilla.mozilla.org/show_bug.cgi?id=739808 name lookups in order of speed, fastest to slowest. arg and local instructions. if a name definitely refers to an argument or local variable of the immediately enclosing function, it can be accessed using jsop_{get,set,call}{arg,local} instructions. some of these can even be fused with other operations into combo instructions like jsop_getargprop, jsop_forlocal, and jsop_inclocal. because arguments and locals can't be deleted, this optimi...
...rs to a global for which we have seen a var, const, or function declaration, then we emit a js_defvar instruction in the script prelude and access the global using jsop_{get,set,call}gvar. this is fast if the global either doesn't exist before the script runs (the script creates it) or it's a non-configurable data property (which amounts to the same thing). otherwise the gvar instructions are as slow as name instructions. there are also combo instructions jsop_{inc,dec}gvar and jsop_gvar{inc,dec}. name instructions. in the worst case we emit jsop_{,set,call}name. these are totally general. they can still be optimized via the property cache; in the worst case we walk the scope chain. in some cases, the jit can optimize a jsop_name instruction that refers to a variable in an enclosing...
Garbage collection
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 compartment. (some cells are shared across all compartments in a zone.) an object may not hold a direct pointer to an object in another compartment. instead, it must store a wrapper for the other object. this allows compartments to be used for security checks: objects in the same compartment have the same access requirements, so no checks are needed, but checks may be done when traversing cross-compartment wrappers. the engine may gc a single compartment without gcing the others. the engine can also gc a set of compartments without gcing the rest. cross-compartment wrappers are used as roots for single- an...
...gh during incremental gc, the engine may run out of memory before finishing the incremental gc. if so, the engine must immediately restart a full, non-incremental gc in order to reclaim some memory and continue execution. incremental write barrier the problem that requires a write barrier incremental gc requires a write barrier for correctness. todo decent diagrams the basic problem is as follows (see dictionary for color terms). say object a is black and contains a pointer field. let object b be white. now let the incremental slice stop, so the mutator resumes. if the mutator stores b into a, so that a contains a pointer to b, and deletes all existing pointers to b, then: b is live, because a is black and contains a pointer to b. b will not be marked, because b is only reachable thr...
...r 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 queued for marking if it is on the mark stack and is not black. thus, the gray objects from cs literature are not represented explicitly. see also: gray, below. gray spidermonkey instead uses "gray" to refer to objects that are not black, but are reachable from "gray roots". gray roots are used by the gecko cycle collector to find cycles that pass through the js heap. handle in our gc, a handle is a pointer that has elsewhere been registered by a root. in other words, it is an updatable pointer to a gc thing (it is essentially a cell** that the gc kn...
JSPropertyDescriptor
setter the set syntax binds an object property to a function to be called when there is an attempt to set that property. ...
... declare whether the specified attribute can be rewritten description a descriptor is a property that describes an object's properties. there are two main types of property descriptors that exist in an object: a data descriptor and an access descriptor. you can use the object.getownpropertydescriptor() function to get the corresponding property of an object. descriptor. examples the following example demonstrates how to use the object.defineproperty() function to create a property under an object in a javascript via a descriptor. var language = {}; // define an empty object language object.defineproperty(language, 'log', { // define the log attribute under the language object value : ['cn','en'], writable : true, enumerable : true, configurable : true }) in the...
... var language = {}; // define an empty object language languange.log = ['cn','en']; // define the log attribute under the language object ...
JS_LookupProperty
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. on success, *vp receives the stored value of the property, if any. description the functions js_lookupproperty, js_lookupucproperty, js_looku...
...emory during the search), the return value is false, and the value left in *vp is undefined. there is no way to tell the difference between not finding any property and finding a property whose value is undefined. sorry. use js_getpropertydescriptorbyid instead. js_lookupucproperty is the unicode version of js_lookupproperty. flags js_lookuppropertywithflags and js_lookuppropertywithflagsbyid allow the caller to specify flags requesting special lookup behavior. when executing javascript code that uses properties, spidermonkey looks up properties using slightly different rules depending on the syntactic context in which the property name appears. (the javascript engine simply passes these flags through to the object when it calls the object's jsclass.resolve callback, so objects of a custom ...
...e property name appears. (the javascript engine simply passes these flags through to the object when it calls the object's jsclass.resolve callback, so objects of a custom jsclass may interpret these flags however they like.) if flags is 0, js_lookuppropertywithflags uses the default lookup rules, the ones used by js_lookupproperty. otherwise, flags must be the logical or of one or more of the following bits: jsresolve_qualified behave as though the property name appeared to the right of a dot, as in alert(obj.name). jsresolve_assigning behave as though the property name appeared on the left-hand side of an assignment. jsresolve_detecting behave as though the name appeared in an idiom like "if (obj.name) ..." or "obj.name ? ... : ...". objects may pretend that the pro...
JS_SET_TRACING_DETAILS
arg void * see the description. index size_t see the description. ...
...ion. callback syntax typedef void (*jstracenameprinter)(jstracer *trc, char *buf, size_t bufsize); 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 debugprinti...
...mxr id search for js_set_tracing_details ...
JS_SetGCCallback
jsgc_end, jsgc_mark_end, // obsolete since jsapi 13 jsgc_finalize_end // obsolete since jsapi 13 } jsgcstatus; typedef void (* jsgccallback)(jsruntime *rt, jsgcstatus status, void *data); name type description cx jscontext * the context in which garbage collection is happening. status jsgcstatus one of the jsgcstatus constants, described below, indicating the stage of gc. description js_setgccallback sets a callback function which the garbage collector calls at several points during garbage collection. rt is the runtime in which you specify the callback. cb is a pointer to the new callback function to use. callback related to finalization is separated to js_setfinalizecallback in jsapi 13. obsolete since jsapi 13 js_setgccallb...
...inters that are not traced by the gc). jsgc_finalize_end obsolete since jsapi 13 end of finalization. jsgc_end end of gc. sometimes these four callbacks happen once each, in the order listed. sometimes jsgc_begin happens and the rest of garbage collection does not happen, so the other three callbacks are not called. ...
...ince jsapi 13 end of finalization. jsgc_end end of gc. sometimes these four callbacks happen once each, in the order listed. sometimes jsgc_begin happens 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 tri...
JS_SetNativeStackQuota
syntax void js_setnativestackquota(jsruntime *cx, size_t systemcodestacksize, size_t trustedscriptstacksize = 0, size_t untrustedscriptstacksize = 0); name type description rt jsruntime * the runtime. systemcodestacksize size_t the desired stack quota setting, in bytes. trustedscriptstacksize size_t the desired stack quota setting, in bytes for trusted script. if omitted, it uses the value of systemcodestacksize. ...
...ystemcodestacksize. added in spidermonkey 31 untrustedscriptstacksize size_t the desired stack quota setting, in bytes for untrusted script. if omitted, it uses the value 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. ...
... the stack quotas for each kind of code should be monotonically descending, and may be specified with this function. ...
SpiderMonkey 24
/pub/mozilla.org/js/mozjs-24.2.0.tar.bz2 (sha1: ce779081cc11bd0c871c6f303fc4a0091cf4fe66) spidermonkey 24 is the javascript engine that shipped in firefox 24. it continues to improve performance over previous spidermonkey releases, with a significantly improved garbage collector, a new jit compilation mode, and other features. it also contains new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. — dec 16, 2013 the download url still available, but spidermonkey not release alone! get it here mozilla-esr24 if the download url is outdate you will find it in "firefox extended suppor...
...jit is provided but not supported. on all other platforms the jit is simply disabled; javascript code runs in an interpreter, as in previous versions. it's the same language, just not as fast. migrating to spidermonkey 24 spidermonkey now provides a fully c++ interface, so embedders relying on embeddability in c projects will have to convert to c++, or implement their own adapter code. the following features in earlier versions of spidermonkey have been dropped. e4x, an extension to ecmascript adding xml support, has been removed. the extension eventually became an evolutionary dead end, as tc39 chose not to incorporate it into ecmascript proper. it is recommended that you embed a separate xml parser, or include an xml parsing implementation written in javascript, as an alternative. ...
... the most significant changes. many of the garbage collector changes require type signature changes to jsapi methods: specifically introducing js::rooted, js::handle, and js::mutablehandle types. these types, with the appropriate parametrizations, can roughly be substituted for plain types of gc things (values, string/object pointers, etc.). these and other changes are explained in detail below. new javascript language features javascript 24 includes significant updates to language features, yo. typedef changes the fixed-size integer types introduced in spidermonkey 17 are defined in one of the following ways (xxx update for msvc<10 deprecation): if the environment variable moz_custom_stdint_h is set, that file will be included to provide definitions for these types. the file mu...
SpiderMonkey 31
hese release notes are incomplete. the mozilla javascript team is pleased to announce the release of spidermonkey 31. spidermonkey 31 is the javascript engine that shipped in firefox 31. it continues to improve performance over previous spidermonkey releases, with a significantly improved garbage collector and other features. it also contains new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. the download url is 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...
...plate types that encapsulate access to the provided value/string/object or its location. the js::handle<js::value> and js::mutablehandle<js::value> classes have been specialized to implement the same interface as js::value, for simplicity and to ease migration pain. changes to introduce handles to the jsapi are not individually documented, because of the breadth of the changes involved. the following features in earlier versions of spidermonkey have been dropped. xxx list removed features here spidermonkey 31 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types, functions, and callback signatures have changed, though most functions that have changed still have the same names and implement essentially unchanged functionality. applications ...
...instances are now explicitly const, and several apis have been updated to use const jsclass * and const js::class * pointers. all references to shortid/tinyid have been removed. that includes the apis js_definepropertywithtinyid and js_defineucpropertywithtinyid as well as the jspropertydescriptor structure and the matching jsprop_shortid flag. these and other changes are explained in detail below. new javascript language features javascript 31 includes significant updates to language features, yo. new c++ apis jsapi is now a c++-only api. please note that spidermonkey reserves the js:: namespace for itself (and the js:: namespace for internal use). js_init is a new function which must be used to initialize the js engine before any jsruntimes are created or other jsapi methods are c...
SpiderMonkey 38
ontains known security vulnerabilities. these release notes are incomplete. the mozilla javascript team is pleased to announce the release of spidermonkey 38. spidermonkey 38 is the javascript engine that shipped in firefox 38. it continues to improve performance over previous spidermonkey releases, with xxx blah blah blah. it also contains new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. — sep 17, 2015 the download url is 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 ...
...plate types that encapsulate access to the provided value/string/object or its location. the js::handle<js::value> and js::mutablehandle<js::value> classes have been specialized to implement the same interface as js::value, for simplicity and to ease migration pain. changes to introduce handles to the jsapi are not individually documented, because of the breadth of the changes involved. the following features in earlier versions of spidermonkey have been dropped. xxx list removed features here spidermonkey 38 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types, functions, and callback signatures have changed, though most functions that have changed still have the same names and implement essentially unchanged functionality. applications ...
...ions that have changed still have the same names and implement essentially unchanged functionality. applications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. here is a list of the most significant changes: .... these and other changes are explained in detail below. new javascript language features javascript 38 includes significant updates to language features, yo. new c++ apis jsapi is now a c++-only api. please note that spidermonkey reserves the js:: namespace for itself (and the js:: namespace for internal use). js::clonefunctionobject (bug 1088228) interned_string_to_jsid (bug 1045900) js::construct (bug 1017109) js::createerror (bug 984048)...
Running Automated JavaScript Tests
irectory path. you can run three specific tests by giving the three names. or you can run all but selected tests with the --exclude option. now that the full set of test262 tests is included in the tree, jstests take a long time to complete. for a smoke test or if you are not changing language-level functionality, you may wish to use jstests.py path_to_js_shell --exclude=test262 other options allow you to show the test command lines being run, command output and return codes, run tests named in a given file, exclude tests named in a given file, hide the progress bar, change the timeout, run skipped tests, print output in tinderbox format, run a test in the debugger, or run tests in valgrind. run with the -h option to see all the options. the jstests test suite also includes some tests from...
...s, print output in tinderbox format, run a test in the debugger, or run tests in valgrind. run with the -h option to see all the options. the jstests test suite also includes some tests from web-platform-tests. by default, these are only run when no tests paths are specified; this can be overridden by the --wpt=enabled flag. ...
...) 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 different names. use -h to see all the options. the --jitflags option allows you to test the js executable with different flags. the flags ...
TPS History Lists
an integer value from one of the transition types listed at https://developer.mozilla.org/en/nsinavhistoryservice#constants. date: required. ...
...an integer value from one of the transition types listed at https://developer.mozilla.org/en/nsinavhistoryservice#constants. date: required. ...
...an object with begin and end properties, which should have integer values that express time since the present in hours (see date above) for example: var history_to_delete = [ { uri: "http://www.cnn.com/" }, { begin: -24, end: -1 }, { host: "www.google.com" } ]; history lists and phase actions history lists cannot be modified, they can only be added, deleted, and verified, using the following functions: history.add history.delete history.verify history.verifynot ...
Thread Sanitizer
or earlier, you must use clang 3.3. you can find precompiled binaries for llvm/clang 3.3 on the llvm releases page. we recommend using clang 3.6 or later. building firefox getting the source if you don't have a source code repository clone yet, you need to get yourself a clone of mozilla-central. ...
...2 -gline-tables-only" ac_add_options --disable-debug starting the build process now you start the build process using the regular make -f client.mk command. starting firefox after the build has completed, you can start firefox from the objdir as usual. building only the javascript shell if you want to build only the javascript shell instead of doing a full firefox build, the build script below will probably help you to do so. before using it, you must of course adjust the path name for llvm_root to match your setup. once you have adjusted everything, execute this script in the js/src/ subdirectory and pass a directory name as the first parameter. the build will then be created in a new subdirectory with that name. #! /bin/sh if [ -z $1 ] ; then echo "usage: $0 <dirname>" elif [ -...
...pic -pie" \ ldflags="-fsanitize=thread -fpic -pie" \ ../configure --disable-debug --enable-optimize="-o2 -gline-tables-only" --enable-llvm-hacks --disable-jemalloc make -j 8 fi using llvm symbolizer for faster/better traces by default, tsan traces are symbolized because otherwise, the runtime suppression list wouldn't work. the default way of symbolizing the traces is much slower than using llvm-symbolizer for that purpose: llvm ships with a symbolizer binary that tsan will readily use to immediately output symbolized traces much faster. furthermore, additional debug information is included in traces when llvm-symbolizer is used. to use it, either make sure the llvm-symbolizer binary is in your path or set the environment variable tsan_options="external_symbolizer_path...
XUL Accessibility
element in neighbour of the element search inside the element subtree go up through parents (max level is 5) and search inside theirs subtrees if the element is anonymous then search in whole anonymous subtree, here the attribute anonid is used instead of id attribute accessible properties this section describes common rules how accessibility properties are formed for xul elements. ...
..."it's label for control" control="control" /> <hbox role="grouping" id="control" /> get tooltiptext attribute if the element is anonymous child of the element that is the direct child of toolbaritem element or the element is direct child of toolbaritem element then title attribute of toolbaritem element is used (currently it's used in firefox ui only) if the element has aria role and the role allows to aggregate name from subtree of element then generate name from subtree of the element description the following rules to generate accessible description are applied: check aria-describedby attribute, description is generated from elements pointed by aria-describedby attribute <description id="descr1">label1</description> <description id="descr2">label2</description> <textbox aria-describ...
...el2</description> <textbox aria-describedby="descr1 descr2" /> if neighbour of the element has description element pointing to this element by the control attribute, if the description element is found then use its content. <description value="it's label for control" control="control" /> <hbox role="grouping" id="control" /> get tooltiptext attribute value if the aria role is used and it allows to have accessible value then aria-valuetext or aria-valuenow are used if the element is xlink then value is generated from link location actions if the element is xlink then jump action is exposed if the element has registered click event handler then click action is exposed xul elements notification used to display an informative message. role role_alert <panel noautofocus = "true" /> role_...
Embedded Dialog API
these new windows can be entire new browser windows opened in response to web page script, or dialogs or alerts which may arise from script or merely during normal operation of the browser. ...
...these new windows can be entire new browser windows opened in response to web page script, or dialogs or alerts which may arise from script or merely during normal operation of the browser. ...
...indows opened in response to web page script, or dialogs or alerts which may arise from script or merely during normal operation of the browser. part of gecko's embedding api is callbacks into the embedding application for creating new windows. the complete windowing portion of the api is large and complex, but it need not be entirely implemented. its simplest requirements are that the app must allow gecko to create new browser windows and new simple, empty windows. gecko can use the latter to pose dialogs built from xul. xul dialogs are part of the gecko package; they are the default dialog posing mechanism. many embedding applications will find them entirely sufficient. however while xul dialogs are very configurable, they will not behave and probably not look precisely like dialogs which t...
Mork
Mozilla › Tech › Mork
it can be viewed as a set of rows, collections of name-value pairs, which can be organized into various tables. rows need not be in a table, nor need they be in only one table. values are merely an opaque sequence of bytes, so their actual content is dependent on the mork consumer. ...
... bytes, so their actual content is dependent on the mork consumer. except when parsing values, whitespace ('\b', '\t', '\r', '\n', '\f', ' ', and '\x7f'), line continuations ('\\' followed by a newline), and comments (c++ or c style) can be ignored. in practice, only c++-style comments, and the standard whitespace characters ('\t', ' ', '\r', '\n') appear to be used. ...
...fault 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 tables. however, since the meta-row of a row never appears to be used, i will generally use 'meta-row' to refer to the meta-row of a table, unless otherwise qualified. dictionaries a dictionary establishes a series of aliases.
Using the Places keywords API
keywords represent an alias for the given url in the autocomplete (aka awesomebar) field, with smart replacement of query terms. a keyword can only be associated to a given url, it's not possible to associate the same keyword with multiple urls (doing so will just update the url it's pointing to). each keyword can be associated with post data, in such a case a post action will be executed when the given url is selected from the awesomebar. different keywords can reference the same url, if their post data differ. keywords in firefox are currently created through the add keyword for this search contextual menu option in form text fields. ...
...ing the keywords api the keywords api is a promise-based api available through the placesutils module: components.utils.import("resource://gre/modules/xpcomutils.jsm"); xpcomutils.definelazymodulegetter(this, "placesutils", "resource://gre/modules/placesutils.jsm"); setting a keyword for an url the insert() method accepts a keyword entry object describing the keyword to insert. it has the following properties: keyword: string representing the keyword url: either a url or spec represeting the url to associate to postdata: optional post data string. should be omitted if there's no post data. placesutils.keywords.insert({ keyword: "my_keyword", url: "http://www.example.com/" postdata: "post+data=1&test=2" ...
... }).then(() => { /* success */ }, e => { /* failure */ }); note that setting an already existing keyword to a different url, will silently update the existing keyword to the new url. fetching an entry by keyword the fetch() method acceps a keyword string (or an object having a keywords property) and might resolve to a keyword entry with the following properties: keyword: string representing the keyword url: the url represeted by the keyword postdata: optional post data string. not defined if there's no post data. if no keyword exists, will resolve to null. placesutils.keywords.fetch("my_keyword").then(entry => { /* entry is either null, or a keyword entry */ }, e => { /* failure */}...
The Publicity Stream API
tor.apps object. publicity stream api (navigator.apps.publicity.*) the publicity api is exposed as properties on the navigator.apps.publicity object. publicizeactivity( <activity>, [ { [ onsuccess: <function> ], [ onerror: <function> ] } ]): applications 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 carib...
...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 will be invoked if the publicity fails. possible error codes include: denied - if the user refuses to publicize the activity permissiondenied - if the publicizing site is not allowed to post to the publicity stream networkerror - if the publicity server is unreachable activityparseerror - if the activity contains syntax errors (not proper json) invalidactivity - if the activity contains semantic errors (i.e. missing required properties) finally, the publicizeactivity() function will throw an exception if required arguments are missing, or if unsupported argume...
... tweeted 4 times'). onsuccess will be called with a single argument: a json list of the current user's socially relevant app activity in the fixme: deadlinkactivity streams open specification. onerror is an error callback that will be invoked if the installation fails. possible error codes include: denied - if the user does not log in correctly permissiondenied - if the site is not allowed to access the publicity stream networkerror - if the publicity server is unreachable for_apps is a json list of apps that this store has (each represented as its origin url), so that stream events not relating to applications in a given presentation context can be excluded from the return value. if null or an empty list is passed, events for all apps are returned. since the timestamp ...
XPCOM Stream Guide
Mozilla › Tech › XPCOM › Guide › Streams
faces.nsistringinputstream); var data = "hello world"; instream.setdata(data, data.length); while (instream.available()) { outstream.writefrom(instream, instream.available()); } note this is an inefficient example: the only important part is how to feed the output stream. this is also a synchronous (blocking) operation, so if you're in javascript, consider using netutil.jsm as described below. a note about unicode strings versus nsiinputstream nsiinputstream and nsioutputstream work with 8-bit characters. however, javascript strings contain 16-bit characters. this can mean if you have characters beyond ascii code 255, you risk losing data using nsstringstream, for example. to get an input stream for javascript strings safely, try this. var converter = components.classes["@mozill...
...od gives you the input stream and the number of bytes available. the stream listener must read exactly count bytes before exiting. from the nsirequestobserver interface, the .onstartrequest(request, context) method tells you when the request begins, while the .onstoprequest(request, context) method tells you when the request ends. a request will have one .onstartrequest(request, context) call, followed by at least one .ondataavailable(...) call, followed by one .onstoprequest(request, context) call. the context argument will be something passed from whoever invokes the request to the .onstartrequest(), .ondataavailable(), and .onstoprequest() methods of the listener. as for passing in the stream listener and starting the request: that will vary depending on the use case. seekable streams ...
...istener. as for passing in the stream listener and starting the request: that will vary depending on the use case. seekable streams some streams are "seekable": they let you specify where in the stream you are reading from (instead of requiring it be from the beginning). they can also report their current position in the file. seekable streams implement the nsiseekablestream interface. the following stream types are known to implement nsiseekablestream: nsstorageinputstream nsstringinputstream nsmultiplexinputstream nspipeinputstream nsfileinputstream nsbufferedinputstream nsfileoutputstream nsbufferedoutputstream complex stream types several stream types leverage primitive stream types to do specialized work. these work by taking the input from another stream, and providing ...
Components.utils.cloneInto
o = clonedobject; in this way privileged code, such as an add-on, can share 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, shou...
... returns a reference to the cloned object. ...
...st = document.getelementbyid("test"); test.addeventlistener("click", function() { window.addonscriptobject.greetme(); }, false); cloning objects that contain dom elements by default, if the object you clone contains objects that are reflected from c++, such as dom elements, the cloning operation will fail with an error. ...
Components.utils.importGlobalProperties
his api you can import these objects into such a system scope. this function is not intended for sandboxes but for system-privileged scopes. to import these objects into a sandbox, use the wantglobalproperties option in the sandbox constructor. this function is passed an array of strings. each string is the name of an object to import, and will be defined on the importing scope's global. ...
...b, file, along with the regular services. the reason this works is because js code modules actually have blob and file. cu.import() will return the full global of a code module. knowing that, we can just get a valid blob by importing a known module that has the objects, such as services.jsm const {blob, file, services} = cu.import("resource://gre/modules/services.jsm", {}); reference: stackoverflow :: use blob on firefox add-on hiddendomwindow the hidden domwindow has all of these objects automatically imported. the downside of using hiddendomwindow is that on startup of firefox, the hiddendomwindow objects cannot be accessed until it is fully loaded. therefore readystate must be checked, if it is not complete, then a load listener must be attached. once readystate is complete then the ob...
...annot be accessed until it is fully loaded. therefore readystate must be checked, if it is not complete, then a load listener must be attached. once readystate is complete then the objects can be used. for example this is how to ues the file object. ...
Components.utils
createarrayin() removed in gecko 31 returns an array created in specified compartment. ...
...hich error reporter gets called. evalinsandbox() runs javascript code in a sandbox, usually used to run code with restricted privileges. evalinwindow() removed in gecko 34. evaluate javascript code in a less-privileged javascript context. ...
...see also specialpowers.getcomponents. ...
Observer Notifications
unless otherwise noted you register for the topics using the nsiobserverservice. application startup these are the topics that you can observe on startup, in order of appearance. if your component requires access to the user profile, or any services which require access to the profile (preferences, bookmarks, and so on) then a common pattern is to register with the nsicategorymanager for the app-startup topic which can be done in the component's registration code, and then in that notification register with the observer service for the profile-after-change notification. see receiving startup notifications for more information about how this works. ...
...data is still available at this point. note: the data value for this notification is always 'shutdown-persist'. profile-before-change called just before the profile is lost. note: the data value for this notification is always 'shutdown-persist'. profile-before-change-qm called to shut down the quotamanager; this is separated from profile-before-change to allow everything inside profile-before-change to continue using it. profile-before-change-telemetry called to shut down telemetry, again separated to allow everything before this event to continue using it. xpcom-will-shutdown called just before xpcom-shutdown. observer must not spin event loop. xpcom-shutdown assortment of critical services stop operating. many thin...
... called when the network link status changes. http requests these are the topics that you can observe during a http request (see setting http request headers and creating sandboxed http connections). both are passed an nsihttpchannel as the subject parameter. topic description http-on-modify-request called as a http request is made. the channel is available to allow 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. http-on-examin...
operator+=
« xpcom api reference summary this operator+= is a shortcut for the append family of functions. self_type& operator+=( const self_type& astring ); parameters astring [in] a nsastring to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator+=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. ...
...ng ); parameters astring [in] a nsastring to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator+=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator+=( char_type achar ); parameters achar [in] a character to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. see also append parameters astring [in] a nsastring to append to this string. return values this operator returns a reference back to the object being mo...
...aining. self_type& operator+=( char_type achar ); parameters achar [in] a character to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. see also append parameters astring [in] a nsastring to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. see also append ...
IAccessibleText
[propget] hresult caretoffset( [out] long offset ); parameters offset the returned offset is relative to the text() represented by this object. return value s_false if the caret is not currently active on this object, that is the caret is located on some other object. the returned offset value will be -1. s_ok. characterexten...
... index of selection (0 based). startoffset 0 based offset of first selected character. endoffset 0 based offset of one past the last selected character. return value e_invalidarg if bad [in] passed, [out] values are 0s. s_false if there is nothing to return, [out] values are 0s. s_ok. setcaretoffset() sets the position of the caret. the caret position/offset is that of the character logically following it, for example to the right of it in a left to right language. setting the caret position may or may not alter the current selection(). a change of the selection() is notified to the accessibility event listeners with an ::ia2_event_text_selection_changed event. when the new caret position differs from the old one (which, of course, is the standard case) this is notified to the accessibility ...
...set new ending offset (0 based) - the offset of the character just past the last character of the selection(). return value e_invalidarg if bad [in] passed. s_ok. text() returns the substring between the two given indices. the substring starts with the character at startoffset (inclusive) and up to the character at endoffset (exclusive), if startoffset is less or equal endoffste. if endoffset is lower than startoffset, the result is the same as a call with the two arguments being exchanged. the whole text can be requested by passing the indices zero and ncharacters(). if both indices have the same value, an empty string is returned. [propget] hresult text( [in] long startoffset, [in] long endoffset, [out] bstr text ); parameters startoffset index of the first character to include in ...
IAccessibleValue
this interface gives access to a single numerical value. 1.0 66 introduced gecko 1.9 inherits from: iunknown last changed in gecko 1.9 (firefox 3) the iaccessiblevalue 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 type...
...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. ...
...e(). [propget] hresult minimumvalue( [out] variant minimumvalue ); parameters minimumvalue returns the minimal 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 implementa...
imgIContainer
o 1.9.2 type unsigned short the type of this image (one of the type_* values above). read only. width print32 the width of the container rectangle. in the case of any error, zero is returned, and an exception will be thrown. read only. constants constant value description type_raster 0 enumerated values for the 'type' attribute (below). type_vector 1 flag_none 0x0 flags for imgicontainer operations. meanings: flag_none: lack of flags. flag_sync_decode: forces synchronous/non-progressive decode of all available data before the call returns. it is an error to pass this flag from a call stack that originates in a decoder (that is, from a decoder observer event). flag_decode_no_...
... auserspacetoimagespace the transformation from user space (for example, appunits) to image space. afill the area in the context to draw pixels to. when aflags includes flag_clamp, the image will be extended to this area by clamping image sample coordinates. otherwise, the image will be automatically tiled as necessary. asubimage the area of the image, in pixels, that we are allowed to sample from. aviewportsize the size (in css pixels) of the viewport that would be available for the full image to occupy, if we were drawing the full image. (note that we might not actually be drawing the full image -- we might be restricted by asubimage -- but we still need the full image's viewport-size in order for svg images with the "viewbox" attribute to position their content ...
...ameters none. exceptions thrown missing exception missing description stopanimation() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) void stopanimation(); parameters none. exceptions thrown missing exception missing description unlockimage() decreases the lock count on the image. if the lock count drops to zero, the image is allowed to discard its frame data to save memory. upon instantiation images have a lock count of zero. it is an error to call this method without first having made a matching lockimage() call. in other words, the lock count is not allowed to be negative. void unlockimage(); parameters none. exceptions thrown missing exception missing description remarks --- see also ...
mozIRegistry
to store that information in the "netscape registry" file. which explains how this information came to be associated with the notion of a "registry." someday (i hope) this page will be properly titled so that everybody knows it is the place to come to in order to find out how they are supposed to link together the various xpcom components that together form the mozilla browser. the information below is intended to tell you everything you need to know about how to do that. summary clients will rely on nsrepository to create instances of a given class. clients requiring dynamic "binding" of clsids will be required to use some higher-level services (tbd) to figure out the clsids they should use. the intent is that such services themselves be built on top of the new moziregistry interface. we...
...ject that can provide the interface your component requires? one way is to create instances by using nsrepository. nsrepository is essentially a mapping from xpcom clsids to class factories, plus code to manage that mapping, including functions that create instances of a given clsid. the nsrepository functions are declared in nsrepository.h. much more information about nsrepository can be found below. the second way you access other components is via the service manager. that thing isn't yet covered in this document. see the note above. in this section, i'll discuss a number of different components, their requirements for dynamically binding to other components, and how they might utilize the core xpcom components to satisfy those requirements. i18n xul/xptoolkit app shell clsid binding...
...is envisioned that there will be multiple flavors of underlying rdf data sources corresponding to the libreg .reg file(s), the shared libraries installed, additional components accessible via the 'net, etc. the contents of this rdf data base will be stored in a plain-text rdf/xml file so that it can easily be viewed edited. it will also facilitate building a browser-based application that will allow people to display and edit its contents. original document information author: bill law last updated date: january 21, 1999 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
mozIStorageVacuumParticipant
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) to create an instance of this interface, use the category manger, with the category "vacuum-participant". add more details here. ...
...ase. the vacuum manager will try to correct the page size when the browser is idle, using this value as a target. valid page sizes are in the range 512 to 65,536. the recommended value is mozistorageconnection::default_page_size. note: if the database is using the wal journal node and the current page size is not the expected one, the journal node will be changed to truncate because wal doesn't allow page size changes. the vacuum manager will try to restore wal mode, but this will only work reliably if the participant properly resets statements. if the attempt to restore the journal node fails, it will remain truncate. methods onbeginvacuum() called when a vacuum operation begins. once you receive this notification, you should avoid using the database until onendvacuum() is called. boolea...
..., but this will only work reliably if the participant properly resets statements. if the attempt to restore the journal node fails, it will remain truncate. methods onbeginvacuum() called when a vacuum operation begins. once you receive this notification, you should avoid using the database until onendvacuum() is called. boolean onbeginvacuum(); parameters none. return value return true to allow the vacuum operation to proceed, or false if you don't want the database to be vacuumed. you may wish to return false, for example, if you're in the middle of an operation that you don't want to (or can't) interrupt. onendvacuum() called when a vacuum operation ends. void onendvacuum( in boolean asucceeded ); parameters asucceeded true if the vacuum operation was successful, or false if it wa...
nsIAccessibleStates
accessible/public/nsiaccessiblestates.idlscriptable please add a summary to this article. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) prior to gecko 1.9, these constants were implemented in nsiaccessible. constants state constants msaa state flags - used for bitfield. more than 1 allowed. constant value description state_unavailable 0x00000001 the object is unavailable, that is disabled. state_selected 0x00000002 the object is selected, that is it indicates this 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. st...
.... state_linked 0x00400000 the object is formatted as a hyperlink. the object role will usually be role_text_leaf. (see nsiaccessiblerole.constants). state_traversed 0x00800000 the object is a hyperlink that has been visited (previously clicked) by a user. state_multiselectable 0x01000000 supports multiple selection. state_extselectable 0x02000000 supports extended selection. ...
... is formatted as a hyperlink. the object role will usually be role_text_leaf. (see nsiaccessiblerole.constants). state_traversed 0x00800000 the object is a hyperlink that has been visited (previously clicked) by a user. state_multiselectable 0x01000000 supports multiple selection. state_extselectable 0x02000000 supports extended selection. state_alert_low 0x04000000 this information is of low priority. state_alert_medium 0x08000000 this information is of medium priority. state_alert_high 0x10000000 this information is of high priority. state_protected 0x20000000 maps to gnome's role* atk_role_passwd_text, nothing for java? state_haspopup 0x40000000 new in msaa 2.0. state_required state_alert_low state_important state_alert_medium currently unused. state_invalid state_a...
nsIBinaryInputStream
this might be used, for example, to implement network protocols or to read from architecture-neutral disk files, that is ones that can be read and written by both big-endian and little-endian platforms. ...
...yte array from the stream. void readbytes( in pruint32 alength, [size_is(alength), retval] out string astring ); parameters alength the number of bytes to read. astring a string containing the bytes read from the stream. exceptions thrown ns_error_failure if it can't read alength bytes. readcstring() reads an 8-bit pascal style string from the stream. 32-bit length field, followed by length 8-bit chars. acstring readcstring(); parameters none. return value the string read from the stream. readdouble() reads from the stream. double readdouble(); parameters none. return value a double read from the stream. readfloat() reads from the stream. float readfloat(); parameters none. return value a float read from the stream. readstring() reads an 16-bit pa...
...ters none. return value the string read from the stream. readdouble() reads from the stream. double readdouble(); parameters none. return value a double read from the stream. readfloat() reads from the stream. float readfloat(); parameters none. return value a float read from the stream. readstring() reads an 16-bit pascal style string from the stream. 32-bit length field, followed by length prunichars. astring readstring(); parameters none. return value the string read from the stream. setinputstream() void setinputstream( in nsiinputstream ainputstream ); parameters ainputstream the stream from which to read. see also nsibinaryoutputstream nsiinputstream nsioutputstream ...
nsIBinaryOutputStream
this might be used, for example, to implement network protocols or to produce architecture-neutral binary disk files, that is ones that can be read and written by both big-endian and little-endian platforms. output is written in big-endian order (high-order byte first), as this is traditional network order. ...
...to the stream. void writedouble( in double adouble ); parameters adouble the double to write to the stream. writefloat() writes a floating point number to the stream. void writefloat( in float afloat ); parameters afloat the floating point value to write to the stream. writestringz() writes an 8-bit pascal style string to the stream. the output data consists of a 32-bit length field, followed by that many 8-bit characters. void writestringz( in string astring ); parameters astring the string to write to the stream. writeutf8z() writes an 8-bit pascal style string (utf8-encoded) to the stream. the output data consists of a 32-bit length field, followed by that many 8-bit characters. void writeutf8z( in wstring astring ); parameters astring the string to write to the stream. ...
...e stream. writeutf8z() writes an 8-bit pascal style string (utf8-encoded) to the stream. the output data consists of a 32-bit length field, followed by that many 8-bit characters. void writeutf8z( in wstring astring ); parameters astring the string to write to the stream. writewstringz() writes a 16-bit pascal style string to the stream. the output data consists of a 32-bit length field, followed by that many prunichars. void writewstringz( in wstring astring ); parameters astring the string to write to the stream. see also nsibinaryinputstream nsioutputstream nsiinputstream ...
nsIClipboard
ipboard into a transferable. void getdata( in nsitransferable atransferable, in long awhichclipboard ); parameters atransferable the transferable to receive data from the clipboard. awhichclipboard specifies the clipboard to which this operation applies. hasdatamatchingflavors() this method provides a way to give correct ui feedback about, for instance, whether a paste should be allowed. it does not actually retrieve the data and should be a very inexpensive call. all it does is check if there is data on the clipboard matching any of the flavors in the given list. boolean hasdatamatchingflavors( [array, size_is(alength)] in string aflavorlist, in unsigned long alength, in long awhichclipboard ); parameters aflavorlist an array of ascii strings. alength the lengt...
...ferable on the native 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. ...
... boolean supportsfindclipboard(); parameters none. return value returns true if the separate clipboard for find search strings is supported. otherwise it returns false. ...
nsIContentViewer
olete since gecko 1.8 attributes attribute type description container nsisupports domdocument nsidomdocument enablerendering boolean obsolete since gecko 2.0 historyentry nsishentry get the history entry that this viewer will save itself into when destroyed. can return null. read only. istabmodalpromptallowed boolean read only. prescontext nsprescontextptr read only. native code only! note: prior to gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7), this attribute was part of nsidocumentviewer. presshell nsipresshellptr read only. native code only! note: prior to gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonke...
...ext content viewer replaces this one. note: if the document is currently being printed, it will not be saved in session history. void close( in nsishentry historyentry ); parameters historyentry the session history entry for the content viewer. if this is null, then destroy() will be called on the document by close(). if it is non-null, the document will not be destroyed, and the following actions will happen when destroy() is called: sanitize() will be called on the viewer's document the content viewer will set the contentviewer property on the history entry, and release its reference (ownership reversal). hide() will be called, and no further destruction will happen. destroy() void destroy(); parameters none. findcontainerview() finds the view to use as the ...
...prevent unloading by firing beforeunload on the document, and if it does, prompts the user. the result is returned. boolean permitunload( in boolean acallercloseswindow optional ); parameters acallercloseswindow optional indicates that the current caller will close() the window. if the method returns true, all subsequent calls will be ignored. return value true if the document will allow unloading; otherwise false. requestwindowclose() boolean requestwindowclose(); parameters none. return value missing description exceptions thrown missing exception missing description resetclosewindow() works in tandem with permitunload(), if the caller decides not to close() the window it indicated it will, it is the caller's responsibility to reset that with this method. note: @note...
nsICookiePermission
these may be relocated somewhere else if we ever consider freezing this interface. methods canaccess() tests whether or not the given uri/ch...
...these may be relocated somewhere else if we ever consider freezing this interface. methods canaccess() tests whether or not the given uri/channel may access the cookie data...
...ase, either to set or get cookies. nscookieaccess canaccess( in nsiuri auri, in nsiuri afirsturi, obsolete since gecko 1.9 in nsichannel achannel ); parameters auri the uri trying to access cookies. afirsturi the uri initiated by the user that resulted in auri being loaded. achannel the channel corresponding to auri. return value one of the nscookieaccess values: access_default, access_allow, or access_deny. cansetcookie() tests whether or not the given uri/channel may set a specific cookie. this method is always preceded by a call to canaccess(). it may modify the issession and expiry attributes of the cookie via the aissession and aexpiry parameters, in order to limit or extend the lifetime of the cookie. this is useful, for instance, to downgrade a cookie to session-only if it fai...
getFile
nsifile object corresponding for a given standard path location. the individual platform implementation of nsidirectoryserviceprovider maps the symbolic path location passed to this function and returns the appropriate nsifile. nsifile getfile( in string aname, out boolean apersistent ); parameters aname [in] the symbolic name for a file or directory location. see symbolic names below for a list of accepted values. xpcom file system aliases apersistent [out] this output parameter indicates to the caller whether or not the returned location is persistent. if true, this lets the directory service cache results to improve the performance of directory lookups. if false, then the directory service will not cache the results of this method. symbolic names the list of symb...
... the application's bundle. starting with firefox 35, this is contents/resources. this change was required in order to comply with apple's new gatekeeper v2 rules; without this change, firefox would not work on any mac os x newer than 10.9.4. ns_gre_component_dir "grecomsd" platform-specific locations some symbolic names represent platform-specific locations. the following sections cover these. available on both mac and unix these locations are available on both mac os x and unix implementations of gecko. c constant string value notes ns_os_system_dir "sysd" available on mac os x only these locations are supported only on mac os x versions of gecko. c constant string value notes ns_mac_desktop...
...ir "localappdata" ns_win_printhood "prnthd" ns_win_cookies_dir "cookd" available on unix only these locations are supported only on unix builds of firefox os. c constant string value notes ns_unix_local_dir "locl" ns_unix_lib_dir "libd" ns_unix_home_dir ns_os_home_dir the following locations are provided only on os/2 builds of gecko. deprecated these locations have been deprecated and should no longer be used. c constant string value notes ns_os_drive_dir "drvd" ...
nsIDownloadManager
d) on the nsicancelable provided by the download. void canceldownload( in unsigned long aid ); parameters aid the unique id of the download. exceptions thrown ns_error_failure the download is not in progress. cleanup() removes completed, failed, and canceled downloads from the list. also notifies observers of the "download-manager-remove-download" topic with a null subject to allow any download manager consumers to react to the removals. void cleanup(); parameters none. endbatchupdate() obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) indicate that a batch update is ending. void endbatchupdate(); parameters none. flush() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) ...
...s_error_failure the download is not in progress. removedownload() removes the download with the specified id if it is not currently in progress. whereas canceldownload() simply cancels the transfer while retaining information about it, removedownload() removes all knowledge of it. also notifies observers of the "download-manager-remove-download" topic with the download id as the subject to allow any download manager consumers to react to the removal. void removedownload( in unsigned long aid ); parameters aid the unique id of the download. exceptions thrown ns_error_failure the download is active. removedownloadsbytimeframe() removes all inactive downloads that were started inclusively within the specified time frame. void removedownloadsbytimeframe( in long long abe...
...id resumedownload( in unsigned long aid ); parameters aid the unique id of the download to resume. exceptions thrown ns_error_failure the download is not in progress. retrydownload() retries a failed download. void retrydownload( in unsigned long aid ); parameters aid the unique id of the download. exceptions thrown ns_error_failure if the download is not in the following states: download_canceled or download_failed. ns_error_not_availale if the download id is not known. savestate() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) update the download datasource. void savestate(); parameters none. startbatchupdate() obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2...
nsIHttpChannelInternal
tupfallbackchannel(in string afallbackkey); attributes attribute type description canceled boolean returns true if and only if the channel has been canceled. read only. channelisfordownload boolean external handlers may set this to true to notify the channel that it is open on behalf of a download. documenturi nsiuri an http channel can own a reference to the document uri. forceallowthirdpartycookie boolean force relevant cookies to be sent with this load even if normally they would not be. localaddress autf8string 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...
...t's major version number. minor on return, contains the request's minor version number. getresponseversion() gets the response's major and minor version numbers. void getresponseversion( out unsigned long major, out unsigned long minor ); parameters major on return, contains the response's major version number. minor on return, contains the response's minor version number. ...
...the onstartrequest and onstoprequest events are still delivered and the listener gets full control over the socket if and when nsihttpupgradelistener.ontransportavailable() is delivered. ...
nsIMsgIdentity
sigbottom boolean what should our signature be at the end of the quoted text when replying above it? signature nsilocalfile the file containing the current signature. signaturedate long escapedvcard astring dofcc ...
...efault? attachsignature boolean should we attach a signature by default? attachvcard boolean should we attach a vcard by default? autoquote boolean should we automatically quote the original message? replyontop long should replies appear above or below the quoted message. (1 - replies appear above the quoted message. 0 - replies appear below the quoted message. sigbottom boolean what should our signature be at the end of the quoted text when replying above it? signature nsilocalfile the file containing the current signature. signaturedate long escapedvcard astring dofcc boolean fccfolder astring fccfolderpickermode astring ...
... sigbottom boolean what should our signature be at the end of the quoted text when replying above it? signature nsilocalfile the file containing the current signature. signaturedate long escapedvcard astring dofcc boolean fccfolder astring fccfolderpickermode astring fccreplyfollowsparent boolean draftsfolderpickermode astring tmplfolderpickermode astring bccself boolean note: don't call bccself, bccothers, and bcclist directly, they are only used for migration and backward compatability. use dobcc and dobcclist instead. bccothers boolean bcclist astring dobcc boolean ...
nsINavBookmarkObserver
n print64 folder, in print64 parent, in print32 index ); parameters folder the id of the folder that was removed. parent the id of the folder's old parent. index the folder's old index in its parent. onitemadded() this method notifies this observer that an item was added. it is called after the actual addition took place. when a new item is created, all the items following it in the same folder will have their index shifted down, but no additional notifications will be sent. void onitemadded( in long long aitemid, in long long aparentid, in long aindex, in unsigned short aitemtype, in nsiuri auri, in autf8string atitle, in prtime adateadded, in acstring aguid, in acstring aparentguid ); parameters aitemid the id of the item that was a...
...navbookmarksservice.type constants. aguid the unique id associated with the item. aoldparentguid the unique id associated with the old item's parent. anewparentguid the unique id associated with the new item's parent. onitemremoved() this method notifies that an item was removed. it is called after the actual remove took place. when an item is removed, all the items following it in the same folder will have their index shifted down, but no additional notifications will be sent. void onitemremoved( in long long aitemid, in long long aparentid, in long aindex, in unsigned short aitemtype, in nsiuri auri, in acstring aguid, in acstring aparentguid ); parameters aitemid the id of the item that was removed. aparentid the id of the folder ...
...eters parent the id of the separator's parent. index the separator's old index in its parent. using onbeforeitemremoved() in gecko 1.9.1 if you wish to support onbeforeitemremoved() in applications based on gecko 1.9.1, you must implement your observer's queryinterface() method to match on both nsinavbookmarkobserver and nsinavbookmarkobserver_mozilla_1_9_1_additions, as shown below. queryinterface: function(iid) { if (iid.equals(ci.nsinavbookmarkobserver) || iid.equals(ci.nsinavbookmarkobserver_mozilla_1_9_1_additions) || iid.equals(ci.nsisupports)) { return this; } throw cr.ns_error_no_interface; } see also places manipulating bookmarks using places nsinavbookmarksservice ...
nsINavHistoryObserver
derbird 21.0 / seamonkey 2.18) note: this method was removed in gecko 21.0 as part of bug 826409. the specified page and all its visits are about to be deleted. note: the page does not necessarily have to have ever existed for this function to be called. delete notifications aren't quite 100% accurate. batch delete operations take place in two steps; the notifications come first, followed by a bulk delete. if an error occurs in between these two steps (for example, an out of memory error), then you may get a notification even though the page doesn't wind up getting deleted. note: see using onbeforedeleteuri() in gecko 1.9.1 for how to implement this in gecko 1.9.1 void onbeforedeleteuri( in nsiuri auri, in acstring aguid ); parameters auri the uri of the page abo...
...cessing until onendupdatebatch() is called. void onbeginupdatebatch(); parameters none. onclearhistory() called just prior to all of history being cleared. void onclearhistory(); parameters none. ondeleteuri() the specified page and all its visits has been deleted. delete notifications are not quite 100% accurate. batch delete operations take place in two steps; the notifications come first, followed by a bulk delete. if an error occurs in between these two steps (for example, an out of memory error), then you may get a notification even though the page doesn't wind up getting deleted. note: the page does not necessarily have to have ever existed for this function to be called. notes the removepagesbyhost() and removepagesbytimeframe() functions call beginupdatebatch() and endupdatebatch(...
...exists, the history result creates a new query node dynamically. it is used in places views only and can be ignored. using onbeforedeleteuri() in gecko 1.9.1 if you wish to support onbeforedeleteuri() in applications based on gecko 1.9.1, you must implement your observer's queryinterface() method to match on both nsinavhistoryobserver and nsinavhistoryobserver_mozilla_1_9_1_additions, as shown below. queryinterface: function(iid) { if (iid.equals(ci.nsinavhistoryobserver) || iid.equals(ci.nsinavhistoryobserver_mozilla_1_9_1_additions) || iid.equals(ci.nsisupports)) { return this; } throw cr.ns_error_no_interface; } see also nsinavhistoryresult ...
nsINavHistoryQueryOptions
s is designed for cases where you want to give the user the option of filing something into a list of folders. it only affects cases where the actual folder result node would appear in its parent folder and filters it out. it doesn't affect the query at all, and doesn't affect more complex queries (such as "folders with annotation x"). expandqueries boolean when set, allows items with "place:" uris to appear as containers, with the container's contents filled in from the stored query. if not set, these will appear as normal items. doesn't do anything if excludequeries is set. defaults to false. note that this has no effect on folder links, which are place: uris returned by nsinavbookmarkservice's getfolderuri method. these are always expanded and will appea...
...otation autf8string the annotation to use in sort_by_annotation_* sorting modes. sortingmode short the sorting annotation to use; see sorting methods for possible values. constants sorting methods you can ask for the results to be pre-sorted. since the db has indices of many items, it can produce sorted results almost for free. note: re-sorting is slower, as is sorting by title or when you have a host name. constant value description sort_by_none 0 for bookmark items, this constant means sort by the natural bookmark order. sort_by_title_ascending 1 sort by the ascending title order. sort_by_title_descending 2 sort by the descending tit...
...querytype=1&resulttype=7&folder=tag_folder_id. note: using this result type forces the query type to be query_type_bookmarks. results_as_tag_contents 7 returns nsinavhistoryresultnode nodes for each bookmark contained into the defined tag. to specify the tag you need to add a folder=tag_folder_id to the query, and only one folder is allowed. note: using this result type forces the query type to be query_type_bookmarks. at this time, sorting methods are not supported; results will always be returned in reverse order of insertion. query type constants constant value description query_type_history 0 query's type is history. query...
nsIOutputStream
lls 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. 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 ...
...eam would block the calling thread (non-blocking mode only) writefrom() this method copies data from an nsiinputstream to this nsioutputstream. a nsioutputstream is not required to implement this method. in some contexts, writefrom may be guaranteed to be implemented, but in general it is not. this method serves as an optimization. note: this method is defined by this interface in order to allow the output stream to efficiently copy the data from the input stream into its internal buffer (if any). if this method was provided as an external facility, a separate char* buffer would need to be used in order to call the output stream's other write() method. unsigned long writefrom( in nsiinputstream afromstream, in unsigned long acount ); parameters afromstream an nsiinputstream co...
... 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 is not guaranteed. native code only!writesegments low-level write method that has access to the stream's underlying buffer. the reader function may be called multiple times for segmented buffers. this method is expected to keep calling the reader until either there is nothing left to write or the reader returns an error. this method should not call the reader with zero bytes to provide. note: a nsioutputstream is not required to implement this meth...
nsIParentalControlsService
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) note: currently, this interface is only supported on microsoft windows vista and newer as well as android 4.3 and newer. implemented by: @mozilla.org/parental-controls-service;1. ...
...log entry type represents an access to web content. epclog_filedownload 2 this log entry type represents a file download. methods log() logs an application specific parental controls event. void log( in short aentrytype, in boolean aflag, in nsiuri asource, in nsifile atarget optional ); parameters aentrytype the type of event to log. see the constants for allowed values. aflag pass true if the event was 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 th...
..."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 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 whi...
nsIPermissionManager
); pruint32 testexactpermissionfromprincipal(in nsiprincipal principal, in string type); pruint32 testpermission(in nsiuri uri, in string type); pruint32 testpermissionfromprincipal(in nsiprincipal principal, in string type); attributes attribute type description enumerator nsisimpleenumerator enumerates all stored permissions. allows access to nsipermission objects. read only. constants permission type constants constant value description unknown_action 0 default permission when no entry is found for a host. it should not be used by consumers. allow_action 1 permission is allowed. deny_action 2 permission is denied. prompt_action 3 prompt use...
... permission expiration constants constant value description expire_never 0 permission never expires. ...
...ks if a principal is permitted to perform an action. pruint32 testpermissionfromprincipal( in nsiprincipal principal, in string type ); parameters principal the principal to be tested. type a case-sensitive ascii string, identifying the consumer. return value a pruint32 representing the permission, or unknown_action if no permission exists. remarks this service broadcasts the following notification when the permission list is changed: topic : "perm-changed" (perm_change_notification) broadcast whenever the permission list changes in some way. there are four possible data strings for this notification; one notification will be broadcast for each change, and will involve a single permission. data : "deleted" a permission was deleted. the subject is the deleted nsipermission...
nsIPrincipal
note: prior to gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1), this was not available to scripts. if the ...
...ability short canenablecapability( in string capability ); parameters capability missing description return value missing description exceptions thrown missing exception missing description checkmayload() checks whether this principal is allowed to load the network resource located at the given uri under the same-origin policy. this means that codebase principals are only allowed to load resources from the same domain, the system principal is allowed to load anything, and null principals are not allowed to load anything. note: prior to gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1), this was not available to scripts. if the load is allowed this function does nothing. if the load is not allowed the function throws ns_error_dom_bad_uri. note: other policies mig...
...d the function throws ns_error_dom_bad_uri. note: other policies might override this, such as the access-control specification. note: the 'domain' attribute has no effect on the behaviour of this function. void checkmayload( in nsiuri uri, in boolean report ); parameters uri missing description report if true, will report a warning to the console service if the load is not allowed. exceptions thrown ns_error_dom_bad_uri the load is not permitted. native code only!disablecapability void disablecapability( in string capability, inout voidptr annotation ); parameters capability missing description annotation missing description native code only!enablecapability void enablecapability( in string capability, inout voidptr annotation ); pa...
nsIProxyInfo
r timeout in seconds for this proxy. if a nsiproxyinfo is reported as failed via nsiprotocolproxyservice.getfailoverforproxy(), then the failed proxy will not be used again for this many seconds. read only. flags unsigned long this attribute specifies flags that modify the proxy type. the value of this attribute is the bit-wise combination of the proxy flags defined below. any undefined bits are reserved for future use. read only. host autf8string this attribute specifies the hostname of the proxy server. read only. note: prior to gecko 1.8 host was available by the host method. next nsiproxyinfo proxy info objects may be chained if several proxies could be treated equivalently. this is used ...
...t long this attribute specifies the port number of the proxy server. read only. note: prior to gecko 1.8 port was available by the port method. type acstring this attribute specifies the type of the proxy server as a case insensitive ascii string. some special values for this attribute include (but are not limited to) the following: "http" - http proxy (or ssl connect for https) "socks" - socks v5 proxy "socks4" - socks v4 proxy "direct" - no proxy "unknown" - unknown proxy (see nsiprotocolproxyservice.resolve()) a future version of this interface may define additional types. read only. note: prior to gecko 1.8 type was available by the t...
...or ssl connect for https) "socks" - socks v5 proxy "socks4" - socks v4 proxy "direct" - no proxy "unknown" - unknown proxy (see nsiprotocolproxyservice.resolve()) a future version of this interface may define additional types. read only. note: prior to gecko 1.8 type was available by the type method. constants the following "proxy flags" may be bit-wise combined to construct the flags attribute defined on this interface. all unspecified bits are reserved for future use. constant value description transparent_proxy_resolves_host 1 << 0 this flag is set if the proxy is to perform name resolution itself. if this is the case, the hostname is used in some fashion,...
nsIScriptableIO
the file name is specified as "foo.txt", the file reference generated will refer to a file named "foo.txt" on the user's desktop. note: the filename may only be the name of a file. if you need to select a file in a subdirectory, you should get a reference to the directory, then use the file's append() method to navigate through the directory hierarchy to the file you really want. this properly allows platform-independent path construction. you may specify an empty filename string if you wish to get a reference to the directory itself. nsifile getfile( in astring alocation, in astring afilename ); parameters alocation a location key identifying a known standard directory. the afilename parameter is treated as being local to this directory. afilename the r...
..._error_invalid_arg auri was null. newinputstream() retrieves a stream from which data can be read. nsisupports newinputstream( in nsivariant abase, in astring amode, [optional] in astring acharset, [optional] in astring areplacechar, [optional] in unsigned long abuffersize ); parameters abase the base object from which to read. this should be one of the following types: nsifile: an object returned by getfile() or getfilewithpath(), or any object implementing the nsifile interface. nsitransport: a transport object such as a socket. nsiinputstream: a stream returned by a previous call to this method, or any other object that implements nsiinputstream. string: a string from which to read data. amode a space-delineated string of m...
...tputstream() retrieves a stream to which data can be written. nsisupports newoutputstream( in nsivariant abase, in astring amode, [optional] in astring acharset, [optional] in astring areplacechar, [optional] in unsigned long abuffersize, [optional] in unsigned long apermissions ); parameters abase the base object to which to write. this should be one of the following types: nsifile: an object returned by getfile() or getfilewithpath(), or any object implementing the nsifile interface. nsitransport: a transport object such as a socket. nsioutputstream: a stream returned by a previous call to this method, or any other object that implements nsioutputstream. amode a space-delineated string of mode terms controlling the manner in which ...
nsISecurityCheckedComponent
caps/idl/nsisecuritycheckedcomponent.idlscriptable provides methods that let an xpcom component define custom rules for accessing it from potentially unprivileged code. inherits from: nsisupports last changed in gecko 1.7 capability strings in gecko, a "capability" is a string identifying a set of actions that code is allowed to perform. two examples: code that has the "universalxpconnect" capability is allowed to access all of xpcom. ...
...ecko 1.7 capability strings in gecko, a "capability" is a string identifying a set of actions that code is allowed to perform. two examples: code that has the "universalxpconnect" capability is allowed to access all of xpcom. this includes creating instances of arbitrary xpcom objects and calling methods and setting properties on them. code that has the "universalbrowserread" capability is allowed to perform certain actions that allow it to read information from the local system. for example, this capability allows code to set the value of <input type="file"> and access an arbitrary file on disk. standard web pages have no special capabilities. extensions can define their own capabilities and use this interface to only allow access to code trusted with that capability. the two specia...
... all code has the "allaccess" capability, and no code has the "noaccess" capability. this interface is used in mozilla by xpconnect and a handful of things that need special handing (xul controllers, the ui for the <video> tag, etc.). ...
nsISupportsPriority
xpcom/threads/nsisupportspriority.idlscriptable this interface exposes the general notion of a scheduled object with an integral priority value. following unix conventions, smaller (and possibly negative) values have higher priority. 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) this interface does not strictly define what happens when the priority of an object is changed. an implementation of this interface is free to define the side-effects of changing the priority of an object. in some cases, changing the priority of an object may be disallowed (resulting in an exception being thrown) or may simply be ignored. method overview void adjustpriority(in long delta); attribu...
...the implementation is free to truncate a given priority value to whatever limits are appropriate. typically this attribute is initialized to priority_normal, but implementations may choose to assign a different initial value. constants constant value description priority_highest -20 the highest priority. ...
...on is free to truncate a given priority value to whatever limits are appropriate. typically this attribute is initialized to priority_normal, but implementations may choose to assign a different initial value. constants constant value description priority_highest -20 the highest priority. priority_high -10 higher than normal priority. priority_normal 0 the default priority. priority_low 10 lower than normal priority. priority_lowest 20 the lowest priority. methods adjustpriority() this method adjusts the priority attribute by a given amount (delta). void adjustpriority( in long delta ); parameters delta the amount by which to adjust the priority attribute. see also changing the priority of http requests for an example of using this interface to adjust the priority of ...
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...
...httpchannel), 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 implementation (see "implementing nsistreamlistener" below). after that your nsistreamlistener implementation will get the response data and will be able to pass the data on to the original nsistreamlistener (possibly modifying it). see nsitraceablechannel, intercept http traffic for a more detailed description with code samples. see modify url before loading page in firefox for an overview of how to modify a request before it is made. method overv...
...h a new one, returning the listener previously assigned to the channel. nsistreamlistener setnewlistener( in nsistreamlistener alistener ); parameters alistener an nsistreamlistener to be notified of events on the http channel. return value the previous listener for the channel. each listener call through to the previous listener for every call, in order to establish a call chain to allow all interested parties a chance to act on each event. implementing nsistreamlistener the nsistreamlistener passed to setnewlistener() should implement the following methods, which are called to notify it of events that occur on the http stream: onstartrequest: an http request is beginning. ondataavailable: data is arriving on the http channel. onstoprequest: the http request is ending. n...
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) {...
...iuri clone(); nsiuri cloneignoringref(); boolean equals(in nsiuri other); boolean equalsexceptref(in nsiuri other); autf8string resolve(in autf8string relativepath); boolean schemeis(in string scheme); attributes attribute type description asciihost acstring the uri host with an ascii compatible encoding. follows the idna draft specification for converting internationalized domain names (utf-8) to ascii for compatibility with existing internet infrastructure. read only. note: ipv6 addresses are not enclosed in square brackets. asciispec acstring (us-ascii) the uri spec with an ascii compatible encoding. the host portion follows the idna draft spec. other parts are url-es...
...ase. note: some implementations may have no concept of a relative uri. autf8string resolve( in autf8string relativepath ); parameters relativepath the relative path to resolve. return value the resolved absolute uri string. schemeis() quickly reports whether the nsiuri represents a uri with the specified scheme. this comparison is case-insensitive. note: this is an optimization, allowing you to check the scheme of the uri without having to get the scheme and do the comparison yourself; this saves memory allocations. boolean schemeis( in string scheme ); parameters scheme a string representing the scheme to compare to. return value true if the uri is for the specified scheme; otherwise false. see also code snippets:uri parsing ...
nsIUserCertPicker
security/manager/ssl/public/nsiusercertpicker.idlscriptable please add a summary to this article. ...
... security/manager/ssl/public/nsiusercertpicker.idlscriptable please add a summary to this article. ...
...from: nsisupports last changed in gecko 1.7 method overview nsix509cert pickbyusage(in nsiinterfacerequestor ctx, in wstring selectednickname, in long certusage, in boolean allowinvalid, in boolean allowduplicatenicknames, out boolean canceled); methods pickbyusage() nsix509cert pickbyusage( in nsiinterfacerequestor ctx, in wstring selectednickname, in long certusage, in boolean allowinvalid, in boolean allowduplicatenicknames, out boolean canceled ); parameters ctx selectednickname certusage allowinvalid allowduplicatenicknames canceled return value ...
nsIWebBrowserPersist
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. persist_state_ready 1 persister is ready to save data. persist_state_saving 2 persister is saving data. persist_state_finished 3 persister has finished saving data. encode_flags_selection_only 1 output only the current selection as op...
...e content. this flag may be used to preserve the original formatting as much as possible. encode_flags_body_only 8 output only the body section, no html tags. encode_flags_preformatted 16 wrap even if when not doing formatted output (for example for text fields). encode_flags_wrap 32 wrap documents at the specified column. encode_flags_format_flowed 64 for plain text output. output for format flowed (rfc 2646). this is used when converting to text for mail sending. this differs just slightly but in an important way from normal formatted, and that is that lines are space stuffed. this can't (correctly) be done later. encode_flags_absolute_links 128 convert links to absolute links where possible. encode_flags_en...
... that is that lines are space stuffed. this can't (correctly) be done later. encode_flags_absolute_links 128 convert links to absolute links where possible. encode_flags_encode_w3c_entities 256 attempt to encode entities standardized at w3c (html, mathml, and so on.). this is a catch-all flag for documents with mixed contents. beware of interoperability issues. see below for other flags which might likely do what you want. encode_flags_cr_linebreaks 512 output with carriage return line breaks. may also be combined with encode_flags_lf_linebreaks and if neither is specified, the platform default format is used. encode_flags_lf_linebreaks 1024 output with linefeed line breaks. may also be combined with encode_flags_cr_linebreaks and if...
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...
... if this flag is set, stop() will be called before the load starts and will stop both content and network activity (the default is to only stop network activity). effectively, this passes the stop_content flag to stop(), in addition to the stop_network flag. load_flags_from_external 4096 a hint this load was prompted by an external program: take care! load_flags_allow_third_party_fixup 8192 this flag specifies that the uri may be submitted to a third-party server for correction. this should only be applied to non-sensitive uris entered by users. load_flags_first_load 16384 this flag specifies that this is the first load in this object. set with care, since setting incorrectly can cause us to assume that nothing was actually loaded in this ...
...party server for correction. this should only be applied to non-sensitive uris entered by users. load_flags_first_load 16384 this flag specifies that this is the first load in this object. set with care, since setting incorrectly can cause us to assume that nothing was actually loaded in this object if the load ends up being handled by an external application. load_flags_allow_popups 32768 this flag specifies that the load should not be subject to popup blocking checks. note for valid load flag combinations look here nsdocshellloadtypes.h stop flags constant value description stop_network 1 this flag specifies that all network activity should be stopped. this includes both active network loads and pending meta-refreshes. ...
nsIWindowWatcher
inherits from: nsisupports last changed in gecko 0.9.6 usage notes: this component has an activewindow property. clients may expect this property to be always current, so to properly integrate this component the application will need to keep it current by setting the property as the active window changes. ...
...cation() clients of this service can register themselves to be notified when a window is opened or closed (added to or removed from this service). this method adds an nsiobserver to the list of objects to be notified. void registernotification( in nsiobserver aobserver ); parameters note: be careful about generating open/close window events inside nsiobserver.observe(). ...
...} } var ww = components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getservice(components.interfaces.nsiwindowwatcher); ww.registernotification(new mywindowobserver()) alert("") //generate the first window-open event aobserver the nsiobserver to be notified when windows are opened or closed. aobserver should implement an observe method, which will be called with the following parameters: asubject - the window being opened or closed, sent as an nsisupports which can be nsisupports.queryinterface() (queryinterfaced) to an nsidomwindow. atopic - a wstring, either "domwindowopened" or "domwindowclosed". adata - not used. setwindowcreator() set the window creator callback. it must be filled in by the app. openwindow() will use it to create new windows. v...
nsIZipReader
al file destination used to extract the zip entry. findentries() returns a string enumerator containing the matching entry names. nsiutf8stringenumerator findentries( in autf8string apattern ); parameters apattern a regular expression used to find matching entries in the zip file. set this parameter to null (javascript) or emptycstring() (c++) to get all entries; otherwise, use the following syntax: * matches anything. ? matches one character. $ matches the end of the string. [abc] matches one occurrence of a, b, or c. the only character that must be escaped inside the brackets is ]. ^ and - must never appear in the first and second positions within the brackets, respectively. (in the former case, the behavior specified for '[^az]' will happen.) [a-z] matches any chara...
... c. the only character that must be escaped inside the brackets is ]. ^ and - must never appear in the first and second positions within the brackets, respectively. (in the former case, the behavior specified for '[^az]' will happen.) [a-z] matches any character between a and z. the characters a and z must either both be letters or both be numbers, with the character represented by 'a' having a lower ascii value than the character represented by 'z'. [^az] matches any character except a or z. if ] is to appear inside the brackets as a character to not match, it must be escaped. pat~pat2 returns matches to the pattern 'pat' which do not also match the pattern 'pat2'. this may be used to perform filtering upon the results of one pattern to remove all matches which also match another patte...
...8string zipentry ); parameters zipentry the zip entry. return value boolean value, true if the zip entry exists, false is it does not exist. init() obsolete since gecko 1.9 (firefox 3) initializes a zip reader after construction. void init( in nsifile zipfile ); parameters zipfile zip file to initialize. open() opens a zip file for reading. it is allowed to open with another file, but it needs to be closed first with close(). note: prior to gecko 1.9 you first had to call init()"." void open( in nsifile zipfile ); 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 z...
XPCOM reference
reachable.ns_if_addrefmacrons_if_releasemacrons_releasemacrons_warningmacronsgetmoduleprocthis function prototype provides the xpcom entry-point into a module.nsiabcard/thunderbird3the nsiabcard interface is used to represent and manipulate cards in the address book. in a big change from the original nsiabcard, properties are now stored in a hash table instead of as attributes on the interface, allowing it to be more flexible.nsicookie2 mozilla 1 8 branchnsimsgsearchvaluedefined in comm-central/ mailnews/ base/ search/ public/ nsimsgsearchvalue.idl nsmsgmessageflagsthe nsmsgmessageflags interface describes possible flags for messages. equivalent flags are also defined in nsmsgmessageflags.h. nsmsgnavigationtypethe nsmsgnavigationtype interface contains constants used for message navigatio...
...tants used for views in thunderbird. this interface isn't ever implemented. it is only used to store constants. for example, to request the 'show all threads' view use the constant:nsstaticmoduleinfothis data structure is used by ns_initxpcom3 to specify static xpcom modules.standard xpcom componentsthere are a number of components provided in the standard implementation of xpcom; these are as follows.xpcom glue classesthese "glue" classes are provided to make it easier to use xpcom from c++ code.xpcom interface referencethis is a reference to the xpcom interfaces provided by the mozilla platform.xpcom interface reference by groupingthis page lists the current (as of dec. 01, 2010) list of mozilla interfaces as listed on the xpcom interface reference page where that page lists items by alphab...
...rary decision by the author. (i'm fully aware that this will be a great point of discussion and probably will end in tears, but since i'm the first person to apparently take a swing at this, i get first dibs.)xpcom primitivean xpcom primitive is an xpcom object that "boxes" a value of a primitive type. all xpcom primitives are scriptable, and they all implement an xpcom interface from the table below.xpcom string functionsxpcom provides these low-level string functions to let you work with strings; however, it's often better to use one of the string classes rather than directly using these functions. many xpcom pages return an nsresult. prior to gecko 19 (firefox 19 / thunderbird 19 / seamonkey 2.16), this was an integer that simply returned an error code. it is now a strongly typed enu...
Using nsIPasswordManager
i just had to use the password manager for a project i was working on, so i thought i'd braindump my notes to the wiki while i was at it. this code is tested, but barely, and i am by no means an expert on this area. review and cleanup would be appreciated. zachlipton 22:52, 18 july 2006 (pdt) the code on this page will work with applications using toolkit 1.8 and below such as firefox 2.0.0.x and thunderbird 2.0.0.x. for similar functionality in toolkit 1.9, see using nsiloginmanager. working with password manager extensions often need to securely store passwords to external sites, web applications, and so on. to do so securely, they can use nsipasswordmanager, which provides for secure storage of sensitive password information. getting nsipasswordmanager to get a component impleme...
...lar functionality in toolkit 1.9, see using nsiloginmanager. working with password manager extensions often need to securely store passwords to external sites, web applications, and so on. to do so securely, they can use nsipasswordmanager, which provides for secure storage of sensitive password information. getting nsipasswordmanager to get a component implementing nsipasswordmanager, use the following: var passwordmanager = components.classes["@mozilla.org/passwordmanager;1"] .getservice(components.interfaces.nsipasswordmanager); storing a password to store a password in the password manager, you need three things: a hostname/url (you'll need this to retrieve the password again later), a username, and a password. of this information, the password is the only...
...asy: passwordmanager.adduser('host', 'username', 'password'); since there's no provision to include names of html input fields, no password stored by this interface will be used to fill in passwords on web pages. nsiloginmanager, available in toolkit 1.9, does let you include input field names. retrieving a password retrieving a password from the password manager is more difficult. ...
Working with out parameters
when working with xpcom components, you might come across method declarations like the following one: [scriptable, uuid(8b5314bc-db01-11d2-96ce-0060b0fb9956)] interface nsitransferable : nsisupports { ... void gettransferdata ( in string aflavor, out nsisupports adata, out unsigned long adatalen ) ; ... } the gettransferdata method takes three parameters, aflavor, adata, and adatalen, and returns nothing. adata and adatalen are marked as out, 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 proper...
...ethod 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 when implementing a method which has out parameters in javascript, you have to set a ne...
... .. adata.value = resultdata; adatalen.value = resultdata.length; } ...
XPCOM tasks
ment in general, and specifically the needs of mozilla. like the standard libraries, xpcom must be a fairly self-contained library, so as not to encumber clients with any unnecessary external dependencies. changes to the build hierarchy there are things in xpcom that don't belong there. there is likely to be code outside of xpcom that should be in it. ...
... p1 various threading issues, e.g., too many locks. see bug 13009. not enough locks. ...
...d be moved to netwerk p3 the `twips' units routines (or perhaps all routines) in "nsunitconversion.h" probably belong in layout. p3 nsstringtokenizer probably belongs in the parser. 5.1 3rd party code that doesn't use any services from our tree should be below xpcom; particularly, code xpcom could exploit, e.g., expat berkeley db changes to apis, functionality, and implementations the following items are listed (very) roughly in their order of importance, i.e., fixing observers is the first thing i want to do. p1 various threading issues, e.g., too many locks. see bug 13009. not enough locks. see bug 5795, bug 12755, and bug 12755. p1 we would like to move to a scheme where no one writes queryinterface, and we save code-space with a table driven implementation. a first step is ...
xptcall FAQ
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. why does xptcall exist? xptcall exists for two reasons: to support invoking arbitrary methods on xpcom interfaces. to support dynamically impersonating 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. ...
... 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 information in the typelibs allows xpconnect to convert function parameters and build the nsxptcvariant array required to make this call. the stubs (or impersonation) facility of xptcall allows for implementing a class which can, at runtime, pretend to be any xpcom interface. this is done by providing a vtbl full of generic function stubs in xptcall. these stubs forward calls to a shared function whose job it is to use the typel...
...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 not run properly without a functioning port of xptcall. non-functional stub code exists to allow building xptcall on non-supported platforms. but any browser feature that relies on xpconnect will fail. any platform that does not do xptcall is in trouble. we need to get moving on getting xptcall working everywhere! what platforms are supported? the growing list: porting status where can i find other resources? the code is at: xpcom/reflect/xptcall a new porting guide is at: https://d...
Xptcall Porting Guide
+--test // simple tests to get started \--tests // full tests via api porters are free to create subdirectories under the base md directory for their given platforms and to integrate into the build system as appropriate for their platform. theory of operation there are really two 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 co...
... look like the vtbl of any arbitrary xpcom interface. objects of this class can then be built to impersonate any xpcom object. the base interface for this is (from xptcall/public/xptcall.h): class nsxptcstubbase : public nsisupports { public: // include generated vtbl stub declarations. // these are virtual and *also* implemented by this class.. #include "xptcstubsdecl.inc" // the following methods must be provided by inheritor 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,...
... the number of stubs or to change their specific declaration) using the perl script xptcall/public/genstubs.pl. here are examples of this implementation for win32 and linux x86, netbsd x86, and freebsd. both of these examples use inline assembly language. that is just how i decided to do it. you can do it as you choose. the win32 version is somewhat tighter because the __declspec(naked) feature allows for very small stubs. however, the __stdcall requires the callee to clean up the stack, so it is imperative that the interface information scheme allow the code to determine the correct stack pointer fixup for return without fail, else the process will crash. i opted to use inline assembler for the gcc linux x86 port. i ended up with larger stubs than i would have preferred rather than battle th...
XPIDL Syntax
Mozilla › Tech › XPIDL › Syntax
lify the grammar, i will not mention them in the grammar, especially since they are handled as a preprocessing step before the idl source code is actually parsed. a `%{' that appears at the beginning of a line is the start of a raw code fragment, which extends until the end of a line that begins with `%}'. text inside raw code fragments are not otherwise parsed by xpidl directly. this may be followed by the language, as in `%{c++', to output the raw fragment only in the specified language. a `#include "file"' line instructs the xpidl processor to include that file in the same sense that the c preprocessor includes a file. note that includes within comments or raw code fragments are not processed by xpidl. unlike the c preprocessor, when a file is included multiple times, it acts as if the ...
... literal = octal_literal / decimal_literal / hex_literal / floating_literal literal /= stri...
..."(" *(scoped_name) ",") scoped_name ")" scoped_name = *(ident "::") ident / "::" ident ; in regex: [a-za-z_][a-za-z0-9_]*; identifiers beginning with _ cause warnings ident = (%x41-5a / %x61-7a / "_") *(%x41-5a / %x61-7a / %x30-39 / "_") parens = "(" 1*(any char except ")") ")" functionality not used in xpidl the libidl parser we use is more powerful than xpidl itself can understand. ...
Mozilla technologies
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 allow developers to treat xml as data i.e. not as just another document format. the module is structured as a drop-in component and exposes its xml-as-data features both to javascript and c++/xpcom users. the xml extras module is built by default on all platforms, and is included in the browser installers so it is available in the nightly builds.xpcomxpcom is a cross platform component object model, si...
...ument format. the module is structured as a drop-in component and exposes its xml-as-data features both to javascript and c++/xpcom users. the xml extras module is built by default on all platforms, and is included in the browser installers so it is available in the nightly builds.xpcomxpcom is a cross platform component object model, similar to microsoft com. ...
...for example, the mozilla xforms project uses xtf to add support for the xforms namespace. ...
Creating a gloda message query
or constraint it would match a red square, a green square, or a blue square. query.involves(identity1, identity2, ...): add the constraint that the message must "involve" one of the identities provided. an identity is involved if the message was to them, from them, or carbon-copied to them. gloda.from, gloda.to, gloda.cc: just like gloda.involves, but specific to from/to/cc. gloda.daterange([lowerdate1, upperdate1], [lowerdate2, upperdate2], ...): add the constraint that the message date (per the message's date header) must fall within one of the specified inclusive ranges. the date instances are javascript date instances. query.folder(folder1, folder2, ...): add the constraint that the message must be found in one of the specified folders. the folder may be a glodafolder instance (retr...
...uery.bodymatches(searchstring): perform a full-text search against plaintext message bodies. query.attachmenttypes(mimetype1, mimetype2, ...): constrain to messages with attachments among the given mime types. in theory, providing no arguments should result in finding messages with any attachment, but this is somewhat untested. more constraints can be found in the three js files given further below. from https://developer.mozilla.org/docs/mozilla/thunderbird/thunderbird_extensions/demo_addon, demo3, it seems that the attributename given in these files is the constraintname to be used (e.g. query.subjectmatches(searchstring) for message subject (compare fundattr.js line 145 ). create a collection from the query your listener is notified as messages are added to the collection as the da...
...sage is found in, as represented by a glodafolder instance. conversation: the conversation the message belongs to, as represented by a glodaconversation instance. somewhat magic attributes: headermessageid: the contents of the message-id header of the message. you probably should not be using this. foldermessage: return the nsimsgdbhdr that corresponds to the message. an nsimsgdbhdr is the low-level, old-school, thunderbird xpcom representation of a message. you should not need to use this unless you are dealing with other old-school code or you need to manipulate the state of a message. in the future, the steel layer should provide wrappers to make manipulation clean and fun. note that this message may return "null" if gloda is unable to locate the underlying message anymore. attrib...
LDAP Support
ow appears listing possible matches against address books and ldap directories. for large companies, there may be a large number of users in the directory with the same name. in such a scenario, it may be hard to tell which person you really want to send the message to. in thunderbird, the type down window can be customized to show arbitrary ldap fields. this can be accomplished by setting the following preferences: user_pref("mail.autocomplete.commentcolumn", 2); user_pref("ldap_2.servers.directoryname.autocomplete.commentformat", "[ou]"); the first preference tells us to use a comment column in the type down (the default value is 0 for no comment), and that the value for the comment is a custom string unique to each directory. the commentformat preference is set on each directory. it...
...ence tells us to use a comment column in the type down (the default value is 0 for no comment), and that the value for the comment is a custom string unique to each directory. the commentformat preference is set on each directory. it acts as a template, specifying the extra ldap attribute which should be used in the comment field along with how the attribute should be formatted. ...
...some notes about the relationship: there is a many to one relationship between ldap attributes and its address book counterpart. there is a one to one relationship between a address book attribute and its ldap counterpart. ...
Adding items to the Folder Pane
er pane consults the map-generator for the current mode, and that generator returns the necessary data for the folder pane's display. this data is returned in the form of an array of folder-tree-items. listening for folder pane rebuilds every time the folder pane rebuilds, it fires a "maprebuild" event, which is the ideal opportunity for extensions to step in and modify the display data. ...
...build", gnumbersext._insert, false); }, _insert: function gne__insert() { // this function is called when a rebuild occurs } }; window.addeventlistener("load", gnumbersext.load, true); the structure of folder-tree-items the folder pane stores its current display data in a property called _rowmap. this property is an array 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 getrowpr...
...css attributes here }, command: function gne_command() { // just going to alert, to do something here components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getservice(components.interfaces.nsipromptservice) .alert(window, null, this.text); } }; second, our child items (the numbers 1, 2, and 3) are copies of the following prototype: function numberrow(anumber) { this._number = anumber; } numberrow.prototype = { get id() { return "numbers-child-row-" + this._number; }, get text() { return this._number; }, level: 1, open: false, children: [], getproperties: function gne_kid_getprops() {}, // no-op command: function gne_kid_command() { // just go...
Building a Thunderbird extension 3: install manifest
warning: this content is for older versions of thunderbird. much of it may no longer be relevant. see developer.thunderbird.net for newer information. the install.rdf file is an xml file that provides general information about the extension. ...
...while this value is in email address format, it is no...
...while this value is in email address format, it is not an email address. ...
Building a Thunderbird extension 5: XUL
a xul document at run time. a xul overlay is a .xul file that specifies xul fragments to insert at specific merge points within a "master" document. these fragments can specify widgets to be inserted, removed or modified. in this example you are adding a line to the indented statusbar. therefore it becomes an item owned by the id called "status-bar". ...
...le you are adding a line to the indented statusbar. therefore it becomes an item owned by the id called "status-bar". this shows how the thunderbird architecture allows extensions to modify the user experience without modifying the installation files. this also enables version independence between thunderbird and thunderbird extensions. ...
...es an item owned by the id called "status-bar". this shows how the thunderbird architecture allows extensions to modify the user experience without modifying the installation files. this also enables version independence between thunderbird and thunderbird extensions. ...
Creating a Custom Column
one of the new and exciting features available to thunderbird extension developers in thunderbird 2.0 is the ability to easily create and handle custom columns in thunderbird's main view. the following step through will get you well on the road to creating your own columns and populating them with custom data. getting started in this example we will be developing a small extension that will be adding a column that will display the "reply-to:" field of an email (if it exists, it if often not set). ...
...ll be developing a small extension that will be adding a column that will display the "reply-to:" field of an email (if it exists, it if often not set). if you are unfamiliar with the setup and creation of an extension please read building a thunderbird extension. adding a column by far the easiest part is the physical addition of the column. for this we overlay messenger.xul, by placing the following line in our chrome.manifest file: overlay chrome://messenger/content/messenger.xul chrome://replyto_col/content/replyto_col_overlay.xul now that our overlay is set up we need to connect a column to the current columns that exist. looking in messenger.xul reveals that the columns reside inside a tree with the id "threadtree" whose columns (treecols) reside in "threadcols". to attach our colum...
...d to implement the nsimsgcustomcolumnhandler interface which defines the basic set of functionality that must be implemented to handle a column. note that an object that implements this interface can also take control of an existing, built-in column, but more about that later. nsimsgcustomcolumnhandler extends (inherits from) nsitreeview and as such needs to implement functions from both. the following is a list of functions that must be implemented to ensure that your extension works well with thunderbird. rest assured that these functions will be called - so implement them, even with empty function. from nsitreeview: getcellproperties(row, col, props): optionally modify the props array getrowproperties(row, props): optionally modify the props array getimagesrc(row, col): return a str...
libmime content type handlers
ent type handler plugins for libmime. libmime has a homegrown object system written in c, and since the content type handler plugins need to exist in this module, a description of the libmime object system should be reviewed and understood. api's content type handler plugins are dynamically loaded and need to access internal pointers, functions that are part of the c based object system. the following xp-com interface is implemented by libmime and is necessary for content type handler plugin development. /* * this interface is implemented by content type handlers that will be * called upon by libmime to process various attachments types. the primary * purpose of these handlers will be to represent the attached data in a * viewable html format that is useful for the user * * not...
...pe handler plugin development. /* * this interface is implemented by content type handlers that will be * called upon by libmime to process various attachments types. ...
... = 0; }; #endif /* nsimimecontenttypehandler_h_ */ plugin installation/location the installation of these modules will be similar to the that of any xpcom component (i.e. the components directory for the bin directory). sample content type handler plugin to see an example of a content type handler plugin, the source for the handler of the content type "text/calendar" can be viewed at the following link: calendar plugin note: this plugin simply creates a blue table in the output stream to identify the fact that it is operational, but the basic constructs of what is needed to build a functional content type handler can be seen. the uuid for this component is: // {20dabda1-f8b5-11d2-8ee0-00a024a7d144} #define ns_vcard_content_type_handler_cid \ { 0x20dabda1, 0xf8b5, 0x11d2, \ ...
Using COM from js-ctypes
nd reference for this article bugzilla :: bug 738501 - implement ability to create windows shortcuts from javascript - comment 4 relavent topic bugzilla :: bug 505907 - support c++ calling from jsctypes converting com code to c code to convert com code to js-ctypes, we need to write c++ vtable pointers in c. after that, we can pass a pointer . speech synthesis example let's start with following c++ code, which invokes microsoft speech api and says "hello, firefox!" with system default voice, then wait until the speaking done. #include <sapi.h> int main(void) { if (succeeded(coinitialize(null))) { ispvoice* pvoice = null; hresult hr = cocreateinstance(clsid_spvoice, null, clsctx_all, iid_ispvoice, (void**)&pvoice); ...
... $ cl ole32.lib test.cpp vtable needs vtable description here. the order of the vtable is very critical. when used from c or js-ctypes, the order of the vtable methods should match the order of the c++ vtable. __stdcall and __cdecl needs __stdcall and __cdecl (callback_abi) description here. call by reference needs c++ reference (&) a...
... $ cl ole32.lib test.c c code with pseudo struct needs pseudo struct description here. #include <sapi.h> struct myispvoicevtbl; struct myispvoice { struct myispvoicevtbl* lpvtbl; }; struct myispvoicevtbl { /* start inherit from iunknown */ void* queryinterface; void* addref; ulong (__stdcall *release)(struct myispvoice*); /* end inherit ...
ctypes
on 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 specified cdata object to a new type, returning a new cdata object representing the value in the new type. see type casting for details. cdata ca...
...char}, {'breserved6': ctypes.unsigned_char}, {'dwdata': ctypes.uintptr_t}, {'istring': ctypes.intptr_t} ]); } else { throw new error("wut?!"); } console.log(struct_tbbutton.size); // 20 on 32-bit, 32 on 64-bit if i'm not mistaken there is another way to do this, we can use arraytype, but example for this i don't know at this time. ...
..."user32"); var funcptr = getprocaddress(huser, "messageboxw"); // now we have a pointer to a function, let's cast it to the right type var messageboxtype = ctypes.functiontype(ctypes.winapi_abi, ctypes.int32_t, [hwnd, lpctstr, lpctstr, ctypes.uint32_t]); funcptr = ctypes.cast(funcptr, messageboxtype.ptr); funcptr(0, "test1", "test2", 0); credit for this example is to wladimir palant (stackoverflow :: how to call a function using pointer in js-ctypes) ...
js-ctypes
note: js-ctypes is only available from chrome code; that is, ctypes is not available to websites, only application and extension code. ...
... to call back and forth to native code written in c. c++ support is possible through vtable pointers see using com from js-ctypes. for a discussion on extended c++ support see bug 505907. other work made possible by js-ctypes is jni, this is elaborated on in the jni.jsm section and not the js-ctypes section due to the jsm abstracting away all of the js-ctypes. unlike binary xpcom components, it allows developers to ship a single binary for use with multiple versions of firefox. note: js-ctypes is only available from chrome code; that is, ctypes is not available to websites, only application and extension code. documentation if you are brand new to js-ctypes, and have no idea about it, the pages you should read first is - ctypes.open followed by standard os libraries. ...
... on mac os x to implement an "add image to iphoto" feature in firefox. ...
Flash Activation: Browser Comparison - Plugins
uture of flash and changes to the user experience. the firefox flash roadmap includes links to roadmaps and posts from other vendors. ui comparison mozilla firefox in-page ui is displayed when the site attempts to use flash. an icon also appears on the left side of the location bar. the user can click on the flash object or the location bar icon to activate flash: users have the choice to allow flash just for the current session, or to remember their choice: google chrome in-page ui is displayed when the site attempts to use flash without fallback content: a user can click the plugin element to show a prompt for allowing flash: if the site provides fallback content for an object element, chrome will display that content and will not prompt the user to enable flash. if a flash ...
...n element to show a prompt for allowing flash: if the site provides fallback content for an object element, chrome will display that content and will not prompt the user to enable flash. if a flash element is not visible to the user, the user will not get a visible prompt. a user can click the information icon on the left side of the location bar on any site to open the site information and allow flash on that site: microsoft edge in-page ui is displayed when the site attempts to use flash. an icon also appears on the right side of the location bar. ...
... a visible prompt. a user can click the information icon on the left side of the location bar on any site to open the site information and allow flash on that site: microsoft edge in-page ui is displayed when the site attempts to use flash. an icon also appears on the right side of the location bar. the user can click the flash object to show activation options: users have the choice to allow flash just for the current session, or to remember their choice: site authoring tips if a flash element is very small, hidden, or covered by other content, users will probably not notice that flash is required and will become confused. even if the plugin element will eventually be hidden, pages should create the plugin element so that it's visible on the page, and should resize or hide it onl...
Initialization and Destruction - Plugins
u can allocate instance-specific private data at this time. nperror npp_new(npmimetype plugintype, npp instance, uint16 mode, int16 argc, char *argn[], char *argv[], npsaveddata *saved); the plugintype parameter represents the mime type of this instance of the plug-in. you can assign more than one mime type to a plug-in, which could potentially allow the plug-in to respond to data streams of different types with different interfaces and behavior. the instance parameter represents an npp object, created by the browser. you can store the instance-specific private data in its pdata field (instance->pdata). the mode parameter identifies the display mode in which the plug-in was invoked, either np_embed or np_full. np_embed means that the ins...
...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 page author can use the arg parameters to specify private attributes defined for a particular plug-in. ...
...the data is saved in the history list. as long as the plug-in still appears in this list, that saved data is associated with the page; any new instances receive this data. ...
DOM Inspector FAQ - Firefox Developer Tools
this causes the document to be loaded in the browser pane. ...
...this causes the document to be loaded in the browser pane. ...
...names are exactly "tab". or, if you do not know anything about the node, you can try to select it by clicking on it. scroll the node into view, choose the select-by-click toolbar button, and then click on the element you wish to inspect. the edit menu also includes a select element by click menu item. how do i inspect pseudo-classes and pseudo-elements in the css rules viewer? dom inspector allows you to force the :hover, :active, and :focus pseudo-classes to apply to a given node. from the dom nodes viewer, select the node and bring up the context menu. you should notice the set pseudo-classes menu item, which will allow you to set the content state for the aforementioned pseudo-classes. there is currently no way to inspect dynamically-applied rules for other pseudo-classes or any pseud...
Debugging service workers - Firefox Developer Tools
in this article we will look at debugging service workers using the firefox devtools application panel. when you open the application panel’s service workers view on a page that doesn't have a service worker registered, you'll get the following output shown: this gives you some advice on what to do if you don't have a service worker registered, and were perhaps expecting there to be one registered! let's start by troubleshooting this. getting your service worker to register before you can look at your service worker in action in the applications panel, you need to successfully register it. registration is done with a block of code along these lines, using the register() method: if('serviceworker' in navigator) { navigator.serviceworker .register('sw.js') .the...
...er service workers registered on the same domain): this gives you a variety of information about your service worker: the url that the service worker is registered on. that last time the service worker was updated (if the service has not been updated, this is when it was first installed). the path to the service worker source file. the server worker’s status, which can be one of the following: stopped: the service worker is installed, but not currently running. when the service worker is stopped, a start button is provided to start it running, allowing you to trigger the service worker lifecycle. running: the service worker is running. there are a couple of other useful controls on this view, too. unregister on the right-hand side of the service workers view there...
... different process to the application (bug 1432311). finding registered service workers on other domains as mentioned above, the service worker view of the application panel shows all the service workers registered on the current domain. if you want to see a list of information concerning all the service workers registered on your browser, you can visit about:debugging#/runtime/this-firefox. below the list of installed extensions you'll find a list of all the service workers you have registered. ...
Browser Console - Firefox Developer Tools
wser console looks like this: you can see that the browser console looks and behaves very much like the web console: most of the window is occupied by a pane that display messages. at the top, a toolbar enables you to filter the messages that appear. at the bottom, a command line interpreter enables you to evaluate javascript expressions. beginning with firefox 68, the browser console allows you to show or hide messages from the content process (i.e. the messages from scripts in all the opened pages) by setting or clearing the checkbox labeled show content messages. the following image shows the browser console focused on the same page as above after clicking on the show content messages checkbox. browser console logging the browser console logs the same sorts of messages as the...
...t of executing them. however, it displays such messages from: web content hosted by all browser tabs the browser's own code add-ons. messages from add-ons the browser console displays messages logged by all firefox add-ons. console.jsm to use the console api from a traditional or bootstrapped add-on, get it from the console module. one exported symbol from console.jsm is "console". below is an example of how to access it, which adds a message to the browser console. components.utils.import("resource://gre/modules/console.jsm"); console.log("hello from firefox code"); //output messages to the console learn more: console api reference console.jsm source code in the mozilla dxr hudservice there is also the hudservice which allows access to the browse console. the module is ...
...that will eat the new page, then loads a new page. note: you can restart the browser with the command ctrl + alt + r (windows, linux) or cmd + alt + r (mac) this command restarts the browser with the same tabs open as before the restart. modifying the browser ui since the global window object is the browser's chrome window, you can also modify the browser's user interface. ...
Page inspector 3-pane mode - Firefox Developer Tools
this article explains how to use the page inspector's 3-pane mode. feature summary from firefox 62 onwards, the page inspector has a new mode available — 3-pane mode. when activated, this allows you to see the following simultaneously: the html pane on the left hand side, as usual. the css rules in the middle in their own separate pane, rather than as a tab. the other css related features — such as computed styles view, animations view, and fonts view — in tabs on the right hand side, as usual. note: at narrower browser window widths, the tabs appear below the css rules pane. ...
...and side, as usual. the css rules in the middle in their own separate pane, rather than as a tab. the other css related features — such as computed styles view, animations view, and fonts view — in tabs on the right hand side, as usual. note: at narrower browser window widths, the tabs appear below the css rules pane. having the css rules in their own pane is very useful because it allows you to not only inspect your html and edit the css applied to it, but also see the effect this has on css features such as computed styles and grids in real time. you just need to have the relevant tab open to see the effect. a brief walkthrough the 3-pane inspector is disabled by default. it is enabled via a toggle control found in the tabs pane on the left hand side. press the toggle cont...
... mode enabled, you can observe live changes in css features as you edit the rules applied to the page. for example, you could edit a css grid property and observe the change immediately in the grid inspector. enabling the 3-pane inspector pre-firefox 62 in earlier versions of firefox (since firefox 59/60), you can enable 3 pane mode in release/beta by going to about:config and flipping the following prefs to true: devtools.inspector.split-rule-enabled — this switches 3-pane mode on and off. devtools.inspector.split-sidebar-toggle — this adds the ui toggle button that lets you toggle it on and off. in firefox 61, these preferences got renamed to: devtools.inspector.three-pane-enabled devtools.inspector.three-pane-toggle you need to flip these two to true in release/beta to tes...
Paint Flashing Tool - Firefox Developer Tools
en composited, so a change in the appearance of one layer does not trigger a repaint in any other layers, and when only the relation of two layers changes (in an animation, for example) no repaints are required at all. the choices made by a web developer can hinder the browser here, causing it to trigger more repaints, and for more of the screen, than necessary. this can then cause a site to be slow responding to user input (also known as "janky"). that's where the paint flashing tool helps: by showing you the areas that the browser repaints in response to an event, you can see whether it is repainting more than it needs to. using the paint flashing tool open the toolbox, then click the icon labeled "highlight painted area": then try using the page. after moving the mouse around and scr...
...g 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 transition to the element's margin-left, while the second way moves the element using the transform property. <body> <div id="container"> <div class="moving-box" id="moving-box-left-margin">transition using margin-left</div> <div class="moving-box" id="moving-box-transform">transition us...
...you should see that the margin-left version triggers a series of repaints as the element moves, while the transform version only causes repaints in the start and end positions. why? well, when you use transform, the browser creates a separate layer for the element. so when the element is moved, all that's changed is the relation of the two laye...
Animating CSS properties - Firefox Developer Tools
nd to drop frames if necessary. however, the performance cost of modifying a css property can vary from one property to another. animating expensive css properties can result in jank as the browser struggles to hit a smooth frame rate. the css rendering waterfall the process the browser uses to update the page when a css property has changed can be described as a waterfall consisting of the following steps: recalculate style: every time a css property for an element changes, the browser must recalculate computed styles. layout: next, the browser uses the computed styles to figure out the position and geometry for the elements. this operation is labeled "layout" but is also sometimes called "reflow". paint: finally, the browser needs to repaint the elements to the screen. one last st...
... layers, which are painted independently and then combined in a process called "composition". this sequence needs to fit into a single frame, since the screen isn't updated until it is complete. it's commonly accepted that 60 frames per second is the rate at which animations will appear smooth. for a rate of 60 frames per second, that gives the browser 16.7 milliseconds to execute the complete flow. css property cost in the context of the rendering waterfall, some properties are more expensive than others: property type cost examples properties that affect an element's geometry or position trigger a style recalculation, a layout and a repaint. left max-width border-width margin-left font-size properties that ...
...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 of the recording shows the waterfall view. if you scroll through this, you'll see a pattern like this: this is showing us the rendering waterfall. in each ani...
Cookies - Firefox Developer Tools
when you select an origin inside the cookies storage type from the storage tree, all the cookies present for that origin will be listed in a table. the cookies table has the following columns: name — the name of the cookie. value — the value of the cookie. domain — the domain of the cookie. path — the path property of the cookie. expires / max-age — the time when the cookie will expire. if the cookie is a session cookie, the value of this column will be "session" size — the size of the cookie name plus value in bytes. ...
...okie. path — the path property of the cookie. expires / max-age — the time when the cookie will expire. if the cookie is a session cookie, the value of this column will be "session" size — the size of the cookie name plus value in bytes. httponly — is this cookie http only? secure — is this cookie a secure cookie? samesite — is this cookie a same-site cookie? same-site cookies allow servers to mitigate the risk of csrf and information leakage attacks by asserting that a particular cookie should only be sent with requests initiated from the same registrable domain. last accessed — date and time when the cookie was last read. created — date and time when the cookie was created. hostonly — is this cookie a domain cookie? that is, the domain value matches exactly the do...
...ay, right-click on the existing table headings and use the resulting context menu to show/hide the columns. you can edit cookies by double-clicking inside cells in the table widget and editing the values they contain, and add new cookies by clicking the "plus" (+) button and then editing the resulting new row to the value you want. context menu the context menu for each cookie includes the following commands: add item - add a new cookie. delete <cookie name>.<domain> - deletes the selected cookie delete all from <domain> - deletes all cookies from the selected domain. this must be an exact match. for example, if you select "delete all from test8.example.com" only cookies from that domain will be deleted. cookies from "test13.example.com" will not be deleted. delete all - deletes all...
AbortSignal - Web APIs
properties the abortsignal interface also inherits properties from its parent interface, eventtarget. abortsignal.aborted read only a boolean that indicates whether the request(s) the signal is communicating with is/are aborted (true) or not (false). events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface. abort invoked when the dom request(s) the signal is communicating with is/are aborted. also available via the onabort property. ...
...r not (false). events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface. abort invoked when the dom request(s) the signal is communicating with is/are aborted. also available via the onabort property. methods the abortsignal interface inherits methods from its parent interface, eventtarget. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal an...
...ing the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); ...
Attr - Web APIs
Web › API › Attr
element's attributes as an object. in most dom methods, you will directly retrieve the attribute as a string (e.g., element.getattribute()), but certain functions (e.g., element.getattributenode()) or means of iterating return attr types. ...
... in the source code or by a script, and false if its value came from the default one defined in the document's dtd. value the attribute's value. note: dom level 3 defined namespaceuri, localname and prefix on the node interface. in dom4 they were moved to attr. this change is implemented in chrome since version 46.0 and firefox since version 48.0. deprecated properties and methods the following properties have been deprecated. where available, the appropriate replacement is noted. attributes this property now always returns null. childnodes obsolete since gecko 14 this property now always returns 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"...
...turns null. schematypeinfo read only the type information associated with this attribute. while the type information contained in this attribute is guaranteed to be correct after loading the document or invoking document.normalizedocument, this property may not be reliable if the node was moved. specified this property now always returns true. textcontent use attr.value instead. the following methods have been deprecated: appendchild() obsolete since gecko 14 modify the value of attr.value instead. clonenode() you shouldn't have been using this in the first place, so you probably don't care that this is going away. createattribute() use element.setattribute() instead. createattributens() use element.setattributens() instead. getattributenode() use element.getattribute()...
AudioContext.createJavaScriptNode() - Web APIs
named 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. ...
... 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. ...
...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. ...
AudioContext.createMediaStreamSource() - Web APIs
n value a new mediastreamaudiosourcenode object representing the audio node whose media is obtained from the specified source stream. example in this example, we grab a media (audio + video) stream from navigator.getusermedia, feed the media into a <video> element to play then mute the audio, but then also feed the audio into a mediastreamaudiosourcenode. next, we feed this source audio into a low pass biquadfilternode (which effectively serves as a bass booster), then a audiodestinationnode. the range slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. var pre = document.queryselector('pre'); var video = do...
...ction(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx = new audiocontext(); var source = audioctx.createmediastreamsource(stream); // create a biquadfilter var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); // get new...
...so playing/pausing the stream can still be done thro...
AudioContext.getOutputTimestamp() - Web APIs
basically, this is the time after the audio context was first created. ...
...timation of the moment when the sample frame corresponding to the stored contexttime value was rendered by the audio output device, in the same units and origin as performance.now(). this is the time after the document containing the audio context was first rendered. syntax var timestamp = audiocontext.getoutputtimestamp() parameters none. ...
... you can see full code of this example at output-timestamp (see it live also). ...
AudioNode.connect() - Web APIs
Web › API › AudioNode › connect
le. the default value is 0. inputindex optional an index describing which input of the destination you want to connect the current audionode to; the default is 0. the index numbers are defined according to the number of input channels (see audio channels). it is possible to connect an audionode to another audionode, which in turn connects back to the first audionode, creating a cycle. this is allowed only if there is at least one delaynode in the cycle. otherwise, a notsupportederror exception is thrown. this parameter is not allowed if the destination is an audioparam. return value if the destination is a node, connect() returns a reference to the destination audionode object, allowing you to chain multiple connect() calls. in some browsers, older implementations of this interface retur...
... oscillator node. ...
...ring the gain value of a gainnode using an oscillatornode with a slow frequency value. this technique is know as an lfo-controlled parameter. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // create an normal oscillator to make sound var oscillator = audioctx.createoscillator(); // create a second oscillator that will be used as an lfo (low-frequency // oscillator), and will control a parameter var lfo = audioctx.createoscillator(); // set the frequency of the second oscillator to a low number lfo.frequency.value = 2.0; // 2hz: two oscillations par second // create a gain whose gain audioparam will be controlled by the lfo var gain = audioctx.creategain(); // connect the lfo to the gain audioparam. this means the value of the lfo...
AudioParam.setValueCurveAtTime() - Web APIs
the curve is a linear interpolation between the sequence of values defined in an array of floating-point values, which are scaled to fit into the given interval starting at starttime and a specific duration. syntax var paramref = param.setvaluecurveattime(values, starttime, duration); parameters values an array of floating-point numbers representing the value curve the audioparam will change through along the specified duration. ...
...of floating-point numbers representing the value curve the audioparam will change through along the specified duration. every value in the array must be a finite number; if any value is nan, infinity, or -infinity, a typeerror exception is thrown. starttime a double representing the time (in seconds) after the audiocontext was first created that the change in value will happen. if this value is lower than audiocontext.currenttime, it is clamped to currenttime. duration a double representing the total time (in seconds) over which the parameter's value will change following the specified curve. the specified values are spaced equally along this duration. return value a reference to this audioparam object. some older browser implementations of this interface return undefined. exceptions ...
...ions invalidstateerror the specified array of values has fewer than 2 items in it. rangeerror the specified starttime is either negative or a non-finite value, or duration is not a finite, strictly positive number. typeerror one or more of the values in the values array is non-finite. non-finite values are nan, infinity, and -infinity. usage notes when the parameter's value finishes following the curve, its value is guaranteed to match the last value in the set of values specified in the values parameter. note: some early implementations of the web audio api did not ensure this to be the case, causing unexpected results. examples in this example, we have a media source with a single button (see the webaudio-examples repo for the source code, or view the example live.) when thi...
BaseAudioContext.createGain() - Web APIs
baseaudiocontext interface creates a gainnode, which can be used to control the overall gain (or volume) of the audio graph. syntax var gainnode = audiocontext.creategain(); return value a gainnode which takes as input one or more audio sources and outputs audio whose volume has been adjusted in gain (volume) to a level specified by the node's gainnode.gain a-rate parameter. ...
...innode which takes as input one or more audio sources and outputs audio whose volume has been adjusted in gain (volume) to a level specified by the node's gainnode.gain a-rate parameter. example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value. ...
... mute.onclick = voicemute; function voicemute() { if(mute.id == "") { // 0 means mute. if you still hear something, make sure you haven't // connected your source into the output in addition to usin...
BaseAudioContext.createScriptProcessor() - Web APIs
of the august 29 2014 web audio api spec publication, this feature has been marked as deprecated, and was replaced by audioworklet (see audioworkletnode). syntax var scriptprocessor = audioctx.createscriptprocessor(buffersize, numberofinputchannels, numberofoutputchannels); parameters buffersize the buffer size in units of sample-frames. ...
...of the following values: 256, 512, 1024, 2048, 4096, 8192, 16384. if it's not passed in, or if the value is 0, then the implementation will choose the best buffer size for the given environment, which will be a constant power of 2 throughout the lifetime of the node. this value controls how frequently the audioprocess event is dispatched and how many sample-frames need to be processed each call. lower values for buffersize will result in a lower (better) latency. higher values will be necessary to avoid audio breakup and glitches. it is recommended for authors to not specify this buffer size and allow the implementation to pick a good buffer size to balance between latency and audio quality. numberofinputchannels integer specifying the number of channels for this node's input, defaults to ...
...d. numberofoutputchannels integer specifying the number of channels for this node's output, defaults to 2. values of up to 32 are supported. important: webkit currently (version 31) requires that a valid buffersize be passed when calling this method. note: it is invalid for both numberofinputchannels and numberofoutputchannels to be zero. returns a scriptprocessornode. example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through ea...
Using the Beacon API - Web APIs
he beacon api's navigator.sendbeacon() method sends a beacon request to the server in the global browsing context. the method takes two arguments: the url and the data to send. the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata. if the browser successfully queues the request for delivery, the method returns true and returns false otherwise. the following example specifies a handler for the load and beforeunload events. the handler calls sendbeacon() with the current url. window.onload = window.onunload = function analytics(event) { if (!navigator.sendbeacon) return; var url = "https://example.com/analytics"; // create the data to send var data = "state=" + event.type + "&location=" + location.href; // send the beacon var status ...
... window.onsubmit = function send_analytics() { var data = json.stringify({ location: location.href, time: date() }); navigator.sendbeacon('/analytics', data); }; workernavigator.sendbeacon() the beacon api's workernavigator.sendbeacon() method works identically to the usual method, ...
...t is fired, the handler calls sendbeacon(). window.onsubmit = function send_analytics() { var data = json.stringify({ location: location.href, time: date() }); navigator.sendbeacon('/analytics', data); }; workernavigator.sendbeacon() the beacon api's workernavigator.sendbeacon() method works identically to the usual method, but is accessible from worker global scope. in the following example, a worker sends a beacon using the url and data from the global context. this code snippet is for the global context: function worker_send(url, data) { // create the worker object var myworker = new worker("worker-using.js"); // send the worker the url and data to beacon myworker.postmessage([url, data]); // set up a message handler to receive the success/fail message fro...
Blob - Web APIs
Web › API › Blob
tring containing the entire contents of the blob interpreted as utf-8 text. examples creating a blob the blob() constructor can create blobs from other objects. for example, to construct a blob from a json string: const obj = {hello: 'world'}; const blob = new blob([json.stringify(obj, null, 2)], {type : 'application/json'}); creating a url representing the contents of a typed array the following code creates a javascript typed array and creates a new blob containing the typed array's data. it then calls url.createobjecturl() to convert the blob into a url. html <p>this example creates a typed array containing the ascii codes for the space character through the letter z, then converts it to an object url. a link to open that object url is created. click the link to see the d...
...< 59; i++) { bytes[i] = 32 + i; } const url = typedarraytourl(bytes, 'text/plain'); const link = document.createelement('a'); link.href = url; link.innertext = 'open the array url'; document.body.appendchild(link); result click the link in the example to see the browser decode the object url. extracting data from a blob one way to read content from a blob is to use a filereader. ...
...acting data from a blob one way to read content from a blob is to use a filereader. the following code reads the content of a blob as a typed array: const reader = new filereader(); reader.addeventlistener('loadend', () => { // reader.result contains the contents of blob as a typed array }); reader.readasarraybuffer(blob); another way to read content from a blob is to use a response. the following code reads the content of a blob as text: const text = await (new response(blob)).text(); or by using blob.prototype.text(): const text = await blob.text(); by using other methods of filereader, it is possible to read the contents of a blob as a string or a data url. specifications specification status comment file apithe definition of 'the blob interface' in tha...
BroadcastChannel - Web APIs
the broadcastchannel interface represents a named channel that any browsing context of a given origin can subscribe to. it allows communication between different documents (in different windows, tabs, frames or iframes) of the same origin. messages are broadcasted via a message event fired at all broadcastchannel objects listening to the channel. note: this feature is available in web workers. ...
...nt documents (in different windows, tabs, frames or iframes) of the same origin. messages are broadcasted via a message event fired at all broadcastchannel objects listening to the channel. note: this feature is available in web workers. ...
...ror is fired—that is, when it receives a message that cannot be deserialized. methods this interface also inherits methods from its parent, eventtarget. broadcastchannel.postmessage() sends the message, of any type of object, to each broadcastchannel object listening to the same channel. broadcastchannel.close() closes the channel object, indicating it won't get any new messages, and allowing it to be, eventually, garbage collected. events message fired when when a message arrives on the channel. also available via the onmessage property. messageerror fired when a message arrives that can't be deserialized. also available via the onmessageerror property. specifications specification status comment html living standardthe definition of 'broadcast...
Using the CSS properties and values API - Web APIs
the css properties and values api — part of the css houdini umbrella of apis — allows the registration of css custom properties, allowing for property type checking, default values, and properties that do or do not inherit their value. registering a custom property registering a custom property allows you to tell the browser how the custom property should behave; what are allowed types, whether the custom property inherits its value, and what the default value of the custom property is. there are two ways to register a property, in javascript or in css. note: the javascript option has working implementations. the css option does not. ...
...ng a custom property allows you to tell the browser how the custom property should behave; what are allowed types, whether the custom property inherits its value, and what the default value of the custom property is. there are two ways to register a property, in javascript or in css. note: the javascript option has working implementations. the css option does not. css.registerproperty the following will register a css custom properties, --my-prop, using css.registerproperty, as a color, give it a default value, and have it not inherit its value: window.css.registerproperty({ name: '--my-prop', syntax: '<color>', inherits: false, initialvalue: '#c0ffee', }); @property the same registration can take place in css. ...
...he css option does not. css.registerproperty the following will register a css custom properties, --my-prop, using css.registerproperty, as a color, give it a default value, and have it not inherit its value: window.css.registerproperty({ name: '--my-prop', syntax: '<color>', inherits: false, initialvalue: '#c0ffee', }); @property the same registration can take place in css. ...
Using the CSS Typed Object Model - Web APIs
converting css object model value strings into meaningfully-typed javascript representations and back (via htmlelement.style) can incur a significant performance overhead. the css typed om makes css manipulation more logical and performant by providing object features (rather than cssom string manipulation), providing access to types, methods, and an object model for css values. this article provides an introduction to all of its main features. ...
...edvalue let unit = allcomputedstyles.get('--unit'); console.log( unit ) // let parsedunit = cssnumericvalue.parse( unit ); console.log( parsedunit ); console.log( parsedunit.unit ); console.log( parsedunit.value ); for this example to work, the example must be closed out here. we've created a blue button with a magic wand background image. ...
...ue.parse( unit ); console.log( parsedunit ); console.log( parsedunit.unit ); console.log( parsedunit.value ); for this example to work, the example must be closed out here. we've created a blue button with a magic wand background image. we grab our stylepropertymapreadonly with the following javascript: const allcomputedstyles = document.queryselector('button').computedstylemap(); the following examples reference allcomputedstyles: cssunparsedvalue the cssunparsedvalue represents custom properties: // cssunparsedvalue let unit = allcomputedstyles.get('--unit'); console.log( unit ) // cssunparsedvalue {0: " 1.2rem", length: 1} console.log (unit[0] ) // " 1.2rem" when we invoke get(), a custom property of type cssunparsedvalue is returned. note the space before the 1.2rem. t...
CSS Typed Object Model API - Web APIs
the css typed object model api simplifies css property manipulation by exposing css values as typed javascript objects rather than strings. this not only simplifies css manipulation, but also lessens the negative impact on performance as compared to htmlelement.style. generally, css values can be read and written in javascript as strings, which can be slow and cumbersome. css typed object model api provides interfaces to interact with underlying values, by representing them with specialized js objects that can be manipulated and understood more easily and more reliably than string parsing and concatenation. this is easier for authors (for example, numeric values are reflected with actual js numbers, and have unit-aware mathematical operations defined for them). it is also generally faster, ...
...ably than string parsing and concatenation. this is easier for authors (for example, numeric values are reflected with actual js numbers, and have unit-aware mathematical operations defined for them). it is also generally faster, as values can be directly manipulated and then cheaply translated back into underlying values without having to both build and parse strings of css. css typed om both allows for the performant manipulation of values assigned to css properties while enabling maintainable code that is both more understand and easier to write. interfaces cssstylevalue the cssstylevalue interface of the the css typed object model api is the base class of all css values accessible through the typed om api. an instance of this class may be used anywhere a string is expected. csssty...
...intainable code that is both more understand and easier to write. interfaces cssstylevalue the cssstylevalue interface of the the css typed object model api is the base class of all css values accessible through the typed om api. an instance of this class may be used anywhere a string is expected. cssstylevalue.parse(property, csstext) the parse() method of the cssstylevalue interface allows a cssnumericvalue to be constructed from a css string. it sets a specific css property to the specified values and returns the first value as a cssstylevalue object. cssstylevalue.parseall() the parseall() method of the cssstylevalue interface sets all occurences of a specific css property to the specified valueand returns an array of cssstylevalue objects, each containing one of the supplied...
CanvasRenderingContext2D.fillText() - Web APIs
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. ...
... 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. ...
...order to fit the text in the specified width. return value undefined. examples drawing filled text this example writes the words "hello world" using the filltext() method. html first, we need a canvas to draw into. this code creates a context 400 pixels wide and 150 pixels across. <canvas id="canvas" width="400" height="150"></canvas> javascript the javascript code for this example follows. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '50px serif'; ctx.filltext('hello world', 50, 90); this code obtains a reference to the <canvas>, then gets a reference to its 2d graphics context. with that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call filltext() to draw the text "hello world," ...
CanvasRenderingContext2D.filter - Web APIs
the canvasrenderingcontext2d.filter property of the canvas 2d api provides filter effects such as blurring and grayscaling. it is similar to the css filter property and accepts the same values. syntax ctx.filter = "<filter-function1> [<filter-function2>] [<filter-functionn>]"; ctx.filter = "none"; values the filter property accepts a value of "none" or one or more of the following filter functions in a domstring. url() a css <url>. takes an iri pointing to an svg filter element, which may be embedded in an external xml file. blur() a css <length>. applies a gaussian blur to the drawing. it defines the value of the standard deviation to the gaussian function, i.e., how many pixels on the screen blend into each other; thus, a larger value will create more blur. a value of ...
...of 100% leaves the input unchanged. contrast() a css <percentage>. adjusts the contrast of the drawing. a value of 0% will create a drawing that is completely black. a value of 100% leaves the drawing unchanged. drop-shadow() applies a drop shadow effect to the drawing. a drop shadow is effectively a blurred, offset version of the drawing's alpha mask drawn in a particular color, composited below the drawing. this function takes up to five arguments: <offset-x>: see <length> for possible units. specifies the horizontal distance of the shadow. <offset-y>: see <length> for possible units. specifies the vertical distance of the shadow. <blur-radius>: the larger this value, the bigger the blur, so the shadow becomes bigger and lighter. negative values are not allowed. <color>: see <...
... value of 0% means completely un-saturated. a value of 100% leaves the drawing unchanged. sepia() a css <percentage>. converts the drawing to sepia. a value of 100% means completely sepia. a value of 0% leaves the drawing unchanged. none no filter is applied. initial value. examples to view these examples, make sure to use a browser that supports this feature; see the compatibility table below. applying a blur this example blurs a piece of text using the filter property. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.filter = 'blur(4px)'; ctx.font = '48px serif'; ctx.filltext('hello world', 50, 100); result applying multiple filters you can combine as many filters as you like. this e...
CanvasRenderingContext2D.strokeText() - Web APIs
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. ...
... 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. ...
...r to fit the text in the specified width. return value undefined. examples drawing text outlines this example writes the words "hello world" using the stroketext() method. html first, we need a canvas to draw into. this code creates a context 400 pixels wide and 150 pixels high. <canvas id="canvas" width="400" height="150"></canvas> javascript the javascript code for this example follows. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '50px serif'; ctx.stroketext('hello world', 50, 90); this code obtains a reference to the <canvas>, then gets a reference to its 2d graphics context. with that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call stroketext() to draw the text "hello worl...
Using channel messaging - Web APIs
in this article we'll explore the basics of using this technology. note: this feature is available in web workers. use cases channel messaging is mainly useful in cases where you've got a social site that embeds capabilities from other sites into its main interface via iframes, such as games, address book, or an audio player with personalized music choices. ...
...high scores from your game into your main profile, or add new background music choices from the audio player onto the game? such things are not so easy using conventional web technology, because of the security models the web uses. you have to think about whether the origins trust one another, and how the messages are passed. message channels on the other hand can provide a secure channel that allows you to pass data between different browsing contexts. note: for more information and ideas, the ports as the basis of an object-capability model on the web section of the spec is a useful read. simple examples to get your started, we have published a couple of demos on github. first up, check out our channel messaging basic demo (run it live too), which shows a really simple single message...
...he receiving browsing context. in this case, we are transferring messagechannel.port2 to the iframe, so it can be used to communicate with the main page. when our button is clicked, we prevent the form from submitting as normal and then send the value entered in our text input to the iframe via the messagechannel. ...
ContentIndex.getAll() - Web APIs
the getall() method of the contentindex interface returns a promise that resolves with an iterable list of content index entries. syntax var indexedcontent = contentindex.getall(); parameters this method receives no parameters. return value returns a promise that resolves with an array of contentdescription items. contentdescription each item returned is an object containing the following data: id: a unique string identifier. title: a string title for the item. used in user-visible lists of content. title: a string title of the item. used in user-visible lists of content. description: a string description of the item. used in user-visible lists of content. url: a string containing the url of the corresponding html document. needs to be under the scope of the current...
...ists of content. url: a string containing the url of the corresponding html document. needs to be under the scope of the current service worker. category: optional a string defining the category of content. can be: '' an empty string, this is the default. ...
...io icons: optional an array of image resources, defined as an object with the following data: src: a url string of the source image. sizes: optional a string representation of the image size. type: optional the mime type of the image. exceptions no exceptions are thrown. if there are no items in the content index, an empty array is returned. examples the below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface. async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing ...
ContentIndex - Web APIs
properties there are no properties of this interface. methods contentindex.add registers an item with the content index. contentindex.delete unregisters an item from the currently indexed content. contentindex.getall returns a promise that resolves with an iterable list of content index entries. examples feature detection and interface access here we get a reference to the serviceworkerregistration, then check for the index property, which gives us access to the content index interface. ...
... async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing ...
... async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } all the above methods are avai...
Credential Management API - Web APIs
credential management concepts and usage this api lets websites interact with a user agent’s password system so that websites can deal in a uniform way with site credentials and user agents can provide better assistance with the management of their credentials. ...
... credential management concepts and usage this api lets websites interact with a user agent’s password system so that websites can deal in a uniform way with site credentials and user agents can provide better assistance with the management of their credentials. ...
...h 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.example.com. to take advantage of this, a pa...
DOMImplementation.createHTMLDocument() - Web APIs
mplementation.createhtmldocument(title) parameters title optional (except in ie) a domstring containing the title to give the new html document. example this example creates a new html document and inserts it into an <iframe> in the current document. ...
...itle to give the new html document. example this example creates a new html document and inserts it into an <iframe> in the current document. ...
...w document. line 16 pulls the contentdocument of the frame; this is the document into which we'll be injecting the new content. the next two lines handle importing the contents of our new document into the new document's context. finally, line 20 actually replaces the contents of the frame with the new document's contents. view live examples the returned document is pre-constructed with the following html: <!doctype html> <html> <head> <title>title</title> </head> <body> </body> </html> specifications specification status comment domthe definition of 'domimplementation.createhtmldocument' in that specification. living standard initial definition. ...
DOMMatrixReadOnly - Web APIs
properties this interface doesn't inherit any properties. is2d read only a boolean flag whose value is true if the matrix was initialized as a 2d matrix. if false, the matrix is 3d. ...
... properties this interface doesn't inherit any properties. is2d read only a boolean flag whose value is true if the matrix was initialized as a 2d matrix. if false, the matrix is 3d. ...
...int values representing each component of a 4×4 matrix, where m11 through m14 are the first column, m21 through m24 are the second column, and so forth. a, b, c, d, e, f double-precision floating-point values representing the components of a 4×4 matrix which are required in order to perform 2d rotations and translations. these are aliases for specific components of a 4×4 matrix, as shown below. 2d 3d equivalent a m11 b m12 c m21 d m22 e m41 f m42 methods this interface doesn't inherit any methods. none of the following methods alter the original matrix. dommatrixreadonly.flipx() returns a new dommatrix created by flipping the source matrix around its...
DOMParser - Web APIs
Web › API › DOMParser
mparser.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. ...
... parsing svg or html the domparser can also be used to parse an svg document (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7) or an html document (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9). there are three different results possible, selected by the mime type given. if the mime type is text/xml, the result will be an xmldocument if the mime type is image/...
... living standard ...
DOMTokenList - Web APIs
wtoken) replaces token with newtoken. domtokenlist.supports(token) returns true if a given token is in the associated attribute's supported tokens. domtokenlist.toggle(token [, force]) removes token from the list if it exists, or adds token to the list if it doesn't. returns a boolean indicating whether token is in the list after the operation. ...
..., or adds token to the list if it doesn't. returns a boolean indicating whether token is in the list after the operation. domtokenlist.entries() returns an iterator, allowing you to go through all key/value pairs contained in this object. domtokenlist.foreach(callback [, thisarg]) executes a provided callback function once per domtokenlist element. domtokenlist.keys() returns an iterator, allowing you to go through all keys of the key/value pairs contained in this object. domtokenlist.values() returns an iterator, allowing you to go through all values of the key/value pairs contained in this object. ...
...ct. domtokenlist.foreach(callback [, thisarg]) executes a provided callback function once per domtokenlist element. domtokenlist.keys() returns an iterator, allowing you to go through all keys of the key/value pairs contained in this object. domtokenlist.values() returns an iterator, allowing you to go through all values of the key/value pairs contained in this object. examples in the following simple example, we retrieve the list of classes set on a <p> element as a domtokenlist using element.classlist, add a class using domtokenlist.add(), and then update the node.textcontent of the <p> to equal the domtokenlist. 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.textcont...
DataTransfer.getData() - Web APIs
thod returns an empty string. caveats data availability the html5 drag and drop specification dictates a drag data store mode. this may result in unexpected behavior, being datatransfer.getdata() not returning an expected value. example this example shows the use of the datatransfer object's getdata() and setdata() methods. ...
...or, being datatransfer.getdata() not returning an expected value. example this example shows the use of the datatransfer object's getdata() and setdata() methods. ...
...l content <div id="div1" ondrop="drop(event)" ondragover="allowdrop(event)"> <span id="drag" draggable="true" ondragstart="drag(event)">drag me to the other box</span> </div> <div id="div2" ondrop="drop(event)" ondragover="allowdrop(event)"></div> css content #div1, #div2 { width:100px; height:50px; padding:10px; border:1px solid #aaaaaa; } javascript content function allowdrop(allowdropevent) { allowdropevent.target.style.color = 'blue'; allowdropevent.preventdefault(); } function drag(dragevent) { dragevent.datatransfer.setdata("text", dragevent.target.id); dragevent.target.style.color = 'green'; } function drop(dropevent) { dropevent.preventdefault(); var data = dropevent.datatransfer.getdata("text"); dropevent.target.appendchild(doc...
Document.getElementsByTagName() - Web APIs
ection of elements with the given tag name. the complete document is searched, including the root node. the returned htmlcollection is live, meaning that it updates itself automatically to stay in sync with the dom tree without having to call document.getelementsbytagname() again. ...
...); elements is a live htmlcollection (but see the note below) of found elements in the order they appear in the tree. name is a string representing the name of the elements. the special string "*" represents all elements. the latest w3c specification says elements is an htmlcollection; however, this method returns a nodelist in webkit browsers. see bug 14869 for details. example in the following example, getelementsbytagname() starts from a particular parent element and searches top-down recursively through the dom from that parent element, building a collection of all descendant elements which match the tag name parameter. this demonstrates both document.getelementsbytagname() and the functionally identical element.getelementsbytagname(), which starts the search at a specific element...
...this is undesirable when trying to match camelcase svg elements in a subtree in an html document. document.getelementsbytagnamens() is useful in that case. see also bug 499656. document.getelementsbytagname() is similar to element.getelementsbytagname(), except that its search encompasses the whole document. specifications specification statu...
Document.requestStorageAccess() - Web APIs
ge access storage access is granted based on a series of checks described here: if the document already has been granted access, resolve. if the document has a null origin, reject. if the document's frame is the main frame, resolve. if the sub frame's origin is equal to the main frame's, resolve. if the sub frame is not sandboxed, skip to step 7. if the sub frame doesn't have the token allow-storage-access-by-user-activation, reject. if the sub frame's parent frame is not the top frame, reject. if the browser is not processing a user gesture, reject. check any additional 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 fulf...
...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() during the same browsing session will prompt the user. the maximum number of concurrent storage access grants an origin can obtain is a positive integer currently defined as one percent of the number of top-level origins visited in the current session or 5, whichever is higher. the threshold is enforced on the level o...
...ess grants are given through our compatibility heuristics. the ephemeral storage access grant is: invalidated at the end of the browser session. not persisted to disk (e.g. will not persist if the browser crashes). reset after 24 hours in the case of a long-running browser session. ...equal or more origins than the maximum: the user is prompted if the user clicks “allow” or “allow on any site” the request is resolved. if the user clicks “don’t allow”, the storage access request is rejected and the requesting origin can re-request once it receives another user interaction. if the user allows storage the requesting origin is given a persistent storage access grant on the current top-level origin. the number of origins the requesting origin has stora...
DocumentFragment - Web APIs
agment 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. ...
...he 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. ...
...ntbyid(). usage notes a common use for documentfragment is to create one, assemble a dom subtree within it, then append or insert the fragment into the dom using node interface methods such as appendchild() or insertbefore(). doing this moves the fragment's nodes into the dom, leaving behind an empty documentfragment. because all of the nodes are inserted into the document at once, only one reflow and render is triggered instead of potentially one for each node inserted if they were inserted separately. this interface is also of great use with web components: <template> elements contain a documentfragment in their htmltemplateelement.content property. an empty documentfragment can be created using the document.createdocumentfragment() method or the constructor. example html <ul id="li...
Using the W3C DOM Level 1 Core - Web APIs
ke types of documents). due to the ubiquity of the dom, this api is supported in all major browsers, including mozilla firefox and microsoft internet explorer, and serves as a base for scripting on the web. what is a dom tree? a dom tree is a kind of tree whose nodes represent an html or xml document's contents. each html or xml document has a unique dom tree representation. ...
...p>paragraph</p> </body> </html> has a dom tree that looks like this: (note that, although the above tree is similar to the above document's dom tree, it's not identical, as the actual dom tree preserves whitespace.) when a web browser parses an html document, it builds a dom tree and then uses it to display the document. what does the dom level 1 core let me do? the w3c dom level 1 core allows you to change a dom tree in any way you want. this implies the ability to create any html or xml document from scratch, or to change any contents of a given html or xml document. the easiest way for web page authors to edit the dom of a document is to use javascript to access the document property of the global object. this document object implements the document interface from the w3c's dom lev...
...s of a given html or xml document. the easiest way for web page authors to edit the dom of a document is to use javascript to access the document property of the global object. this document object implements the document interface from the w3c's dom level 1 spec. a simple example suppose the author wants to change the header of the above document and write two paragraphs instead of one. ...
Element.attachShadow() - Web APIs
the element.attachshadow() method attaches a shadow dom tree to the specified element and returns a reference to its shadowroot. elements you can attach a shadow to note that you can't attach a shadow root to every type of element. there are some that can't have a shadow dom for security reasons (for example <a>), and more besides. ...
...this can be one of: open: elements of the shadow root are accessible from javascript outside the root, for example using element.shadowroot: element.shadowroot; // returns a shadowroot obj closed: denies access to the node(s) of a closed shadow root from javascript outside it: ...
...ing. return value returns a shadowroot object. exceptions exception explanation invalidstateerror the element you are trying to attach to is already a shadow host. notsupportederror you are trying to attach a shadow root to an element outside the html namespace, or the element cannot have a shadow attached to it (see above). examples the following example is taken from our word-count-web-component demo (see it live also). you can see that we use attachshadow() in the middle of the code to create a shadow root, which we then attach our custom element's contents to. // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // count wo...
Element.innerHTML - Web APIs
Web › API › Element › innerHTML
ing; value a domstring containing the html serialization of the element's descendants. setting the value of innerhtml removes all of the element'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 th...
...he value of innerhtml is changed to this new string. as a result, the document contents are replaced with a display of the page's entire source code. document.documentelement.innerhtml = "<pre>" + document.documentelement.innerhtml.replace(/</g,"&lt;") + "</pre>"; operational details what exactly happens when you set value of innerhtml? doing so causes the user agent to follow these steps: the specified value is parsed as html or xml (based on the document type), resulting in a documentfragment object representing the new set of dom nodes for the new elements. if the element whose contents are being replaced is a <template> element, then the <template> element's content attribute is replaced with the new documentfragment created in step 1. for all other elements, ...
...gevent); boxelem.addeventlistener("mouseleave", logevent); html the html is quite simple for our example. <div class="box"> <div><strong>log:</strong></div> <div class="log"></div> </div> the <div> with the class "box" is just a container for layout purposes, presenting the contents with a box around it. the <div> whose class is "log" is the container for the log text itself. css the following css styles our example content. .box { width: 600px; height: 300px; border: 1px solid black; padding: 2px 4px; overflow-y: scroll; overflow-x: auto; } .log { margin-top: 8px; font-family: monospace; } result the resulting content looks like this. you can see output into the log by moving the mouse in and out of the box, clicking in it, and so forth. specification ...
Element.setAttribute() - Web APIs
s, the value is updated; otherwise a new attribute is added with the specified name and value. to get the current value of an attribute, use getattribute(); to remove an attribute, call removeattribute(). syntax element.setattribute(name, value); parameters name a domstring specifying the name of the attribute whose value is to be set. the attribute name is automatically converted to all lower-case when setattribute() is called on an html element in an html document. value a domstring containing the value to assign to the attribute. any non-string value specified is converted automatically into a string. boolean attributes are considered to be true if they're present on the element at all, regardless of their actual value; as a rule, you should specify the empty string ("") in va...
...ing containing the value to assign to the attribute. any non-string value specified is converted automatically into a string. boolean attributes are considered to be true if they're present on the element at all, regardless of their actual value; as a rule, you should specify the empty string ("") in value (some people use the attribute's name; this works but is non-standard). see the example below for a practical demonstration. since the specified value gets converted into a string, specifying null doesn't necessarily do what you expect. instead of removing the attribute or setting its value to be null, it instead sets the attribute's value to the string "null". if you wish to remove an attribute, call removeattribute(). return value undefined. exceptions invalidcharactererror the ...
...sarily do what you expect. instead of removing the attribute or setting its value to be null, it instead sets the attribute's value to the string "null". if you wish to remove an attribute, call removeattribute(). return value undefined. exceptions invalidcharactererror the specified attribute name contains one or more characters which are not valid in attribute names. example in the following example, setattribute() is used to set attributes on a <button>. html <button>hello world</button> javascript var b = document.queryselector("button"); b.setattribute("name", "hellobutton"); b.setattribute("disabled", ""); this demonstrates two things: the first call to setattribute() above shows changing the name attribute's value to "hellobutton". you can see this using your browse...
File - Web APIs
Web › API › File
file objects are generally retrieved from a filelist object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's datatransfer object, or from the mozgetasfile() api on an htmlcanvaselement. a file object is a specific kind of a blob, and can be used in any context that a blob can. in particular, filereader, url.createobjecturl(), createimagebitmap(), and xmlhttprequest.send() accept both blobs and files. see using files from web applications for more information and examples. ...
...e used in any context that a blob can. in particular, filereader, url.createobjecturl(), createimagebitmap(), and xmlhttprequest.send() accept both blobs and files. see using files from web applications for more information and examples. ...
...epoch (january 1st, 1970 at midnight). file.prototype.lastmodifieddate read only returns the last modified date of the file referenced by the file object. file.prototype.nameread only returns the name of the file referenced by the file object. file.prototype.webkitrelativepath read only returns the path the url of the file is relative to. file implements blob, so it also has the following properties available to it: file.prototype.size read only returns the size of the file in bytes. file.prototype.type read only returns the mime type of the file. instance methods the file interface doesn't define any methods, but inherits methods from the blob interface: blob.prototype.slice([start[, end[, contenttype]]]) returns a new blob object containing the data in the spec...
FileEntrySync - Web APIs
this specification is more or less abandoned as it didn't get significant traction among browser makers. basic concepts to write content to file, create a filewriter object by calling createwriter(). ...
...). method overview filewritersync createwriter () raises (fileexception); file file () raises (fileexception); methods createwriter() creates a new filewriter associated with the file that the fileentry represents. void createwriter ( ) raises (fileexception); parameter none. returns filewritersync exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist. invalid_state_err the file is no longer valid for some reason other than it having been deleted. file() returns a file that represents the current state of the file that this fileentry represents. void file ( ) raises (fileexception); parameter none. returns file except...
...ot_found_err the file does not exist. invalid_state_err the file is no longer valid for some reason other than it having been deleted. file() returns a file that represents the current state of the file that this fileentry represents. void file ( ) raises (fileexception); parameter none. returns file exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist. invalid_state_err the file is no longer valid for some reason other than it having been deleted. 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...
FileSystemDirectoryEntry.getDirectory() - Web APIs
ntry.getdirectory([path][, options][, successcallback][, errorcallback]); parameters path optional a usvstring representing an absolute path or a path relative to the directory on which the method is called, describing which directory entry to return. absolute paths may not be able to be used, for security reasons. options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file already exists. these options are currently not useful in web contexts. successcallback optional a method to be called once the filesystemdirectoryentry has been created. the method receives a single parameter: the filesystemdirectoryentry object representing the directory in question. errorcall...
...on. errorcallback optional a method to be called if an error occurs. receives as its sole input parameter a fileerror object describing the error which occurred. return value undefined. errors if an error occurs and an errorcallback was specified, it gets called with a single parameter: a fileerror object describing the error. the fileerror.code specifies what type of error occurred, as follows: fileerror.not_found_err the create option was not specified (or was specified as false), and the directory doesn't exist. fileerror.path_exists_err the create and exclusive options were both true, indicating that the directory should be created but must not already exist, but the directory does in fact already exist. fileerror.security_err the request to access the directory was denied ...
... is true, and the requested file or directory doesn't exist, the user agent should create it. the default is false. the parent directory must already exist. exclusive optional if true, and the create option is also true, the file must not exist prior to issuing the call. instead, it must be possible for it to be created newly at call time. the default is false. values and results the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallb...
FileSystemDirectoryEntry.getFile() - Web APIs
irectory subtree rooted at the directory on which it's called. syntax filesystemdirectoryentry.getfile([path][, options][, successcallback][, errorcallback]); parameters path optional a usvstring specifying the path, relative to the directory on which the method is called, describing which file's entry to return. options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file already exists. these options are currently not useful in web contexts. successcallback optional a method to be called once the filesystemfileentry has been created. the method receives a single parameter: the filesystemfileentry object representing the file in question. errorcallback optional ...
...back optional a method to be called if an error occurs. receives as its sole input parameter a fileerror object describing the error which occurred. return value undefined. errors if an error occurs and an errorcallback was specified, it gets called with a single parameter: a fileerror object describing the error. the {domxref("fileerror.code")}} specifies what type of error occurred, as follows: fileerror.not_found_err the create option was not specified (or was specified as false), and the file doesn't exist. fileerror.path_exists_err the create and exclusive options were both true, indicating that the file should be created but must not already exist, but the file does in fact already exist. fileerror.security_err the request to access the file was denied for security reasons...
... is true, and the requested file or directory doesn't exist, the user agent should create it. the default is false. the parent directory must already exist. exclusive optional if true, and the create option is also true, the file must not exist prior to issuing the call. instead, it must be possible for it to be created newly at call time. the default is false. values and results the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallb...
FileSystemEntry - Web APIs
origin of your app. just use filesystem: scheme for the root directory of the origin of the app. for example, if your app is in http://www.html5rocks.com, open filesystem:http://www.html5rocks.com/temporary/ in a tab. chrome shows a read-only list of all the files and folders stored the origin of your app. example to see an example of how tourl() works, see the method description. the snippet below shows you how you can remove a file by name. // taking care of the browser-specific prefixes. window.requestfilesystem = window.requestfilesystem || window.webkitrequestfilesystem; ... // opening a file system with temporary storage window.requestfilesystem(temporary, 1024*1024 /*1mb*/, function(fs) { fs.root.getfile('log.txt', {}, function(fileentry) { fileentry.remove(function() { ...
...indow.requestfilesystem || window.webkitrequestfilesystem; ... // opening a file system with temporary storage window.requestfilesystem(temporary, 1024*1024 /*1mb*/, function(fs) { fs.root.getfile('log.txt', {}, function(fileentry) { fileentry.remove(function() { console.log('file removed.'); }, onerror); }, onerror); }, onerror); properties this interface provides the following properties. filesystem read only a filesystem object representing the file system in which the entry is located. fullpath read only a usvstring object which provides the full, absolute path from the file system's root to the entry; it can also be thought of as a path which is relative to the root directory, prepended with a "/" character. isdirectory read only a boolean which is tru...
...haracter. isdirectory read only a boolean which is true if the entry represents a directory; otherwise, it's false. isfile read only a boolean which is true if the entry represents a file. if it's not a file, this value is false. name read only a usvstring containing the name of the entry (the final part of the path, after the last "/" character). methods this interface defines the following methods. copyto() copies the file or directory to a new location on the file system. getmetadata() obtains metadata about the file, such as its modification date and size. getparent() returns a filesystemdirectoryentry representing the entry's parent directory. moveto() moves the file or directory to a new location on the file system, or renames the file or directory. remove() remo...
Using FormData Objects - Web APIs
mplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br /> <label>custom file label:</label> <input type="text" name="filelabel" size="12" maxlength="32" /><br /> <label>file to stash:</label> <input type="file" name="file" required /> <input type="submit" value="stash the file!" /> </form> <div></div> then you can send it using code like the following: var form = document.forms.nameditem("fileinfo"); form.addeventlistener('submit', function(ev) { var ooutput = document.queryselector("div"), odata = new formdata(form); odata.append("customfield", "this is some extra data"); var oreq = new xmlhttprequest(); oreq.open("post", "stash.php", true); oreq.onload = function(oevent) { if (oreq.status == 200) { ooutput.in...
... parameter isn't supported), the name "blob" is used. using a formdata event a more recent addition to the platform than the formdata object is the formdata event — this is fired on an htmlformelement object after the entry list representing the form's data is constructed. this happens when the form is submitted, but can also be triggered by the invocation of a formdata() constructor. this allows a formdata object to be quickly obtained in response to a formdata event firing, rather than needing to put it together yourself. typically this is used as shown in our simple formdata event demo — in the javascript we reference a form: const formelem = document.queryselector('form'); in our submit event handler we use preventdefault to stop the default form submission, then invoke a formd...
... formelem.addeventlistener('formdata', (e) => { console.log('formdata fired'); // get the form data from the event object let data = e.formdata; for (var value of data.values()) { console.log(value); } // submit the data via xhr let request = new xmlhttprequest(); request.open("post", "/formhandler"); request.send(data); }); ...
Guide to the Fullscreen API - Web APIs
given an element that you'd like to present in full-screen mode (such as a <video>, for example), you can present it in full-screen mode by simply calling its requestfullscreen() method. let's consider this <video> element: <video controls id="myvideo"> <source src="somevideo.webm"></source> <source src="somevideo.mp4"></source> </video> we can put that video into full-screen mode as follows: var elem = document.getelementbyid("myvideo"); if (elem.requestfullscreen) { elem.requestfullscreen(); } this code checks for the existence of the requestfullscreen() method before calling it. presentation differences it's worth noting a key difference here between the gecko and webkit implementations at this time: gecko automatically adds css rules to the element to stretch it to fill th...
...creenchange event. note that the fullscreenchange event doesn't provide any information itself as to whether the document is entering or exiting fullscreen mode, but if the document has a non null fullscreenelement, you know you're in fullscreen mode. when a fullscreen request fails it's not guaranteed that you'll be able to switch into fullscreen mode. for example, <iframe> elements have the allowfullscreen attribute in order to opt-in to allowing their content to be displayed in fullscreen mode. in addition, certain kinds of content, such as windowed plug-ins, cannot be presented in fullscreen mode. attempting to put an element which can't be displayed in fullscreen mode (or the parent or descendant of such an element) won't work. instead, the element which requested fullscreen will recei...
...ications: documentorshadowroot.fullscreenelement the fullscreenelement property tells you the element that's currently being displayed fullscreen. if this is non-null, the document is in fullscreen mode. if this is null, the document is not in fullscreen mode. document.fullscreenenabled the fullscreenenabled property tells you whether or not the document is currently in a state that would allow fullscreen mode to be requested. things your users want to know you'll want to be sure to let your users know that they can press the esc key (or f11) to exit fullscreen mode. in addition, navigating to another page, changing tabs, or switching to another application (using, for example, alt-tab) while in fullscreen mode exits fullscreen mode as well. example in this example, a video is pre...
GainNode.gain - Web APIs
Web › API › GainNode › gain
the gain property of the gainnode interface is an a-rate audioparam representing the amount of gain to apply. syntax var audioctx = new audiocontext(); var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; value an audioparam. note: though the audioparam returned is read-only, the value it represents is not. ...
...ocontext(); var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; value an audioparam. note: though the audioparam returned is read-only, the value it represents is not. example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value. ...
... mute.onclick = voicemute; function voicemute() { if(mute.id == "") { // 0 means mute. if you still hear something, make sure you haven't // connected your source into the output in addition to usin...
GainNode - Web APIs
Web › API › GainNode
e; instead, use the method audiocontext.creategain(). properties inherits properties from its parent, audionode. gainnode.gain read only is an a-rate audioparam representing the amount of gain to apply. you have to set audioparam.value or use the methods of audioparam to change the effect of gain. methods no specific method; inherits methods from its parent, audionode. ...
...gain to apply. you have to set audioparam.value or use the methods of audioparam to change the effect of gain. methods no specific method; inherits methods from its parent, audionode. example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value. ...
... mute.onclick = voicemute; function voicemute() { if(mute.id == "") { // 0 means mute. if you still hear something, make sure you haven't // connected your source into the output in addition to usin...
GamepadButton - Web APIs
a gamepadbutton object is returned by querying any value of the array returned by the buttons property of the gamepad interface. note: this is the case in firefox gecko 28 and later; chrome and earlier firefox versions still return an array of double values when this property is accessed. properties gamepadbutton.value read only a double value used to represent the current state of analog buttons, such as the triggers on many modern gamepads. ...
...o represent the current state of analog buttons, such as the triggers on many modern gamepads. the values are normalized to the range 0.0 —1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed. gamepadbutton.pressed read only a boolean value indicating whether the button is currently pressed (true) or unpressed (false). ...
...mepads needs a webkit prefix and the button values are stored as an array of double values, whereas in firefox navigator.getgamepads doesn't need a prefix, and the button values are stored as an array of gamepadbutton objects; it is the gamepadbutton.value or gamepadbutton.pressed properties of these we need to access, depending on what type of buttons they are. in this simple example i've just allowed either. function gameloop() { if(navigator.webkitgetgamepads) { var gp = navigator.webkitgetgamepads()[0]; if(gp.buttons[0] == 1) { b--; } else if(gp.buttons[1] == 1) { a++; } else if(gp.buttons[2] == 1) { b++; } else if(gp.buttons[3] == 1) { a--; } } else { var gp = navigator.getgamepads()[0]; if(gp.buttons[0].value > 0 || gp.butto...
Geolocation API - Web APIs
concepts and usage you will often want to retrieve a user's location information in your web app, for example to plot their location on a map, or display personalized information relevant to their location. ...
... concepts and usage you will often want to retrieve a user's location information in your web app, for example to plot their location on a map, or display personalized information relevant to their location. ...
...ide an error callback, and contains an error code and message. navigator.geolocation the entry point into the api. returns a geolocation object instance, from which all other functionality can be accessed. dictionaries positionoptions represents an object containing options to pass in as a parameter of geolocation.getcurrentposition() and geolocation.watchposition(). examples in the following example the geolocation api is used to retrieve the user's latitude and longitude. if sucessful, the available hyperlink is populated with an openstreetmap.org url that will show their location. body { padding: 20px; background-color:#ffffc9 } button { margin: .5rem 0; } html <button id = "find-me">show my location</button><br/> <p id = "status"></p> <a id = "map-link" target="_bl...
GlobalEventHandlers.onmousemove - Web APIs
nmousemove property of the globaleventhandlers mixin is an eventhandler that processes mousemove events. the mousemove event fires when the user moves the mouse. syntax target.onmousemove = functionref; value functionref is a function name or a function expression. the function receives a mouseevent object as its sole argument. examples tooltips this example creates link tooltips that follow your mouse. it uses the onmousemove, onmouseover, and onmouseout event handlers. html <p><a href="#" data-tooltip="first link">see a tooltip here &hellip;</a></p> <p><a href="#" data-tooltip="second link">&hellip; or here!</a></p> css .tooltip { position: absolute; z-index: 9999; padding: 6px; background: #ffd; border: 1px #886 solid; border-radius: 5px; } javascript const toolt...
... data-tooltip="second link">&hellip; or here!</a></p> css .tooltip { position: absolute; z-index: 9999; padding: 6px; background: #ffd; border: 1px #886 solid; border-radius: 5px; } javascript const tooltip = new (function() { const node = document.createelement('div'); node.classname = 'tooltip'; node.setattribute('hidden', ''); document.body.appendchild(node); this.follow = function(event) { node.style.left = event.clientx + 20 + 'px'; node.style.top = event.clienty + 10 + 'px'; }; this.show = function(event) { node.textcontent = event.target.dataset.tooltip; node.removeattribute('hidden'); }; this.hide = function() { node.setattribute('hidden', ''); }; })(); const links = document.queryselectorall('a'); links.foreach(link => { ...
... specifications specification status comment html living standardthe definition of 'onmousemove' in that specification. living standard ...
HTMLAnchorElement - Web APIs
d those of the regular htmlelement object interface that they inherit from) for manipulating the layout and presentation of such elements. ...
...ils.href, though it can't be used to modify the value. the blur() and focus() methods are inherited from htmlelement from html5 on, but were defined on htmlanchorelement in dom level 2 html and earlier specifications. specifications specification status comment html living standardthe definition of 'htmlanchorelement' in that specification. living standard the following property has been added: download. technically, the url-related properties, media, host, hostname, pathname, port, protocol, search, and hash, have been moved to the htmlhyperlinkelementutils mixin, and htmlanchorelement implements this mixin. html5the definition of 'htmlanchorelement' in that specification. recommendation the methods blur() and focus(), as well as the prope...
...roperties, media, host, hostname, pathname, port, protocol, search, and hash, have been moved to the htmlhyperlinkelementutils mixin, and htmlanchorelement implements this mixin. html5the definition of 'htmlanchorelement' in that specification. recommendation the methods blur() and focus(), as well as the properties tabindex and accesskey, are now defined on htmlelement. the following properties are now obsolete: charset, coords, name, rev, and shape. the following properties have been added: hash, host, hostname, media, pathname, port, protocol, rellist, search, and text. document object model (dom) level 2 html specificationthe definition of 'htmlanchorelement' in that specification. obsolete no change from document object model (dom) level 1 specificat...
HTMLAreaElement - Web APIs
the htmlareaelement interface provides special properties and methods (beyond those of the regular object htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of <area> elements. ...
...ements those from htmlhyperlinkelementutils. htmlhyperlinkelementutils.tostring() returns a usvstring containing the whole url of the script executed in the worker. it is a synonym for htmlhyperlinkelementutils.href. specifications specification status comment html living standardthe definition of 'htmlareaelement' in that specification. living standard the following property has been added: download. technically, the url-related properties, media, host, hostname, pathname, port, protocol, search, and hash, have been moving to the htmlhyperlinkelementutils mixin, and htmlareaelement implements this mixin. html5the definition of 'htmlareaelement' in that specification. recommendation technically, the properties tabindex and accesskey are ...
... technically, the url-related properties, media, host, hostname, pathname, port, protocol, search, and hash, have been moving to the htmlhyperlinkelementutils mixin, and htmlareaelement implements this mixin. html5the definition of 'htmlareaelement' in that specification. recommendation technically, the properties tabindex and accesskey are now defined on htmlelement. the following property is now obsolete: nohref. the following properties have been added: rel, rellist, media, hreflang, type, host, hostname, pathname, port, protocol, search, and hash. document object model (dom) level 2 html specificationthe definition of 'htmlareaelement' in that specification. obsolete no change from document object model (dom) level 1 specification. documen...
HTMLCanvasElement.getContext() - Web APIs
an that hints the user agent to reduce the latency by desynchronizing the canvas paint cycle from the event loop antialias: boolean that indicates whether or not to perform anti-aliasing. depth: boolean that indicates that the drawing buffer has a depth buffer of at least 16 bits. ...
... premultipliedalpha: boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. preservedrawingbuffer: if the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author. ...
...ntext2d for "2d", webglrenderingcontext for "webgl" and "experimental-webgl", webgl2renderingcontext for "webgl2" or imagebitmaprenderingcontext for "bitmaprenderer". if the contexttype doesn't match a possible drawing context, null is returned. examples given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> you can get a 2d context of the canvas with the following code: var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); console.log(ctx); // canvasrenderingcontext2d { ... } now you have the 2d rendering context for a canvas and you can draw within it. specifications specification status comment html living standardthe definition of 'htmlcanvaselement.getcontext' in that specification. living...
HTMLCanvasElement.toBlob() - Web APIs
0 are used for image/jpeg and image/webp respectively. other arguments are ignored. return value none. exceptions securityerror the canvas's bitmap is not origin clean; at least some of its contents come from secure examples getting a file representing the canvas once you have drawn content into a canvas, you can convert it into a file of any supported image format. the code snippet below, for example, takes the image in the <canvas> element whose id is "canvas", obtains a copy of it as a png image, then appends a new <img> element to the document, whose source image is the one created using the canvas. var canvas = document.getelementbyid('canvas'); canvas.toblob(function(blob) { var newimg = document.createelement('img'), url = url.createobjecturl(blob); newimg.onlo...
...ting from png to ico, so it uses bmp instead. a download link is created by setting the download attribute. the value of the download attribute is the name it will use as the file name. ...
... with os.file (chrome/add-on context only) this technique saves it to the desktop and is only useful in firefox chrome context or add-on code as os apis are not present on web sites. var canvas = document.getelementbyid('canvas'); var d = canvas.width; ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(d / 2, 0); ctx.lineto(d, d); ctx.lineto(0, d); ctx.closepath(); ctx.fillstyle = 'yellow'; ctx.fill(); function blobcallback(iconname) { return function(b) { var r = new filereader(); r.onloadend = function () { // r.result contains the arraybuffer. cu.import('resource://gre/modules/osfile.jsm'); var writepath = os.path.join(os.constants.path.desktopdir, iconname + '.ico'); var promise = os.file.writeatomic(writepath, new ui...
HTMLDialogElement - Web APIs
the htmldialogelement interface provides methods to manipulate <dialog> elements. it inherits properties and methods from the htmlelement interface. ...
...available for interaction. htmldialogelement.returnvalue a domstring that sets or returns the return value for the dialog. methods inherits methods from its parent, htmlelement. htmldialogelement.close() closes the dialog. an optional domstring may be passed as an argument, updating the returnvalue of the the dialog. htmldialogelement.show() displays the dialog modelessly, i.e. ...
...from there you can click the cancel button to close the dialog (via the htmldialogelement.close() function), or submit the form via the submit button. ...
HTMLElement.hidden - Web APIs
nk you message that is displayed after a user agrees to an unusual request. javascript document.getelementbyid("okbutton") .addeventlistener("click", function() { document.getelementbyid("welcome").hidden = true; document.getelementbyid("awesome").hidden = false; }, false); this code sets up a handler for the welcome panel's "ok" button that hides the welcome panel and makes the follow-up panel—with the curious name "awesome"—visible in its place. html the html for the two boxes are shown here. the welcome panel <div id="welcome" class="panel"> <h1>welcome to foobar.com!</h1> <p>by clicking "ok" you agree to be awesome every day!</p> <button class="button" id="okbutton">ok</button> </div> this html creates a panel (in a <div> block) that welcomes the user to a si...
... html for the two boxes are shown here. the welcome panel <div id="welcome" class="panel"> <h1>welcome to foobar.com!</h1> <p>by clicking "ok" you agree to be awesome every day!</p> <button class="button" id="okbutton">ok</button> </div> this html creates a panel (in a <div> block) that welcomes the user to a site and tells them what they're agreeing to by clicking the ok button. ...
...ome every day!</p> <button class="button" id="okbutton">ok</button> </div> this html creates a panel (in a <div> block) that welcomes the user to a site and tells them what they're agreeing to by clicking the ok button. the follow-up panel once the user clicks the "ok" button in the welcome panel, the javascript code swaps the two panels by changing their respective values for hidden. the follow-up panel looks like this in html: <div id="awesome" class="panel" hidden> <h1>thanks!</h1> <p>thank you <strong>so</strong> much for agreeing to be awesome today! now get out there and do awesome things awesomely to make the world more awesome!</p> </div> css the content is styled using the css below. .panel { font: 16px "open sans", helvetica, arial, sans-serif; border: 1px solid...
HTMLHyperlinkElementUtils - Web APIs
htmlhyperlinkelementutils.protocol this is a usvstring containing the protocol scheme of the url, including the final ':'. ...
... htmlhyperlinkelementutils.protocol this is a usvstring containing the protocol scheme of the url, including the final ':'. ...
...ause it was not specified or because it was specified to be the default port of the url's scheme), a ':', and the port of the url. htmlhyperlinkelementutils.hostname this is a usvstring containing the domain of the url. htmlhyperlinkelementutils.port this is a usvstring containing the port number of the url. htmlhyperlinkelementutils.pathname this is a usvstring containing an initial '/' followed by the path of the url. htmlhyperlinkelementutils.search this is a usvstring containing a '?' followed by the parameters of the url. htmlhyperlinkelementutils.hash this is a usvstring containing a '#' followed by the fragment identifier of the url. htmlhyperlinkelementutils.username this is a usvstring containing the username specified before the domain name. htmlhyperlinkelementutils.pa...
HTMLImageElement.x - Web APIs
er <col> or <colgroup>. syntax let imagex = htmlimageelement.x; value an integer value indicating the distance in pixels from the left edge of the element's nearest root element and the left edge of the <img> element's border box. the nearest root element is the outermost <html> element that contains the image. if the image is in an <iframe>, its x is relative to that frame. in the diagram below, the left border edge is the left edge of the blue padding area. so the value returned by x would be the distance from that point to the left edge of the content area. note: the x property is only valid if the computed value of the image's display property is either table-column or table-column-group; in other words, either of those are set directly on the <img> or they're inherited from a co...
... that point to the left edge of the content area. note: the x property is only valid if the computed value of the image's display property is either table-column or table-column-group; in other words, either of those are set directly on the <img> or they're inherited from a containing element or by being located within a column described by either <col> or <colgroup>. example the example below demonstrates the use of the htmlimageelement properties x and y. html in this example, we see a table showing information about users of a web site, including their user id, their full name, and their avatar image. <table id="userinfo"> <colgroup> <col span="2" class="group1"> <col> </colgroup> <tr> <th>userid</th> <th>name</th> <th>avatar</th> </tr> <tr> <td>...
..."2" class="group1"> <col> </colgroup> <tr> <th>userid</th> <th>name</th> <th>avatar</th> </tr> <tr> <td>12345678</td> <td>johnny rocket</td> <td><img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre> javascript the javascript code that fetches the image from the table and looks up its x and y values is below. let logbox = document.queryselector("pre"); let tbl = document.getelementbyid("userinfo") let log = msg => { logbox.innerhtml += `${msg}<br>`; } let cell = tbl.rows[1].cells[2]; let image = cell.queryselector("img"); log(`image's global x: ${image.x}`); log(`image's global y: ${image.y}`); this uses the <table>'s rows property to get a list of the rows in the table, from which it looks up...
HTMLImageElement.y - Web APIs
ither <col> or <colgroup>. syntax let imagey = htmlimageelement.y; value an integer value indicating the distance in pixels from the top edge of the element's nearest root element to the top edge of the <img> element's border box. the nearest root element is the outermost <html> element that contains the image. if the image is in an <iframe>, its y is relative to that frame. in the diagram below, the top border edge is the top edge of the blue padding area. so the value returned by y would be the distance from that point to the top edge of the content area. note: the y property is only valid if the computed value of the image's display property is either table-column or table-column-group; in other words, either of those are set directly on the <img> or they're inherited from a conta...
...m that point to the top edge of the content area. note: the y property is only valid if the computed value of the image's display property is either table-column or table-column-group; in other words, either of those are set directly on the <img> or they're inherited from a containing element or by being located within a column described by either <col> or <colgroup>. example the example below demonstrates the use of the htmlimageelement properties x and y. html in this example, we see a table showing information about users of a web site, including their user id, their full name, and their avatar image. <table id="userinfo"> <colgroup> <col span="2" class="group1"> <col> </colgroup> <tr> <th>userid</th> <th>name</th> <th>avatar</th> </tr> <tr> <td>...
..."2" class="group1"> <col> </colgroup> <tr> <th>userid</th> <th>name</th> <th>avatar</th> </tr> <tr> <td>12345678</td> <td>johnny rocket</td> <td><img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre> javascript the javascript code that fetches the image from the table and looks up its x and y values is below. let logbox = document.queryselector("pre"); let tbl = document.getelementbyid("userinfo") let log = msg => { logbox.innerhtml += `${msg}<br>`; } let cell = tbl.rows[1].cells[2]; let image = cell.queryselector("img"); log(`image's global x: ${image.x}`); log(`image's global y: ${image.y}`); this uses the <table>'s rows property to get a list of the rows in the table, from which it looks up...
HTMLInputElement.stepDown() - Web APIs
tep="7"> <!-- 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...
... set to any, an invalidstateerror exception is thrown. htmlinputelement.stepdown() decrements the value by (step * n), where n defaults to 1 if not specified. throws an invalid_state_err exception: if the method is not applicable to for the current type value, if the element has no step value, if the value cannot be converted to a number, if the resulting value is above the max or below the min. syntax element.stepdown( [ stepdecrement ] ); parameters stepdecrement the optional stepdecrement paremeter is a numeric value. if no parameter is passed, stepdecrement defaults to 1. if the value is a float, the value will increment as if math.floor(stepdecrement) was passed. if the value is negative, the value will be incremented instead of decremented. exa...
... } } css input:invalid { border: red solid 3px; } result note if you don't pass a parameter to the stepdown() method, it defaults to 1. any other value is a multiplier of the step attribute value, which in this case is 5. if we pass 4 as the stepdecrement, the input will stepdown by 4 * 5, or 20. if the parameter is 0, the number will not be decremented. the stepdown() method will not allow the input to go out of range, in this case stopping when it reaches 0 and rounding down and floats that are passed as a parameter. try setting the step decrementer to 1.2. what happens when you invoke the method? try setting the value to 44, which is not valid. what happens when you invoke the method? specifications specification status comment html living standard...
HTMLLegendElement - Web APIs
the htmllegendelement is an interface allowing to access properties of the <legend> elements. it inherits properties and methods from the htmlelement interface. ...
... the htmllegendelement is an interface allowing to access properties of the <legend> elements. it inherits properties and methods from the htmlelement interface. ...
...tion status comment html living standardthe definition of 'htmllegendelement' in that specification. living standard html 5.1the definition of 'htmllegendelement' in that specification. recommendation html5the definition of 'htmllegendelement' in that specification. recommendation the property accesskey is now defined on htmlelement. the following property is now obsolete: align. document object model (dom) level 2 html specificationthe definition of 'htmllegendelement' in that specification. obsolete no change from document object model (dom) level 1 specification. document object model (dom) level 1 specificationthe definition of 'htmllegendelement' in that specification. obsolete initial definition. ...
HTMLMediaElement.play() - Web APIs
return value a promise which is resolved when playback has been started, or is rejected if for any reason playback cannot be started. note: older browsers may not return a value from play(). exceptions the promise's rejection handler is called with an exception name passed in as its sole input parameter (as opposed to a traditional exception being thrown). possible errors include: notallowederror the user agent (browser) or operating system doesn't allow playback of media in the current context or situation. this may happen, for example, if the browser requires the user to explicitly start media playback by clicking a "play" button. notsupportederror the media source (which may be specified as a mediastream, mediasource, blob, or file, for example) doesn't represent a supported ...
... be reported, depending on browser implementation details, media player implementation, and so forth. usage notes although the term "autoplay" is usually thought of as referring to pages that immediately begin playing media upon being loaded, web browsers' autoplay policies also apply to any script-initiated playback of media, including calls to play(). if the user agent is configured not to allow automatic or script-initiated playback of media, calling play() will cause the returned promise to be immediately rejected with a notallowederror. web sites should be prepared to handle this situation. for example, a site should not present a user interface that assumes playback has begun automatically, but should instead update their ui based on whether the returned promise is resolved or reject...
... note: the play() method may cause the user to be asked to grant permission to play the media, resulting in a possible delay before the returned promise is resolved. be sure your code doesn't expect an immediate response. ...
HTMLMediaElement.playbackRate - Web APIs
the pitch of the audio is corrected by default and is the same for every speed. ...
... the pitch of the audio is corrected by default and is the same for every speed. ...
...utside a useful range (for example, gecko mutes the sound outside the range 0.25 to 5.0). the pitch of the audio is corrected by default and is the same for every speed. some browsers implement the non-standard htmlmediaelement.preservespitch property to control this. syntax // video video.playbackrate = 1.5; // audio audio.playbackrate = 1.0; value a double. 1.0 is "normal speed," values lower than 1.0 make the media play slower than normal, higher values make it play faster. (default: 1.0) example var obj = document.createelement('video'); console.log(obj.playbackrate); // expected output: 1 specifications specification status comment html living standardthe definition of 'htmlmediaelement.playbackrate' in that specification. living standard ...
HTMLMediaElement - Web APIs
the htmlmediaelement interface adds to htmlelement the properties and methods needed to support basic media-related capabilities that are common to audio and video. the htmlvideoelement and htmlaudioelement elements both inherit this interface. ...
...iaelement.defaultmuted a boolean that reflects the muted html attribute, which indicates whether the media element's audio output should be muted by default. htmlmediaelement.defaultplaybackrate a double indicating the default playback rate for the media. htmlmediaelement.disableremoteplayback a boolean that sets or returns the remote playback state, indicating whether the media element is allowed to have a remote playback ui. htmlmediaelement.duration read only a read-only double-precision floating-point value indicating the total duration of the media in seconds. if no media data is available, the returned value is nan. if the media is of indefinite length (such as streamed live media, a webrtc call's media, or similar), the value is +infinity. htmlmediaelement.ended read only re...
... duration. htmlmediaelement.mozframebufferlength is a unsigned long that indicates the number of samples that will be returned in the framebuffer of each mozaudioavailable event. this number is a total for all channels, and by default is set to be the number of channels * 1024 (e.g., 2 channels * 1024 samples = 2048 total). the mozframebufferlength property can be set to a new value for lower latency, larger amounts of data, etc. the size given must be a number between 512 and 16384. using any other size results in an exception being thrown. the best time to set a new length is after the loadedmetadata event fires, when the audio info is known, but before the audio has started or mozaudioavailable events have begun firing. htmlmediaelement.mozsamplerate read only returns a ...
HTMLOListElement - Web APIs
the htmlolistelement interface provides special properties (beyond those defined on the regular htmlelement interface it also has available to it by inheritance) for manipulating ordered list elements. ...
...lue reflecting the reversed and defining if the numbering is descending, that is its value is true, or ascending (false). htmlolistelement.start is a long value reflecting the start and defining the value of the first number of the first element of the list. htmlolistelement.type is a domstring value reflecting the type and defining the kind of marker to be used to display. ...
...scending (false). htmlolistelement.start is a long value reflecting the start and defining the value of the first number of the first element of the list. htmlolistelement.type is a domstring value reflecting the type and defining the kind of marker to be used to display. it can have the following values: '1' meaning that decimal numbers are used: 1, 2, 3, 4, 5, … 'a' meaning that the lowercase latin alphabet is used: a, b, c, d, e, … 'a' meaning that the uppercase latin alphabet is used: a, b, c, d, e, … 'i' meaning that the lowercase latin numerals are used: i, ii, iii, iv, v, … 'i' meaning that the uppercase latin numerals are used: i, ii, iii, iv, v, … htmlolistelement.compact is a boolean indicating that spacing between list items should be reduced. thi...
HTMLOptionsCollection - Web APIs
represents a collection of <option> html elements (in document order) and offers methods and properties for selecting from the list as well as optionally altering its items. this object is returned only by the options property of select. ...
... methods this interface inherits the methods of its parent, htmlcollection. specifications specification status comment ...
...naco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmloptionscollection</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties name type description length unsigned long as optionally allowed by the spec, this property isn't read-only. you can either remove options from the end by lowering the value, or add blank options at the end by raising the value. mozilla allows this, while other implementations could potentially throw a domexception. methods this interface inherits the methods of its parent, htmlcollection. specifications specification status comment html living standardthe definition of 'htmloptionscollection' in that specification...
HTMLOrForeignElement.dataset - Web APIs
not directly written. instead, all writes must be to the individual properties within the dataset, which in turn represent the data attributes. note also that an html data-attribute and its corresponding dom dataset.property do not share the same name, but they are always similar: in html, the name of a custom data attribute begins with data-. it must contain only letters, numbers, and the following characters: dash (-), dot (.), colon (:), underscore (_)—but not any ascii capital letters (a to z). in javascript, the name of a custom data attribute is the name of the same html attribute, but in camelcase and with no dashes, dots, etc. in addition to the information below, you'll find a how-to guide for using html data attributes in our article using data attributes. name conversion ...
...f a custom data attribute is the name of the same html attribute, but in camelcase and with no dashes, dots, etc. in addition to the information below, you'll find a how-to guide for using html data attributes in our article using data attributes. name conversion dash-style to camelcase conversion a custom data attribute name is transformed to a key for the domstringmap entry with the following rules the prefix data- is removed (including the dash); for any dash (u+002d) followed by an ascii lowercase letter a to z, the dash is removed, and the letter is transformed into its uppercase counterpart; other characters (including other dashes) are left unchanged. camelcase to dash-style conversion the opposite transformation, which maps a key to an attribute name, uses th...
...ules the prefix data- is removed (including the dash); for any dash (u+002d) followed by an ascii lowercase letter a to z, the dash is removed, and the letter is transformed into its uppercase counterpart; other characters (including other dashes) are left unchanged. camelcase to dash-style conversion the opposite transformation, which maps a key to an attribute name, uses the following rules: restriction: before the transformation, a dash must not be immediately followed by an ascii lowercase letter a to z; the prefix data- is added; any ascii uppercase letter a to z is transformed into a dash, followed by its lowercase counterpart; other characters are left unchanged. the restriction in the rules above ensures that the two transformations are the inverse on...
HTMLScriptElement - Web APIs
ut browsers are lenient and block them only if the script is served with an image type (image/*), video type (video/*), audio type (audio/*), or text/csv. if the script is blocked, its element receives an error event; otherwise, it receives a load event. ...
...t reflects the referrerpolicy html attribute indicating which referrer to use when fetching the script, and fetches done by that script. methods no specific methods; inherits methods from its parent, htmlelement. examples dynamically importing scripts let's create a function that imports new scripts within a document creating a <script> node immediately before the <script> that hosts the following code (through document.currentscript). these scripts will be asynchronously executed. for more details, see the defer and async properties. function loaderror(oerror) { throw new urierror("the script " + oerror.target.src + " didn't load correctly."); } function prefixscript(url, onloadfunction) { var newscript = document.createelement("script"); newscript.onerror = loaderror; if (on...
...rrectly loaded."); }); specifications specification status comment html living standardthe definition of 'htmlscriptelement' in that specification. living standard html 5.1the definition of 'htmlscriptelement' in that specification. recommendation html5the definition of 'htmlscriptelement' in that specification. recommendation the following properties are now obsolete: htmlfor,. document object model (dom) level 2 html specificationthe definition of 'htmlscriptelement' in that specification. obsolete no change from document object model (dom) level 1 specification. document object model (dom) level 1 specificationthe definition of 'htmlscriptelement' in that specification. obsolete initial definition...
HTMLStyleElement - Web APIs
the htmlstyleelement interface represents a <style> element. it inherits properties and methods from its parent, htmlelement, and from linkstyle. this interface doesn't allow to manipulate the css it contains (in most case). to manipulate css, see using dynamic styling information for an overview of the objects used to manipulate specified css properties using the dom. ...
...lement, and from linkstyle. this interface doesn't allow to manipulate the css it contains (in most case). to manipulate css, see using dynamic styling information for an overview of the objects used to manipulate specified css properties using the dom. ...
...element, and linkstyle. specifications specification status comment html living standardthe definition of 'htmlstyleelement' in that specification. living standard html 5.1the definition of 'htmlstyleelement' in that specification. recommendation html5the definition of 'htmlstyleelement' in that specification. recommendation the following property has been added: scoped. document object model (dom) level 2 html specificationthe definition of 'htmlstyleelement' in that specification. obsolete added a second inheritence, the linkstyle interface. document object model (dom) level 1 specificationthe definition of 'htmlstyleelement' in that specification. obsolete initial definition ...
HTMLTableElement - Web APIs
the htmltableelement interface provides special properties and methods (beyond the regular htmlelement object interface it also has available to it by inheritance) for manipulating the layout and presentation of tables in an html document. ...
...ree order, and those members of a <tbody> last, also in tree order. the htmlcollection is live and is automatically updated when the htmltableelement changes. htmltableelement.tbodiesread only returns a live htmlcollection containing all the <tbody> of the element. the htmlcollection is live and is automatically updated when the htmltableelement changes. obsolete properties warning: the following properties are obsolete. you should avoid using them. htmltableelement.align is a domstring containing an enumerated value reflecting the align attribute. it indicates the alignment of the element's contents with respect to the surrounding context. the possible values are "left", "right", and "center". htmltableelement.bgcolor is a domstring containing the background color of the ...
...it reflects the obsolete cellpadding attribute. htmltableelement.cellspacing is a domstring containing the width in pixels of the horizontal and vertical separation between cells. it reflects the obsolete cellspacing attribute. htmltableelement.frame is a domstring containing the type of the external borders of the table. it reflects the obsolete frame attribute and can take one of the following values: "void", "above", "below", "hsides", "vsides", "lhs", "rhs", "box", or "border". htmltableelement.rules is a domstring containing the type of the internal borders of the table. it reflects the obsolete rules attribute and can take one of the following values: "none", "groups", "rows", "cols", or "all". htmltableelement.summary is a domstring containing a description of the purpo...
HTMLTimeElement.dateTime - Web APIs
the htmltimeelement.datetime property is a domstring that reflects the datetime html attribute, containing a machine-readable form of the element's date and time value. ...
... the htmltimeelement.datetime property is a domstring that reflects the datetime html attribute, containing a machine-readable form of the element's date and time value. ...
...mm-ddthh:mm:ss.mmm 2013-12-25 11:12 1972-07-25 13:43:07 1941-03-15 07:06:23.678 2013-12-25t11:12 1972-07-25t13:43:07 1941-03-15t07:06:23.678 valid time-zone offset string z +hhmm +hh:mm -hhmm -hh:mm z +0200 +04:30 -0300 -08:00 valid global date and time string any combination of a valid local date and time string followed by a valid time-zone offset string 2013-12-25 11:12+0200 1972-07-25 13:43:07+04:30 1941-03-15 07:06:23.678z 2013-12-25t11:12-08:00 valid week string yyyy-www 2013-w46 four or more ascii digits yyyy 2013, 0001 valid duration string pddthhmmss pddthhmms.xs pddthhmms.xxs pddthhmms.xxxs pthhmmss pthhmms.xs pthhmms.xxs ...
The HTML DOM API - Web APIs
ment 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 been further adapted to represent html elements specifically by introducing the htmlelement interface, which all more specific ht...
...text. htmlelement also adds all the global event handlers. an html document is a dom tree in which each of the nodes is an html element, represented by the htmlelement interface. the htmlelement class, in turn, implements node, so every element is also a node (but not the other way around). this way, the structural features implemented by the node interface are also available to html elements, allowing them to be nested within each other, created and deleted, moved around, and so forth. the htmlelement interface is generic, however, providing only the functionality common to all html elements such as the element's id, its coordinates, the html making up the element, information about scroll position, and so forth. in order to expand upon the functionality of the core htmlelement interface ...
... the length of the current value of the input; if it's zero, then the "send" button is disabled if it's not already disabled. otherwise, the code ensures that the button is enabled. with this in place, the "send" button is always enabled whenever the user name input field has a value, and disabled when it's empty. html the html for the form looks like this: <p>please provide the information below. items marked with "*" are required.</p> <form action="" method="get"> <p> <label for="username" required>your name:</label> <input type="text" id="username"> (*) </p> <p> <label for="email">email:</label> <input type="email" id="useremail"> </p> <input type="submit" value="send" id="sendbutton"> </form> result specifications specification status com...
IDBCursorSync - Web APIs
ber of objects that share the current key. direction readonly unsigned short the direction of traversal of the cursor. see constants for possible values. key readonly any the key for the record at the cursor's position. value any the value for the record at the cursor's position. ...
... readonly any the key for the record at the cursor's position. value any the value for the record at the cursor's position. setting this attribute can raise an idbdatabaseexception with the following codes: data_err if the underlying object store uses in-line keys and the property at the key path does not match the key in this cursor's position. not_allowed_err if the underlying index or object store does not support updating the record because it is open in the read_only or snapshot_read mode, or if an index record cannot be changed because the underlying index is auto-populated. serial_err if the data being stored could not be serialized by the internal structured cloning algorithm. constants constant ...
...lse if the cursor has reached the end of its range; otherwise returns true. bool continue ( in optional any key ); parameters key the key to which to move the cursor's position. remove() deletes the record at the cursor's position, without changing the cursor's position void delete ( ) raises (databaseexception); exceptions this method can raise an idbdatabaseexception with the following code: not_allowed_err if the underlying index or object store does not support updating the record because it is open in the read_only or snapshot_read mode. ...
IDBDatabase - Web APIs
ns with data in the database. all objects in indexeddb — including object stores, indexes, and cursors — are tied to a particular transaction. thus, you cannot execute commands, access data, or open anything outside of a transaction. ...
...st created, this attribute is an empty string. idbdatabase.objectstorenames read only a domstringlist that contains a list of the names of the object stores currently in the connected database. methods inherits from: eventtarget idbdatabase.close() returns immediately and closes the connection to a database in a separate thread. idbdatabase.createmutablefile() creates a file handle, allowing files to be stored inside an indexeddb database. idbdatabase.createobjectstore() creates and returns a new object store or index. idbdatabase.deleteobjectstore() destroys the object store with the given name in the connected database, along with any indexes that reference it. idbdatabase.transaction() immediately returns a transaction object (idbtransaction) containing the idbtransaction...
...ort property. close fired when the database connection is unexpectedly closed. also available via the onclose property. error fired when a request returns an error and the event bubbles up to the connection object. also available via the onerror property. versionchange fired when a database structure change was requested. also available via the onversionchange property. example in the following code snippet, we open a database asynchronously (idbfactory), handle success and error cases, and create a new object store in the case that an upgrade is needed (idbdatabase). for a complete working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the idbdata...
IDBObjectStore.autoIncrement - Web APIs
for this object store. note that every object store has its own separate auto increment counter. note: this feature is available in web workers. syntax var myautoincrement = objectstore.autoincrement; value a boolean: value meaning true the object store auto increments. false the object store does not auto increment. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add(). after the object store has been created, we log objectstore.autoincrement to the console. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess ...
...jectstore.autoincrement to the console. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...r adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBObjectStore.clear() - Web APIs
indexes that reference the object store. to remove only some of the records in a store, use idbobjectstore.delete passing a key or idbkeyrange. note: this feature is available in web workers. syntax var request = objectstore.clear(); returns an idbrequest object on which subsequent events related to this operation are fired. ...
...ject on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description readonlyerror the transaction associated with this operation is in read-only mode. transactioninactiveerror this idbobjectstore's transaction is inactive. example in the following code snippet, we open a read/write transaction on our database and clear all the current data out of the object store using clear(). for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li...
... out of the object store using clear(). for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBObjectStore.deleteIndex() - Web APIs
called only from a versionchange transaction mode callback. note that this method synchronously modifies the idbobjectstore.indexnames property. note: this feature is available in web workers. syntax objectstore.deleteindex(indexname); parameters indexname the name of the existing index to remove. return value undefined exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror occurs if the method was not called from a versionchange transaction mode callback. transactioninactiveerror occurs if the transaction this idbobjectstore belongs to is not active (e.g. has been deleted or removed.) in firefox previous to version 41, an invalidstateerror was raised in this case as well, whi...
...ccurs if the transaction this idbobjectstore belongs to is not active (e.g. has been deleted or removed.) in firefox previous to version 41, an invalidstateerror was raised in this case as well, which was misleading; this has now been fixed (see bug 1176165.) notfounderror occurs if there is no index with the given name (case-sensitive) in the database. example in the following example you can see the idbopendbrequest.onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. idbobjectstore.createindex is used to create new indexes on the object store, after which we delete the unneeded old indexes with deleteindex(). for a full working example, see our to-do notifications app (view example live.) var d...
...dexeddb.open("todolist", 4); // these two event handlers act on the database being opened successfully, or not dbopenrequest.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBObjectStore.get() - Web APIs
if the record exists, and no cursor if it does not. note: this feature is available in web workers. syntax var request = objectstore.get(key); parameters key the key or key range that identifies the record to be retrieved. return value an idbrequest object on which subsequent events related to this operation are fired. ...
...once this data object is retrieved, you could then update it using normal javascript, then put it back into the database using a idbobjectstore.put operation. ...
... using a idbobjectstore.put operation. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBObjectStore.indexNames - Web APIs
after the object store has been created, we log objectstore.indexnames to the console. ...
... objectstore.indexnames to the console. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...or adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBObjectStore.keyPath - Web APIs
the keypath read-only property of the idbobjectstore interface returns the key path of this object store. if this property is null, the application must provide a key for each modification operation. note: this feature is available in web workers. syntax var mykeypath = objectstore.keypath; value any value type. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add(). after the object store has been created, we log objectstore.keypath to the console. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialis...
...log objectstore.keypath to the console. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBObjectStore.name - Web APIs
object store's name. invalidstateerror either the object store has been deleted or the current transaction is not an upgrade transaction; you can only rename indexes during upgrade transactions; that is, when the mode is "versionchange". transactioninactiveerror the current transaction is not active. constrainterror an object store is already using the specified name. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add(). after the object store has been created, we log objectstore.name to the console. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = functio...
...we log objectstore.name to the console. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBObjectStore.transaction - Web APIs
after the object store has been created, we log objectstore.transaction to the console. ...
...objectstore.transaction to the console. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...r adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBOpenDBRequest - Web APIs
dexeddb api provides access to the results of requests to open or delete databases (performed using idbfactory.open and idbfactory.deletedatabase), using specific event handler attributes. note: this feature is available in web workers. ...
... to the oneventname property of this interface. blocked fired when an open connection to a database is blocking a versionchange transaction on the same database. also available via the onblocked property. upgradeneeded fired when an attempt was made to open a database with a version number higher than its current version. also available via the onupgradeneeded property. example in the following example you can see the onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these event handlers act on the database being opened. dbopenrequest.
...request = window.indexeddb.open("todolist", 4); // these event handlers act on the database being opened. dbopenrequest.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db // variable. ...
IDBRequest.error - Web APIs
Web › API › IDBRequest › error
the error read-only property of the idbrequest interface returns the error in the event of an unsuccessful request. note: this feature is available in web workers. syntax var myerror = request.error; value a domerror containing the relevant error. in chrome 48+/firefox 58+ this property returns a domexception because domerror has been removed from the dom standard. the following error codes are returned under certain conditions: error explanation aborterror if you abort the transaction, then all requests still in progress receive this error. constrainterror if you insert data that doesn't conform to a constraint. it's an exception type for creating stores and indexes. you get this error, for example, if you try to add a new key that already exi...
... already exists in the record. quotaexceedederror if you run out of disk quota and the user declined to grant you more space. unknownerror if the operation failed for reasons unrelated to the database itself. a failure due to disk io errors is such an example. noerror if the request succeeds. versionerror if you try to open a database with a version lower than the one it already has. in addition to the error codes sent to the idbrequest object, asynchronous operations can also raise exceptions. the list describes problems that could occur when the request is being executed, but you might also encounter other problems when the request is being made. for example, if the the request failed and the result is not available, the invalidstateerr...
... addition to the error codes sent to the idbrequest object, asynchronous operations can also raise exceptions. the list describes problems that could occur when the request is being executed, but you might also encounter other problems when the request is being made. for example, if the the request failed and the result is not available, the invalidstateerror exception is thrown. example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store. also included at the bottom is an onerror function that reports what the error was if the request fails. for a full working example, see our to-do ...
IDBTransaction.abort() - Web APIs
the abort() method of the idbtransaction interface rolls back all the changes to objects in the database associated with this transaction. all pending idbrequest objects created during this transaction have their idbrequest.error attribute set to aborterror. note: this feature is available in web workers. syntax transaction.abort(); exceptions this method may raise a domexception of the following type: exception description invalidstateerror the transaction has already been committed or aborted. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of s...
...under the current transaction using abort(). for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...ing the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBTransaction.db - Web APIs
Web › API › IDBTransaction › db
the db read-only property of the idbtransaction interface returns the database connection with which this transaction is associated. note: this feature is available in web workers. syntax var mydatabase = transaction.db; value an idbdatabase object. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. at the end, we return the associated database connection using db. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = func...
...ssociated database connection using db. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...ding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBTransactionSync - Web APIs
dynamic. methods abort() call this method to signal a need to cancel the effects of the operations performed by this transaction. when this method is called, the browser ignores all the changes performed to the objects of this database since this transaction was created. void abort( ) raises (idbdatabaseexception); exceptions this method can raise an idbdatabaseexception with the following code: non_transient_err if this transaction has already been committed or aborted. commit() call this method to signal that the transaction has completed normally and satisfactorily. when this method is called, the browser durably stores all the changes performed to the objects of the database since this transaction was created. void commit( ) raises (idbdatabaseexception); exception...
...dy been committed or aborted. commit() call this method to signal that the transaction has completed normally and satisfactorily. when this method is called, the browser durably stores all the changes performed to the objects of the database since this transaction was created. void commit( ) raises (idbdatabaseexception); exceptions this method can raise an idbdatabaseexception with the following codes: non_transient_err if this transaction has already been committed or aborted. recoverable_err if this transaction's scope is dynamic, and the browser cannot commit all of the changes due to another transaction. objectstore() returns an object store that has already been added to the scope of this transaction. idbobjectstoresync objectstore( in domstring name ) raises (idbdata...
...tstore() returns an object store that has already been added to the scope of this transaction. idbobjectstoresync objectstore( in domstring name ) raises (idbdatabaseexception); parameters name the name of the requested object store. returns idbobjectstoresync an object for accessing the requested object store. exceptions the method can raise an idbdatabaseexception with the following code: not_found_err if the requested object store is not in this transaction's scope. ...
Browser storage limits and eviction criteria - Web APIs
ind 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 make use of browser data storage to store data when required. we...
...sistent storage for their sites using the storagemanager.persist() method available in the storage api. where is the data stored? each storage type represents a separate repository. here's the actual mapping to directories under a user's firefox profile (other browsers may differ slightly): <profile>/storage — the main top-level directory for storages maintained by the quota manager (see below) <profile>/storage/permanent — persistent data storage repository <profile>/storage/temporary — temporary data storage repository <profile>/storage/default — default data storage repository note: after introducing storage api, the "permanent" folder can be considered obsolete; the "permanent" folder only stores indexeddb persistent-type databases. it doesn't matter if box mode is "be...
... 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 found here. lru policy when the available disk space is fi...
Checking when a deadline is due - Web APIs
adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction opened for task addition.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var request = objectstore.add(newitem[0]); in this section we create an object called newitem that stores the data in the format required to insert it into the database. the next few lines open the database transacti...
... = now.getmonth(); var yearcheck = now.getfullyear(); the date object has a number of methods to extract various parts of the date and time inside it. ...
...n leading zero equivalents, e.g. 09 -> 9. this is needed because javascript date number values never have leading zeros, but our data might. the notified == "no" check is designed to make sure you will only get one notification per to-do item. ...
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. ...
...ger 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 key produces a character key that would result in a character being inserted into po...
...his completes the process. in sequence 1 & 3, the keyboardevent.key attribute is defined and is set appropriately to a value according to the rules defined ealier. keyboardevent sequence example consider the event sequence generated when we interact with the shift and the 2 key using a u.s keyboard layout as compared to when we do so using a uk keyboard layout. try experimenting using the following two test cases: press and hold the shift key, then press 2 and release it. next, release the shift key. press and hold the shift key, then press and hold 2. release the shift key. finally, release 2. html <div class="fx"> <div> <textarea rows="5" name="test-target" id="test-target"></textarea> <button type="button" name="btn-clear-console" id="btn-clear-console">clear console<...
Keyboard API - Web APIs
the keyboardlayoutmap interface. the keyboard interface is accessed through navigator.keyboard. keyboard provides the keyboard.getlayoutmap method, which returns a promise that resolves with a keyboardlayoutmap object that contains members for converting codes to keys. a list of valid code values is found in the writing system keys section of the ui events keyboardevent code values spec. the following example demonstrates how to get the location-specific or layout-specific string associated with the key labeled w on an english qwerty keyboard. 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 somethi...
...thing 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 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"...
...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 system keys” are defined in the writing system keys section of the ui events keyboardevent code values spec as the physical keys that change meaning based on the current locale and keyboard layout. these keys are shown below. blue keys are present on all standard keyboards while green keys are only available on some keyboards. interfaces keyboard provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard. keyboardlayoutmap a map-like object with functions for retrieving the string associated with specific physical keys. navigator.keyboard read on...
KeyframeEffect.KeyframeEffect() - Web APIs
the keyframeeffect() constructor of the web animations api returns a new keyframeeffect object instance, and also allows you to clone an existing keyframe effect object instance. syntax var keyframes = new keyframeeffect(element, keyframeset, keyframeoptions); var keyframes = new keyframeeffect(sourcekeyframes); parameters the first type of constructor (see above) creates a completely new keyframeeffect object instance. its parameters are: element the dom element to be animated, or null. keyframeset an keyframe object or null. keyframeoptions optional either an integer representing the animation's duration (in milliseconds), or an object containing one or more of the following: delay optional the number of milliseconds to delay the start of the animation. defaults to ...
... 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. ...
...ed 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.setKeyframes() - Web APIs
} ], 2000); note: offset values, if provided, must be between 0.0 and 1.0 (inclusive) and arranged in ascending order. it is not necessary to specify an offset for every keyframe. keyframes without a specified offset will be evenly spaced between adjacent keyframes. the easing to apply between keyframes can be specified by providing an easing value as illustrated below. element.animate([ { opacity: 1, easing: 'ease-out' }, { opacity: 0.1, easing: 'ease-in' }, { opacity: 0 } ], 2000); in this example, the specified easing only applies from the keyframe where it is specified until the next keyframe. any easing value specified on the options argument, however, applies across a single iteration of the anima...
...imate and an array of values to iterate over. element.animate({ opacity: [ 0, 1 ], // [ from, to ] color: [ "#fff", "#000" ] // [ from, to ] }, 2000); using this format, the number of elements in each array does not need to be equal. the provided values will be spaced out independently. element.animate({ opacity: [ 0, 1 ], // offset: 0, 1 backgroundcolor: [ "red", "yellow", "green" ], // offset: 0, 0.5, 1 }, 2000); the special keys offset, easing, and composite (described below) may be specified alongside the property values. element.animate({ opacity: [ 0, 0.9, 1 ], offset: [ 0, 0.8 ], // shorthand for [ 0, 0.8, 1 ] easing: [ 'ease-in', 'ease-out' ], }, 2000); after generating a suitable set of keyframes from the property value lists, each suppli...
...rthand values such as margin are also permitted. two exceptional css properties are: float, which must be written as cssfloat since "float" is a reserved word in javascript. it's just for reference here, this will have no effect on animation since "float" is not an animatable css property. offset, which must be written as cssoffset since "offset" represents the keyframe offset as 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 use...
LargestContentfulPaint - Web APIs
nput 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 returns an empty string when there is no id. largestcontentfulpaint.url if the element is an image, the request url of the image. methods larg...
...rgestcontentfulpaint.size the intrinsic size of the element returned as the area (width * height). largestcontentfulpaint.id the id of the element. this property returns an empty string when there is no id. largestcontentfulpaint.url if the element is an image, the request url of the image. methods largestcontentfulpaint.tojson() returns the above properties as json. examples the following example shows how to create a performanceobserver that listens for largest-contentful-paint entries and logs the lcp value to the console. this example also demonstrates how to include buffered entries (those that ocurred before observer() was called), which is done by setting the buffered option to true. note that in this example data is only sent to the server when the user leaves the tab.
...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); } catc...
LocalFileSystemSync - Web APIs
this specification is more or less abandonned, failing to get significant traction. ...
...temsync requestfilesystemsync( in unsigned short type, in unsigned long long size ); parameters type the storage type of the file system. the values can be either temporary or persistent. size the storage space—in bytes—that you need for your app. returns filesystemsync an object that represents the file system. exceptions this method can raise an fileexception with the following code: exception description security_error the application does not have permission to access the file system interface. for example, you cannot run from file://. for more details, see the article on basic concepts. resolvelocalfilesystemsyncurl() allows the user to look up the entry for a file or directory referred to by a local url. void resolvelocalfilesyst...
... not_found_err the url was structurally correct, but refers to a resource that does not exist. security_err the application does not have permission to access the file system interface. ...
LockManager.request() - Web APIs
er lock with the same name can be held. request a "shared" lock when multiple instances of the code can share access to a resource. when a "shared" lock for a given name is held, other "shared" locks for the same name can be granted, but no "exclusive" locks with that name can be held or granted. this shared/exclusive lock pattern is common in database transaction architecture, for example to allow multiple simultaneous readers (each requests a "shared" lock) but only one writer (a single "exclusive" lock). this is known as the readers-writer pattern. in the indexeddb api, this is exposed as "readonly" and "readwrite" transactions which have the same semantics. syntax lockmanager.request(var promise = name[, {options}], callback) parameters name an identifier for the lock you want to...
...ranted, preempting any queued requests for it. the default value is false. signal optional: an abortsignal (the signal property of an abortcontroller); if specified and the abortcontroller is aborted, the lock request is dropped if it was not already granted. callback … return value a promise that resolves with undefined when the request is granted. ...
... notice that both functions use a lock called my_resource. the do_read() requests a lock in 'shared' mode meaning that multiple calls may occur simultaneously across different event handlers, tabs, or workers. ...
LockedFile.getMetadata() - 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. summary the getmetadata method allows to retrieve some metadata about the locked file. ...
...getmetadata method allows to retrieve some metadata about the locked file. syntax var request = instanceoflockedfile.getmetadata(param); parameters param optional an object used to request specific metadata. each key is a boolean where true means the metadata is expected and where false means it is not expected. note that if the key is undefined, it is considered as if it were true. the following metadata are supported: size : will provide the size of the file lastmodified : will provide the date when the file was last modified return a filerequest object. in case of success, the request's result is an object with the metadata requested through the param object. ...
... is not expected. note that if the key is undefined, it is considered as if it were true. the following metadata are supported: size : will provide the size of the file lastmodified : will provide the date when the file was last modified return a filerequest object. in case of success, the request's result is an object with the metadata requested through the param object. ...
MediaDevices.getDisplayMedia() - Web APIs
upported at all by the media recorder and in terms of the which audio source or sourcoes are supported. check the compatibility table for details for each browser. exceptions rejections of the returned promise are made by passing a domexception error object to the promise's failure handler. ...
... notfounderror no sources of screen video are available for capture. ...
...pted for permission every time. the call to getdisplaymedia() must be made from code which is running in response to a user action, such as in an event handler. browsers are encouraged to provide a warning to users about sharing displays or windows that contain browsers, and to keep a close eye on what other content might be getting captured and shown to other users. example in the example below, a startcapture() method is created which initiates screen capture given a set of options specified by the displaymediaoptions parameter. the options are specified in the form of a mediastreamconstraints object which specifies the preferred stream configuration and the display surface from which video is to be captured. async function startcapture(displaymediaoptions) { let capturestream = nul...
MediaDevices.ondevicechange - Web APIs
nges. it displays in the browser window two lists: one of audio devices and one of video devices, with both the device's label (name) and whether it's an input or an output device. because the example provides a handler for the devicechange event, the list is refreshed any time a media device is attached to or removed from the device running the sample. ...
... let videoelement = document.getelementbyid("video"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediad...
...device.kind.match(/(\w+)(input|output)/i); deserves special notice. this uses destructuring assignment (a new feature of ecmascript 6) to assign the values of the first three items in the array returned by string.match() to the variables kind, type, and direction. we do this because the value of mediadeviceinfo.kind is a single string that includes both the media type and the direction the media flows, such as "audioinput" or "videooutput". this line, then, pulls out the type ("audio" or "video") and direction ("input" or "output") so they can be used to construct the string displayed in the list. once the string is assembled, containing the device's name in bold and the direction in parentheses, it's appended to the appropriate list by calling appendchild() on either audiolist or videolist,...
MediaList - Web APIs
Web › API › MediaList
medialist.length read only returns the number of media queries in the medialist. ...
... medialist.length read only returns the number of media queries in the medialist. ...
...t. medialist.length read only returns the number of media queries in the medialist. methods medialist.appendmedium() adds a media query to the medialist. medialist.deletemedium() removes a media query from the medialist. medialist.item() a getter that returns a cssomstring representing a media query as text, given the media query's index value inside the medialist. examples the following would log to the console a textual representation of the medialist of the first stylesheet applied to the current document. const stylesheets = document.stylesheets; let stylesheet = stylesheets[0]; console.log(stylesheet.media.mediatext); specifications specification status comment css object model (cssom)the definition of 'medialist' in that specification. worki...
MediaRecorder.onerror - Web APIs
ccur while creating or using a media recorder. the error object is of type mediarecordererrorevent, 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 m...
...ed, 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 configured to disallow recording. this may be the case, for example, with sources obtained using getusermedia() when the user denies permission to use an input device. this also happens when a mediastreamtrack within the stream is marked as isolated due to the peeridentity constraint on the source stream. notsupportederror an attempt was made to instantiate a mediarecorder using a mime type that isn't supported on t...
....push(event.data); }; recorder.onerror = function(event) { let error = event.error; switch(error.name) { case invalidstateerror: shownotification("you can't record the video right " + "now. ...
MediaSession - Web APIs
for example, a smartphone might have a standard panel in its lock screen that provides controls for media. a browser on that device might deliver the metadata provided by calling mediasession to the device in order to be controllable using the global user interface. properties metadata returns an instance of mediametadata which contains rich media metadata, for display in a platform ui. ...
...n a platform ui. playbackstate indicates whether the current media session is playing. valid values are none, paused, or playing. methods setactionhandler() sets an event handler for a media session action, such as play or pause. see the method page for a full list. setpositionstate() sets the current playback position and speed of the media currently being presented. ...
...ndler('play', function() {}); navigator.mediasession.setactionhandler('pause', function() {}); navigator.mediasession.setactionhandler('seekbackward', function() {}); navigator.mediasession.setactionhandler('seekforward', function() {}); navigator.mediasession.setactionhandler('previoustrack', function() {}); navigator.mediasession.setactionhandler('nexttrack', function() {}); } the following example sets up event handlers for pausing and playing: var audio = document.queryselector("#player"); audio.src = "song.mp3"; navigator.mediasession.setactionhandler('play', play); navigator.mediasession.setactionhandler('pause', pause); function play() { audio.play(); navigator.mediasession.playbackstate = "playing"; } function pause() { audio.pause(); navigator.mediasession.play...
MediaStreamConstraints.video - Web APIs
nges of values for the track's constrainable properties. if you specify constraints, a video track meeting these constraints is required. examples using a boolean value in this example, we provide a simple value of true for the video property. this tells getusermedia() that we require a video track, but we don't care about any specifics beyond that. ...
...ler for a click event which uses getusermedia() to obtain a video-only stream with no specific constraints, then attaches the resulting stream to a <video> element once the stream is returned. ...
...> log(err.name + ": " + err.message)); }, false); here we see an event handler for a click event which calls getusermedia(), specifying a set of video constraints that indicate a preference for a video track whose dimensions are as close as possible to 160x120 pixels, and whose frame rate is as close to 15 frames per second as possible. as long as a video input device is available and the user allows it to be used, a video track will be included in the resulting stream, and it will match the specified constraints as well as possible. result specifications specification status comment media capture and streamsthe definition of 'mediastreamconstraints.video' in that specification. candidate recommendation initial specification. ...
MediaStreamTrack - Web APIs
see capabilities, constraints, and settings to learn how to correctly work with constrainable properties. not doing so correctly will result in your code being unreliable. ...
...rrectly work with constrainable properties. not doing so correctly will result in your code being unreliable. mediastreamtrack.contenthint a string that may be used by the web application to provide a hint as to what type of content the track contains to guide how it should be treated by api consumers. mediastreamtrack.enabled a boolean whose value of true if the track is enabled, that is allowed to render the media source stream; or false if it is disabled, that is not rendering the media source stream but silence and blackness. if the track has been disconnected, this value can be changed but has no more effect. note: you can implement standard "mute" functionality by setting enabled to false. the muted property refers to a condition in which there's no media because of a technical i...
...nabled to false, and unmute the media by setting it back to true again. mediastreamtrack.readonly read only returns a boolean value with a value of true if the track is readonly (such a video file source or a camera that settings can't be modified), false otherwise. mediastreamtrack.readystate read only returns an enumerated value giving the status of the track. this will be one of the following values: "live" which indicates that an input is connected and does its best-effort in providing real-time data. in that case, the output of data can be switched on or off using the enabled attribute. "ended" which indicates that the input is not giving any more data and will never provide new data. mediastreamtrack.remote read only returns a boolean with a value of true if the t...
MediaStreamTrackAudioSourceNode - Web APIs
rties of its own; however, it inherits the properties of its parent, audionode. methods inherits methods from its parent, audionode. example in this example, we grab a media (audio + video) stream from navigator.getusermedia, feed the media into a <video> element to play then mute the audio, but then also feed the audio into a mediastreamaudiosourcenode. next, we feed this source audio into a low pass biquadfilternode (which effectively serves as a bass booster), then a audiodestinationnode. the range slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. var pre = document.queryselector('pre'); var video = do...
...ction(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx = new audiocontext(); var source = audioctx.createmediastreamsource(stream); // create a biquadfilter var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); // get new...
...so playing/pausing the stream can still be done thro...
MutationEvent - Web APIs
observers are the proposed replacement for mutation events in dom4. they are expected to be included in firefox 14 and chrome 18. the practical reasons to avoid the mutation events are performance issues and cross-browser support. performance adding dom mutation listeners to a document profoundly degrades the performance of further dom modifications to that document (making them 1.5 - 7 times slower!). moreover, removing the listeners does not reverse the damage. the performance effect is limited to the documents that have the mutation event listeners. cross-browser support these events are not implemented consistently across different browsers, for example: ie prior to version 9 didn't support the mutation events at all and does not implement some of them correctly in version 9 (for...
...hem correctly in version 9 (for example, domnodeinserted) webkit doesn't support domattrmodified (see webkit bug 8191 and the workaround) "mutation name events", i.e. domelementnamechanged and domattributenamechanged are not supported in firefox (as of version 11), and probably in other browsers as well. ... dottoro documents browser support for mutation events. ...
... the following is a list of all mutation events, as defined in dom level 3 events specification: domattrmodified domattributenamechanged domcharacterdatamodified domelementnamechanged domnodeinserted domnodeinsertedintodocument domnoderemoved domnoderemovedfromdocument domsubtreemodified usage you can register a listener for mutation events using eventtarget.addeventlistener() as follows: element.addeventlistener("domnodeinserted", function (event) { // ... }, false); the event object is passed to the listener in a mutationevent (see its definition in the specification) for most events, and mutationnameevent for domattributenamechanged and domelementnamechanged. ...
NDEFReader.scan() - Web APIs
Web › API › NDEFReader › scan
ef records from compatible nfc devices, e.g., ndef nfc tags. syntax var readerpromise = ndefreader.scan(options); parameters options optional id -- the match pattern for matching each ndefrecord.id. recordtype -- the match pattern for matching each ndefrecord.recordtype. mediatype -- the match pattern for matching each ndefrecord.mediatype. ...
... notsupportederror there is no nfc adapter compatible with web nfc, or a connection can not be established. ...
...is scan() operation. return value a promise that resolves with undefined immediatelly after scheduling read operations for the nfc adapter. exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: aborterror the scan operation was aborted with abortsignal passed in options. notallowederror the permission for this operation was rejected. notsupportederror there is no nfc adapter compatible with web nfc, or a connection can not be established. specifications specification status comment web nfc, scan() draft initial definition. ...
NDEFWriter.write() - Web APIs
Web › API › NDEFWriter › write
message the message to be written, either domstring or buffersource or ndefmessageinit. options optional ignoreread -- boolean specifying whether or not to skip reading for the activated reader objects. will be ignored if overwrite is false. overwrite -- boolean specifying whether or not existing record should be overwritten, if such exists. ...
...record should be overwritten, if such exists. signal -- optional abortsignal that allows to cancell this write operation. return value a promise that resolves with undefined when and if the message transfer is successfully completed. exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: aborterror the write operation was aborted with abortsignal passed in options. notallowederror the permission for this operation was rejected or overwrite is false and there are already records on the tag. notsupportederror there is no nfc adapter compatible with web nfc, or the available nfc adapter does not support pushing messages, or connection can not be established. notreadable...
... networkerror transfer failed after it already started (e.g., the tag was removed from the reader). ...
Navigator.getUserMedia() - Web APIs
etusermedia() method, as well as the article capabilities, constraints, and settings. successcallback a function which is invoked when the request for media access is approved. the function is called with one parameter: the mediastream object that contains the media stream. your callback can then assign the stream to the desired object (such as an <audio> or <video> element), as shown in the following example: function(stream) { var video = document.queryselector('video'); video.srcobject = stream; video.onloadedmetadata = function(e) { // do something with the video here. }; } errorcallback when the call fails, the function specified in the errorcallback is invokedwith a mediastreamerror object as its sole argument; this object is is modeled on domexception. see {anc...
...nction(stream) { var video = document.queryselector('video'); video.srcobject = stream; video.onloadedmetadata = function(e) { // do something with the video here. }; } errorcallback when the call fails, the function specified in the errorcallback is invokedwith a mediastreamerror object as its sole argument; this object is is modeled on domexception. see {anch("errors")}} below for a list of the errors which can occur. return value undefined. errors examples width and height here's an example of using getusermedia(), including code to cope with various browsers' prefixes. note that this is the deprecated way of doing it: see the examples section under the mediadevices.getusermedia() for modern examples. navigator.getusermedia = navigator.getusermedia || ...
... navigator.mozgetusermedia; if (navigator.getusermedia) { navigator.getusermedia({ audio: true, video: { width: 1280, height: 720 } }, function(stream) { var video = document.queryselector('video'); video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); }; }, function(err) { console.log("the following error occurred: " + err.name); } ); } else { console.log("getusermedia not supported"); } ...
Navigator.msLaunchUri() - Web APIs
ture. the mslaunchuri() method is a microsoft extension to the navigator interface, which starts a service or app, such as an email client, that handles a given protocol. the uniform resource identifier (uri) contains the protocol for the default service or app, such as mailto://test@contoso.com. this proprietary method is specific to internet explorer, and microsoft edge versions 18 and lower. syntax navigator.mslaunchuri(uri, successcallback, nohandlercallback); parameters uri a domstring specifying the url containing including the protocol of the document or resource to be displayed. successcallbackoptional a function matching the signature of mslaunchuricallback to be executed if the protocol handler is present. nohandlercallbackoptional a function matching mslau...
... nohandlercallbackoptional a function matching mslaunchuricallback to be executed if the protocol handler is not present. return value undefined. usage notes if a default protocol handler is available on the system that matches the uri, the successcallback is invoked, otherwise, the nohandlercallback is called. to help protect a user's privacy, windows displays a prompt for the user to allow the service or app to be launched. the user can choose to not see the prompt after the first instance for a particular protocol and automatically open the app or service without a user intervention. the mslaunchuri() method does not support http, secure hypertext transfer protocol (https), file transfer protocol (ftp), file, res, javascript, or microsoft visual basic scripting edition (vbscript) ...
...s not have a program registered to handle a specific protocol, and a nohandlercallback is provided, windows internet explorer will invoke the nohandlercallback. this enables developers to provide a custom fallback experience for the user. if a handler doesn't exist, and the developer doesn't provide a nohandlercallback, then internet explorer displays a dialog that asks the user if they want to allow the action. if the user allows it, the user is then prompted to look in the windows store for an app to handle the protocol. if multiple programs are registered on the system for the given protocol and no default has been chosen, windows prompts the user to choose one. see also mslaunchuricallback microsoft api extensions ...
Web-based protocol handlers - Web APIs
o: protocol: <a href="mailto:webmaster@example.com">web master</a> web 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 regis...
...oogle.co.uk/?uri=%s", "burger handler"); where the parameters are: the protocol. the url template, used as the handler. the "%s" is replaced with the href of the link and a get is executed on the resultant url. the user friendly name for the protocol handler. when a browser executes this code, it should display a prompt to the user, asking permission to allow the web application to register as a handler for the protocol. firefox displays a prompt in the notification bar area: note:the url template supplied when registering must be of the same domain as the webpage attempting to perform the registration or the registration will fail. for example, http://example.com/homepage.html can register a protocol handler for http://example.com/handle_mailto/%s...
...er for http://example.com/handle_mailto/%s, but not for http://example.org/handle_mailto/%s. registering the same protocol handler more than once will pop up a different notification, indicating that the protocol handler is already registered. therefore, it is a good idea to guard your call to register the protocol handler with a check to see if it is already registered, such as in the example below. example <!doctype html public "-//w3c//dtd html 4.01//en"> <html lang="en"> <head> <title>web protocol handler sample - register</title> <script type="text/javascript"> navigator.registerprotocolhandler("web+burger", "http://www.google.co.uk/?uri=%s", "burger handler"); </script> </head> <body> <h1>web protocol han...
Navigator.sendBeacon() - Web APIs
g the data any sooner may miss some possible data collection. for example, which link the user clicked before navigating away and unloading the page. ensuring that data has been sent during the unloading of a document has traditionally been difficult, because user agents typically ignore asynchronous xmlhttprequests made in an unload handler. historically, this was addressed with some of the following workarounds to delay the page unload long enough to send data to some url: submitting the data with a blocking synchronous xmlhttprequest call in unload or beforeunload event handlers. creating an <img> element and setting its src in the unload handler. most user agents will delay the unload to load the image. creating a no-op loop for several seconds in the unload handler. all of these...
...enough to send data to some url: submitting the data with a blocking synchronous xmlhttprequest call in unload or beforeunload event handlers. creating an <img> element and setting its src in the unload handler. most user agents will delay the unload to load the image. creating a no-op loop for several seconds in the unload handler. all of these methods block unloading the document, which slows down the next navigation. there is nothing the next page can do to avoid this, so the new page seems slow, even though it's the previous page's fault. the following example shows theoretical analytics code that attempts to submit data to a server with a synchronous xmlhttprequest in an unload handler. this results in the next page load to be delayed. window.addeventlistener("unload", function ...
...method, the data is transmitted asynchronously when the user agent has an opportunity to do so, without delaying unload or the next navigation. this solves all of the problems with submission of analytics data: the data is sent reliably it's sent asynchronously it doesn't impact the loading of the next page in addition, the code is simpler to write than any of the older techniques! the following example shows a theoretical analytics code pattern that submits data to a server using the sendbeacon() method. window.addeventlistener("unload", function logdata() { navigator.sendbeacon("/log", analyticsdata); }); the beacon sends an http request via the post method, with all relevant cookies available when called. specifications specification status comment ...
Navigator - Web APIs
Web › API › Navigator
a navigator object can be retrieved using the read-only window.navigator property. properties doesn't inherit any properties, but implements those defined in navigatorid, navigatorlanguage, navigatoronline, navigatorcontentutils, navigatorstorage, navigatorstorageutils, navigatorconcurrenthardware, navigatorplugins, and navigatorusermedia. standard navigatorid.appcodename read only returns the internal "code" name of the current browser. do not rely on this property to return the correct value. ...
...a batterymanager object you can use to get information about the battery charging status. navigator.connection read only provides a networkinformation object containing information about the network connection of a device. navigator.cookieenabled read only returns false if setting a cookie will be ignored and true otherwise. navigator.geolocation read only returns a geolocation object allowing accessing the location of the device. navigatorconcurrenthardware.hardwareconcurrency read only returns the number of logical processor cores available. navigatorplugins.javaenabled read only returns a boolean flag indicating whether the host browser is java-enabled or not. navigator.keyboard read only returns a keyboard object which provides access to functions that retrieve keybo...
... navigatorcontentutils, navigatorusermedia, and navigatorstorageutils. standard navigator.canshare() returns true if a call to navigator.share() would succeed. navigator.getusermedia() after having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer. navigator.registercontenthandler() obsolete since gecko 59 allows web sites to register themselves as a possible handler for a given mime type. navigator.registerprotocolhandler() allows web sites to register themselves as a possible handler for a given protocol. navigator.requestmediakeysystemaccess() returns a promise for a mediakeysystemaccess object. navigator.sendbeacon() used to asynchronously transfer a small amount of data using http from the ...
Navigator.onLine - Web APIs
for example, the property should return false when users click links soon after they lose internet connection. browsers implement this property differently. ...
...ndows shows that it only looks for lan connection like chrome and safari giving false positives. you can see changes in the network state by listening for the events on window.ononline and window.onoffline. syntax online = window.navigator.online; value online is a boolean true or false. example view a live example. ...
...re online, query window.navigator.online, as in the following example: if (navigator.online) { console.log('online'); } else { console.log('offline'); } if the browser doesn't support navigator.online the above example will always come out as false/undefined. to see changes in the network state, use addeventlistener to listen for the events on window.online and window.offline, as in the following example: window.addeventlistener('offline', function(e) { console.log('offline'); }); window.addeventlistener('online', function(e) { console.log('online'); }); specifications specification status comment html living standardthe definition of 'navigator.online' in that specification. living standard initial definition ...
Node.nextSibling - Web APIs
Web › API › Node › nextSibling
syntax nextnode = node.nextsibling notes gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. therefore a node obtained, for example, using node.firstchild or node.previoussibling may refer to a whitespace text node rather than the actual element the author intended to get. see whitespace in the dom and w3c dom 3 faq: why are some text nodes empty? for more information. ...
...ments. example <div id="div-1">here is div-1</div> <div id="div-2">here is div-2</div> <script> var el = document.getelementbyid('div-1').nextsibling, i = 1; console.group('siblings of div-1:'); while (el) { console.log(i, '. ...
...see the resources in the notes section. specifications specification status comment domthe definition of 'node.nextsibling' in that specification. ...
Notification.requestPermission() - Web APIs
ional callback function that is called with the permission value. deprecated in favor of the promise return value. returns a promise that resolves to a domstring with the permission picked by the user. possible values for this string are: granted denied default examples assume this basic html: <button onclick="notifyme()">notify me!</button> it's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification. function notifyme() { // let's check if the browser supports notifications if (!("notifica...
...ermission) { // if the user accepts, let's create a notification if (permission === "granted") { var notification = new notification("hi there!"); } }); } // at last, if the user has denied notifications, and you // want to be respectful there is no need to bother them any more. } we no longer show a live sample on this 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 ag...
...firefox is already doing this from version 72, for example. ...
Notification - Web APIs
. instance methods these properties are available only on an instance of the notification object or through its prototype. the notification object also inherits from the eventtarget interface. notification.close() programmatically closes a notification instance. examples assume this basic html: <button onclick="notifyme()">notify me!</button> it's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification. function notifyme() { // let's check if the browser supports notifications if (!("notifica...
...ermission) { // if the user accepts, let's create a notification if (permission === "granted") { var notification = new notification("hi there!"); } }); } // at last, if the user has denied notifications, and you // want to be respectful there is no need to bother them any more. } we no longer show a live sample on this 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 ag...
...firefox is already doing this from version 72, for example. ...
Notifications API - Web APIs
these are outside the top-level browsing context viewport, so therefore can be displayed even when the user has switched tabs or moved to a different app. the api is designed to be compatible with existing notification systems, across different platforms. concepts and usage on supported platforms, showing a system notification generally involves two things. ...
...questpermission() 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 made, the setting will generally persist for the current session. note: as of firefox 44, the permission...
...sh will also be enabled. next, a new notification is created using the notification() constructor. this must be passed a title argument, and can optionally be passed an options object to specify options, such as text direction, body text, icon to display, notification sound to play, and more. in addition, the notifications api spec specifies a number of additions to the serviceworker api, to allow service workers to fire notifications. note: to find out more about using notifications in your own app, read using the notifications api. notifications interfaces notification defines a notification object. service worker additions serviceworkerregistration includes the serviceworkerregistration.shownotification() and serviceworkerregistration.getnotifications() method, for control...
OscillatorNode - Web APIs
ion speakers constructor oscillatornode() creates a new instance of an oscillatornode object, optionally providing an object specifying default values for the node's properties. if the default values are acceptable, you can simply call the baseaudiocontext.createoscillator() factory method. properties inherits properties from its parent, audioscheduledsourcenode, and adds the following properties: oscillatornode.frequency an a-rate audioparam representing the frequency of oscillation in hertz (though the audioparam returned is read-only, the value it represents is not). the default value is 440 hz (a standard middle-a note). oscillatornode.detune an a-rate audioparam representing detuning of oscillation in cents (though the audioparam returned is read-only, the valu...
...ve to describe a custom waveform. different waves will produce different tones. standard values are "sine", "square", "sawtooth", "triangle" and "custom". the default is "sine". event handlers oscillatornode.onended sets the event handler for the ended event, which fires when the tone has stopped playing. methods inherits methods from its parent, audioscheduledsourcenode, and adds the following: oscillatornode.setperiodicwave() sets a periodicwave which describes a periodic waveform to be used instead of one of the standard waveforms; calling this sets the type to custom. this 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 to...
...setperiodicwave() sets a periodicwave which describes a periodic waveform to be used instead of one of the standard waveforms; calling this sets the type to custom. this 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...
Page Visibility API - Web APIs
as settimeout() are throttled in background/inactive tabs to help improve performance. see reasons for delays longer 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 sp...
... connections (websockets and webrtc) go unthrottled in order to avoid closing these connections timing out and getting unexpectedly closed. indexeddb processes are also left unthrottled in order to avoid timeouts. example view live example (video with sound). ...
...alse); // when the video pauses, set the title. // this shows the paused videoelement.addeventlistener("pause", function(){ document.title = 'paused'; }, false); // when the video plays, set the title. videoelement.addeventlistener("play", function(){ document.title = 'playing'; }, false); } properties added to the document interface the page visibility api adds the following properties to the document interface: document.hidden read only returns true if the page is in a state considered to be hidden to the user, and false otherwise. document.visibilitystate read only a domstring indicating the document's current visibility state. possible values are: visible the page content may be at least partially visible. in practice this means that the page is t...
PaymentResponse.complete() - Web APIs
over, and causes any remaining user interface to be closed. this method must be called after the user accepts the payment request and the promise returned by the paymentrequest.show() method is resolved. syntax completepromise = paymentrequest.complete(result); parameters result optional a domstring indicating the state of the payment operation upon completion. it must be one of the following: success the payment was successfully processed. the user agent may or may not present some form of "payment successful" indication to the user. fail the payment was not successfully processed. the failure may or may not be announced to the user by the user agent, depending on its design. unknown the success or failure status of the transaction is unknown or irrelevant, and the ...
...esign. unknown the success or failure status of the transaction is unknown or irrelevant, and the user agent should not present any notification, even if it normally would. this is the default value. note: in older versions of the specification, an empty string, "", was used instead of unknown to indicate a completion without a known result state. see the browser compatibility section below for details. return value a promise which resolves with no input value once the payment interface has been fully closed. if an error occurs, the promise instead rejects, returning one of the exceptions listed below. exceptions aborterror the document in which the payment request is taking place became inactive while the user interface was shown. invalidstateerror the payment has alr...
...it calls complete() with an answer appropriate to the status in the response. // initialization of paymentrequest arguments are excerpted for the // sake of brevity. ...
PerformanceEventTiming - Web APIs
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. ...
...ted. 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. ...
...ue to an analytics endpoint. sendtoanalytics({fid}); } } // create a performanceobserver that calls `onfirstinputentry` for each entry. const po = new performanceobserver((entrylist) => { entrylist.getentries().foreach(onfirstinputentry); }); // observe entries of type `first-input`, including buffered entries, // i.e. entries that occurred before calling `observe()` below. po.observe({ type: 'first-input', buffered: true, }); } catch (e) { // do nothing if the browser doesn't support this api. } specifications specification status comment unknownthe definition of '[[member]]' in that specification. unknown initial definition. ...
PerformanceFrameTiming - Web APIs
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. ...
... performanceentry.name returns the document's address. performanceentry.starttime returns the timestamp when the frame was started. performanceentry.duration returns a timestamp indicating the difference between the sta...
... performanceentry.name returns the document's address. ...
PerformanceMark - Web APIs
ncemark is an abstract interface for performanceentry objects with an entrytype of "mark". entries of this type are created by calling performance.mark() to add a named domhighrestimestamp (the mark) to the browser's performance timeline. ...
... 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 d...
... x="276" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">performancemark</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but it extends the following performanceentry properties by qualifying/constraining the properties as follows: performanceentry.entrytype returns "mark". 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 us...
PerformanceMeasure - Web APIs
rface for performanceentry objects with an entrytype of "measure". entries of this type are created by calling performance.measure() to add a named domhighrestimestamp (the measure) between two marks to the browser's performance timeline. ...
... 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...
...291" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">performancemeasure</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but it extends the following performanceentry properties by qualifying/constrainting the properties as follows: performanceentry.entrytype returns "measure". 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...
PerformanceResourceTiming - Web APIs
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. ...
...7f8" stroke="#d4dde4" stroke-width="2px" /><text x="326" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">performanceresourcetiming</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} note: this feature is available in web workers. properties this interface extends the following performanceentry properties for resource performance entry types by qualifying and constraining them as follows: performanceentry.entrytyperead only returns "resource". performanceentry.nameread only returns the resources url. performanceentry.starttimeread only returns the timestamp for the time a resource fetch started. this value is equivalent to performanceentry.fetchstart. pe...
...esource". performanceentry.nameread only returns the resources url. performanceentry.starttimeread only returns the timestamp for the time a resource fetch started. this value is equivalent to performanceentry.fetchstart. performanceentry.durationread only returns a timestamp that is the difference between the responseend and the starttime properties. the interface also supports the following properties which are listed in the order in which they are recorded for the fetching of a single resource. an alphabetical listing is shown in the navigation, at left. performanceresourcetiming.initiatortyperead only a string representing the type of resource that initiated the performance entry, as specified in performanceresourcetiming.initiatortype. performanceresourcetiming.nexthoppr...
Pinch zoom gestures - Web APIs
kground: white; border: 1px solid black; } </style> global state supporting a two-pointer gesture requires preserving a pointer's event state during various event phases. this application uses two global variables to cache the event state. // global vars to cache event state var evcache = new array(); var prevdiff = -1; register event handlers event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup. the handler for pointerup is used for the pointercancel, pointerout and pointerleave events since these four events have the same semantics in this application. function init() { // install event handlers for the pointer target var el=document.getelementbyid("target"); el.onpointerdown = pointerdown_handler; el.onpointermove = pointe...
...or changes to lightblue if the pinch is closing (zoom out).</div> <!-- ui for logging/debugging --> <button id="log" onclick="enablelog(event);">start/stop event logging</button> <button id="clearlog" onclick="clearlog(event);">clear the log</button> <p></p> <output></output> </body> miscellaneous functions these functions support the application but aren't directly involved in the event flow. cache management this function helps manage the global event caches evcache. function remove_event(ev) { // remove this event from the target's cache for (var i = 0; i < evcache.length; i++) { if (evcache[i].pointerid == ev.pointerid) { evcache.splice(i, 1); break; } } } event logging these functions are used to send event activity to the application's window (to support...
...manage the global event caches evcache. function remove_event(ev) { // remove this event from the target's cache for (var i = 0; i < evcache.length; i++) { if (evcache[i].pointerid == ev.pointerid) { evcache.splice(i, 1); break; } } } event logging these functions are used to send event activity to the application's window (to support debugging and learning about the event flow). // log events flag var logevents = false; // logging/debugging functions function enablelog(ev) { logevents = logevents ? false : true; } function log(prefix, ev) { if (!logevents) return; var o = document.getelementsbytagname('output')[0]; var s = prefix + ": pointerid = " + ev.pointerid + " ; pointertype = " + ev.pointertype + " ; isprimary = " + ev.
RTCPeerConnection.setLocalDescription() - Web APIs
ess. deprecated parameters in older code and documentation, you may see a callback-based version of this function used. this has been deprecated and its use is strongly discouraged, as it will be removed in the future. you should update any existing code to use the promise-based version of setlocaldescription() instead. the parameters for the older form of setlocaldescription() are described below, to aid in updating existing code. successcallback a javascript function which accepts no input parameters to be be called once the description has been successfully set. at that time, the offer can be sent to a remote peer via the signaling server. errorcallback a function matching the signature rtcpeerconnectionerrorcallback which gets called if the description can't be set. it is pas...
... passed a single domexception object explaining why the request failed. this deprecated form of the method returns instantaneously without waiting for the actual setting to be done: in case of success, the successcallback will be called; in case of failure, the errorcallback will be called. deprecated exceptions when using the deprecated callback-based version of setlocaldescription(), the following exceptions may occur: invalidstateerror the connection's signalingstate is "closed", indicating that the connection is not currently open, so negotiation cannot take place. invalidsessiondescriptionerror the rtcsessiondescription specified by the sessiondescription parameter is invalid. examples implicit descriptions one of the advantages of the parameter-free form of setlocaldes...
...t handler needs to look like, for the most part. just add the signaling server code, which here is represented by the call to signalremotepeer(). pc.addeventlistener("negotiationneeded", async (event) => { await pc.setlocaldescription(); signalremotepeer({ description: pc.localdescription }); }); other than error handling, that's about it! providing your own offer or answer the example below shows the implementation of a handler for the negotiationneeded event that explicitly creates an offer, rather than letting setlocaldescription() do it. async function handlenegotiationneededevent() { try { await offer = pc.createoffer(); pc.setlocaldescription(offer); signalremotepeer({ description: pc.localdescription }); } catch(err) { reporterror(err); } } this begins ...
RTCRtpSender.replaceTrack() - Web APIs
amtrack. the new track must be of the same media kind (audio, video, etc) and switching the track should not require negotiation. among the use cases for replacetrack() is the common need to switch between the rear- and front-facing cameras on a phone. with replacetrack(), you can simply have a track object for each camera and switch between the two as needed. see the example switching cameras below. syntax trackreplacedpromise = sender.replacetrack(newtrack); parameters newtrack optional a mediastreamtrack specifying the track with which to replace the rtcrtpsender's current source track. the new track's kind must be the same as the current track's, or the replace track request will fail. return value a promise which is fulfilled once the track has been successfully replaced. the ...
...the rtcrtpsender's current source track. the new track's kind must be the same as the current track's, or the replace track request will fail. return value a promise which is fulfilled once the track has been successfully replaced. ...
... invalidstateerror the track on which this method was called is stopped rather than running. ...
RTCRtpSender.setParameters() - Web APIs
width situations; the value comes from the rtcdegradationpreference enumerated string type, and the default is balanced. encodings an array of rtcrtpencodingparameters objects, each specifying the parameters for a single codec that could be used to encode the track's media. priority a string from the rtcprioritytype enumerated type which indicates the encoding's priority. the default value is low. transactionid a string containing a unique id for the last set of parameters applied; this value is used to ensure that setparameters() can only be called to alter changes made by a specific previous call to getparameters(). return value a promise that resolves when the rtcrtpsender.track property is updated with the given parameters. exceptions if an error occurs, the returned promise...
...st set of parameters applied; this value is used to ensure that setparameters() can only be called to alter changes made by a specific previous call to getparameters(). return value a promise that resolves when the rtcrtpsender.track property is updated with the given parameters. exceptions if an error occurs, the returned promise is rejected with the appropriate exception from the list below. invalidmodificationerror one of the following problems was detected: the number of encodings specified in the parameters object's encodings property does not match the number of encodings currently listed for the rtcrtpsender. you cannot change the number of encoding options once the sender has been created. the order of the specified encodings has changed from the current list's order...
...ted. invalidstateerror the transceiver of which the rtcrtpsender is a part is not running, or has no parameters to set. operationerror any error condition which occurs that isn't covered by one of the other error codes results in an operationerror. rangeerror the value specified for scaleresolutiondownby is less than 1.0, which would result in scaling up rather than down, which is not allowed; or one or more of the specified encodings' maxframerate values is less than 0.0. in addition, if a webrtc error occurs while configuring or accessing the media, an rtcerror is thrown with its errordetail set to hardware-encoder-error. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpsender.setpa...
ReadableStreamDefaultReader - Web APIs
the readablestreamdefaultreader 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. readablestreamdefau...
...s 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() returns a promise providing access to the next chunk in the stream's internal queue. readablestreamdefaultreader.releaselock() releases the reader's lock on the stream. ...
... examples in the following example, an artifical 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. ...
Reporting API - Web APIs
ing your code is trying to do because it is deemed a security risk for example, or just plain annoying, like auto-playing audio). the reporting api's purpose is to provide a consistent reporting mechanism that can be used to make such information available to developers in the form of reports represented by javascript objects. there are a few ways to use it, which are detailed in the sections below. origins and endpoints each unique origin you want to retrieve reports for can be given a series of endpoints, which are urls that can receive given reports from a user agent. the report-to http header is used to specify details about the different endpoints that a user-agent has available to it for delivering reports to. you can then retrieve reports by making a request to those urls. the en...
...bserver object is created using the reportingobserver() constructor, which is passed two parameters: a callback function that has available as parameters the reports available in the observer's report queue, and a copy of the same reportingobserver object, so observation can be controlled directly from inside the callback. the callback runs when observation starts an options dictionary that allows you to specify the type of reports to collect, and whether the reports that were generated before the observer was able to be created should be observable (buffered: true). methods are then available on the observer to start collecting reports (reportingobserver.observe()), retrieve the reports currently in the report queue (reportingobserver.takerecords()), and disconnect the observer so it c...
...eportingobserver.takerecords()), and disconnect the observer so it can no longer collect records (reportingobserver.disconnect()). reporting api interfaces reportingobserver create reportingobserver instances using its constructor, which can then be used to collect and access reports. report an object representing a single report. reporting api dictionaries reportingobserveroptions allows options to be set in the constructor when creating a reporting observer. available report types the spec defines the following report types: deprecation report indicates that a webapi or other browser feature being used in the website is expected to stop working in a future release. indicated by a report.body property with a deprecationreportbody return value. intervention report indica...
Request.clone() - Web APIs
Web › API › Request › clone
the clone() method of the request interface creates a copy of the current request object. clone() throws a typeerror if the response body has already been used. in fact, the main reason clone() exists is to allow multiple uses of body objects (when they are one-use only.) if intend to modify the request, you may prefer the request constructor. syntax var newrequest = request.clone(); parameters none. return value a request object, which is an exact copy of the request that clone() was called on. ...
...onse body has already been used. in fact, the main reason clone() exists is to allow multiple uses of body objects (when they are one-use only.) if intend to modify the request, you may prefer the request constructor. syntax var newrequest = request.clone(); parameters none. return value a request object, which is an exact copy of the request that clone() was called on. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then clone the request. ...
...r the request constructor. syntax var newrequest = request.clone(); parameters none. return value a request object, which is an exact copy of the request that clone() was called on. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then clone the request. var myrequest = new request('flowers.jpg'); var newrequest = myrequest.clone(); // a copy of the request is now stored in newrequest specifications specification status comment fetchthe definition of 'clone' in that specification. living standard initial definition ...
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...
...erviceworker and sharedworker. syntax var destination = request.destination; value a string from the requestdestination enumerated type which indicates the type of content the request is asking for. this type is much broader than the usual document type values (such as "document" or "manifest"), and may include contextual cues such as "image" or "worker" or "audioworklet". ...
... for. this type is much broader than the usual document type values (such as "document" or "manifest"), and may include contextual cues such as "image" or "worker" or "audioworklet". example in the following snippet, we create a new request using the request() constructor (for an image file in the same directory as the script), then save the request's destination: var myrequest = new request('flowers.jpg'); var mydestination = myrequest.destination; // returns the empty string by default specifications specification status comment fetchthe definition of 'destination' in that specification. living standard initial definition ...
Request.headers - Web APIs
Web › API › Request › headers
the headers read-only property of the request interface contains the headers object associated with the request. syntax var myheaders = request.headers; value a headers object. ...
...ad-only property of the request interface contains the headers object associated with the request. syntax var myheaders = request.headers; value a headers object. ...
... living standard initial definition ...
Request.mode - Web APIs
Web › API › Request › mode
han simple headers. if any serviceworkers intercept these requests, they may not add or override any headers except for those that are simple headers. in addition, javascript may not access any properties of the resulting response. this ensures that serviceworkers do not affect the semantics of the web and prevents security and privacy issues arising from leaking data across domains. cors — allows cross-origin requests, for example to access various apis offered by 3rd party vendors. these are expected to adhere to the cors protocol. only a limited set of headers are exposed in the response, but the body is readable. navigate — a mode for supporting navigation. the navigate value is intended to be used only by html navigation. a navigate request is created only while navigating betwee...
...ructor, no-cors is typically used as the mode; for example, for embedded resources where the request is initiated from markup, unless the crossorigin attribute is present, the request is in most cases made using the no-cors mode — that is, for the <link> or <script> elements (except when used with modules), or <img>, <audio>, <video>, <object>, <embed>, or <iframe> elements. ...
...g the no-cors mode — that is, for the <link> or <script> elements (except when used with modules), or <img>, <audio>, <video>, <object>, <embed>, or <iframe> elements. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request mode in a variable: var myrequest = new request('flowers.jpg'); var mymode = myrequest.mode; // returns "cors" by default specifications specification status comment fetchthe definition of 'mode' in that specification. living standard initial definition ...
Resize Observer API - Web APIs
element.getboundingclientrect or window.getcomputedstyle, for example. such a solution tends to only work for limited use cases, be bad for performance (continually calling the above methods would result in a big performance hit), and often won't work when the browser window size is not changed. the resize observer api provides a solution to exactly these kinds of problems, and more besides, allowing you to easily observe and respond to changes in the size of an element’s content or border box in a performant way. it provides a javascript solution to the often-discussed lack of element queries in the web platform. usage is simple, and pretty much the same as other observers, such as performance observer or intersection observer — you create a new resizeobserver object using the resize...
...ty much the same as other observers, such as performance observer or intersection observer — you create a new resizeobserver object using the resizeobserver() constructor, then use resizeobserver.observe() to make it look for changes to a specific element's size. a callback function set up inside the constructor then runs every time the size changes, providing access to the new dimensions and allowing you to do anything you like in response to those changes. interfaces resizeobserver provides the ability to register new observers and to start and stop observing elements. resizeobserverentry describes a single element which has been resized, identifying the element and its new size. examples you find a couple of simple examples on our github repo: resize-observer-border-radius.h...
...ou nice square corners that scale with the box size. resize-observer-text.html (see source): here we use the resize observer to change the font-size of a header and paragraph as a slider’s value is changed causing the containing <div> to change width. this shows that you can respond to changes in an element’s size, even if they have nothing to do with the viewport. ...
Response.redirected - Web APIs
the read-only redirected property of the response interface indicates whether or not the response is the result of a request you made which was redirected. relying on redirected to filter out redirects makes it easy for a forged redirect to prevent your content from working as expected. instead, you should actually instead do the filtering when you call fetch(). ...
...en you call fetch(). see the example disallowing redirects, which shows this being done. syntax var isredirected = response.redirected; value a boolean which is true if the response indicates that your request was redirected. examples detecting redirects checking to see if the response comes from a redirected request is as simple as checking this flag on the response object. in the code below, a textual message is inserted into an element when a redirect occurred during the fetch operation. note, however, that this isn't as safe as outright rejecting redirects if they're unexpected, as described under disallowing redirects below. fetch("awesome-picture.jpg").then(function(response) { let elem = document.getelementbyid("warning-message-box"); if (response.redirected) { elem.in...
...e-picture.jpg").then(function(response) { let elem = document.getelementbyid("warning-message-box"); if (response.redirected) { elem.innerhtml = "unexpected redirect"; } else { elem.innerhtml = ""; } return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); disallowing redirects because using redirected to manually filter out redirects can allow forgery of redirects, you should instead set the redirect mode to "error" in the init parameter when calling fetch(), like this: fetch("awesome-picture.jpg", { redirect: "error" }).then(function(response) { return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); ...
Response - Web APIs
Web › API › Response
a headers object, associated with the response with response.headers for values of the http trailer header. response.type read only the type of the response (e.g., basic, cors). response.url read only the url of the response. response.usefinalurl a boolean indicating whether this is the final url of the response. body interface properties response implements body, so it also has the following properties available to it: body.body read only a simple getter exposing a readablestream of the body contents. body.bodyused read only stores a boolean that declares whether the body has been used in a response yet. methods response.clone() creates a clone of a response object. response.error() returns a new response object associated with a network error. response.redirect()...
... body.bodyused read only stores a boolean that declares whether the body has been used in a response yet. methods response.clone() creates a clone of a response object. response.error() returns a new response object associated with a network error. response.redirect() creates a new response with a different url. body interface methods response implements body, so it also has the following methods available to it: body.arraybuffer() takes a response stream and reads it to completion. it returns a promise that resolves with an arraybuffer. body.blob() takes a response stream and reads it to completion. it returns a promise that resolves with a blob. body.formdata() takes a response stream and reads it to completion. it returns a promise that resolves with a formdata objec...
...ple fetch() call to grab an image and display it in an <img> element. the fetch() call returns a promise, which resolves to the response object associated with the resource fetch operation. you'll notice that since we are requesting an image, we need to run body.blob (response implements body) to give the response its correct mime type. ...
SVGStyleElement - Web APIs
svg style interface the svgstyleelement interface corresponds to the svg <style> element. ...
...styleelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent interface, svgelement and implements properties from linkstyle. svgstyleelement.type a domstring corresponding to the type attribute of the given element. svg 1.1 defined that a domexception is raised with code no_modification_allowed_err on an attempt to change the value of a read-only attribute. this restriction was removed in svg 2. svgstyleelement.media a domstring corresponding to the media attribute of the given element. svg 1.1 defined that a domexception is raised with code no_modification_allowed_err on an attempt to change the value of a read-only attribute. this restriction was removed in svg 2. svgstyleel...
...this restriction was removed in svg 2. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement and implements methods from linkstyle. ...
Screen Capture API - Web APIs
diadevices interface mediadevices.getdisplaymedia() the getdisplaymedia() method is added to the mediadevices interface. similar to getusermedia(), this method creates a promise that resolves with a mediastream containing the display area selected by the user, in a format that matches the specified options. additions to existing dictionaries the screen capture api adds properties to the following dictionaries defined by other specifications. mediatrackconstraints mediatrackconstraints.cursor a constraindomstring indicating whether or not the cursor should be included in the captured display surface's stream, and if it should always be visible or if it should only be visible while the mouse is in motion. mediatrackconstraints.displaysurface a constraindomstring indicating what ty...
...e support the mediatrackconstraints.cursor constraint. mediatracksupportedconstraints.displaysurface a boolean which is true if the current environment supports the mediatrackconstraints.displaysurface constraint. mediatracksupportedconstraints.logicalsurface a boolean which is true if the current environment supports the constraint mediatrackconstraints.logicalsurface. dictionaries the following dictionaries are defined by the screen capture api. cursorcaptureconstraint an enumerated string type used to provide the value for the cursor property for the settings and constraints. the possible values are always, motion, and never. displaycapturesurfacetype an enumerated string type which is used to identify the kind of display surface to capture. this type is used for the displaysu...
...type an enumerated string type which is used to identify the kind of display surface to capture. this type is used for the displaysurface property in the constraints and settings objects, and has the possible values application, browser, monitor, and window. feature policy validation user agents that support feature policy (either using http's feature-policy header or the <iframe> attribute allow) can specify a desire to use the screen capture api using the policy control directive display-capture: <iframe allow="display-capture" src="/some-other-document.html"> the default allow list is self, which lets the any content within the document use screen capture. see using feature policy for a more in-depth explanation of how feature policy is used. specifications specification ...
ScriptProcessorNode - Web APIs
note: as of the august 29 2014 web audio api spec publication, this feature has been marked as deprecated, and 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. ...
...tes 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 lower the latency, but large number may be necessary to avoid audio breakup and glitches. if the buffer size is not defined, which is recommended, the browser will pick one that its heuristic deems appropriate. number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpre...
......
Selection.setBaseAndExtent() - Web APIs
ncluded 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 position in the document, the direction of the selection is reversed — the caret is placed at the beginning of the text rather the end, which matters for any keyboard command that might follow. for example, shift + ➡︎ would cause the selection to narrow from the beginning rather than grow at the end. return value void. exceptions if anchoroffset is larger than the number of child nodes inside anchornode, or if focusoffset is larger than the number of child nodes inside focusnode, an indexsizeerror exception is thrown. examples in this example, we have two paragraphs containi...
...soffset is larger than the number of child nodes inside focusnode, an indexsizeerror exception is thrown. examples in this example, we have two paragraphs containing spans, each one containing a single word. the first one is set as the anchornode and the second is set as the focusnode. we also have an additional paragraph that sits in between the two nodes. next, we have two form inputs that allow you to set the anchoroffset and focusoffset — they both have a default value of 0. we also have a button that when pressed invokes a function that runs the setbaseandextent() method with the specified offsets, and copies the selection into the output paragraph at the very bottom of the html. <h1>setbaseandextent example</h1> <div> <p class="one"><span>fish</span><span>dog</span><span>cat</s...
... note: you can find this example on github (see it live also.) specifications specification status comment selection apithe definition of 'selection.setbaseandextent()' in that specification. working draft ...
ServiceWorkerGlobalScope - Web APIs
andler should assume it's being invoked with a bare, default global state. once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. an active service worker is automatically restarted to respond to events, such as serviceworkerglobalscope.onfetch or serviceworkerglobalscope.onmessage. additionally, synchronous requests are not allowed from within a service worker — only asynchronous requests, like those initiated via the fetch() method, can be used. this interface inherits from the workerglobalscope interface, and its parent eventtarget, and therefore implements properties from windowtimers, windowbase64, and windoweventhandlers. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%...
... those initiated via the fetch() method, can be used. this interface inherits from the workerglobalscope interface, and its parent eventtarget, and therefore implements properties from windowtimers, windowbase64, and windoweventhandlers. ...
...he serviceworkerglobalscope.onpushsubscriptionchange property. sync triggered when a call to syncmanager.register is made from a service worker client page. the attempt to sync is made either immediately if the network is available or as soon as the network becomes available. also available via the serviceworkerglobalscope.onsync property. methods serviceworkerglobalscope.skipwaiting() allows the current service worker registration to progress from waiting to active state while service worker clients are using it. serviceworkerglobalscope implements workerglobalscope — which implements windoworworkerglobalscope. therefore it also has the following property available to it: globalfetch.fetch() starts the process of fetching a resource. this returns a promise that resolves to t...
Service Worker API - Web APIs
service workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available). they are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. they will also allow access to push notifications and background sync apis. service worker concepts and usage a service worker is an event-driven worker registered against an origin and a path. it takes the form of a javascript file that can control the web-page/site that it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete contro...
...se of promises, as generally they will wait for responses to come through, after which they will respond with a success or failure action. the promises architecture is ideal for this. registration a service worker is first registered using the serviceworkercontainer.register() method. if successful, your service worker will be downloaded to the client and attempt installation/activation (see below) for urls accessed by the user inside the whole origin, or inside a subset specified by you. download, install and activate at this point, your service worker will observe the following lifecycle: download install activate the service worker is immediately downloaded when a user first accesses a service worker–controlled site/page. after that, it is updated when: a navigation to an...
...workerglobalscope from another context) — extends the lifetime of such events. fetchevent the parameter passed into the serviceworkerglobalscope.onfetch handler, fetchevent represents a fetch action that is dispatched on the serviceworkerglobalscope of a serviceworker. it contains information about the request and resulting response, and provides the fetchevent.respondwith() method, which allows us to provide an arbitrary response back to the controlled page. installevent the parameter passed into the oninstall handler, the installevent interface represents an install action that is dispatched on the serviceworkerglobalscope of a serviceworker. as a child of extendableevent, it ensures that functional events such as fetchevent are not dispatched during installation. navigationprelo...
ShadowRoot - Web APIs
element the shadowroot is attached to. shadowroot.innerhtml sets or returns a reference to the dom tree inside the shadowroot. shadowroot.mode read only the mode of the shadowroot — either open or closed. this defines whether or not the shadow root's internal features are accessible from javascript. properties included from documentorshadowroot the shadowroot interface includes the following properties defined on the documentorshadowroot mixin. note that this is currently only implemented by chrome; other browsers still implement them on the document interface. documentorshadowroot.activeelement read only returns the element within the shadow tree that has focus. documentorshadowroot.stylesheets read only returns a stylesheetlist of cssstylesheet objects for stylesheets ex...
...d by chrome; other browsers still implement them on the document interface. documentorshadowroot.activeelement read only returns the element within the shadow tree that has focus. documentorshadowroot.stylesheets read only returns a stylesheetlist of cssstylesheet objects for stylesheets explicitly linked into, or embedded in a document. methods the shadowroot interface includes the following methods defined on the documentorshadowroot mixin. note that this is currently only implemented by chrome; other browsers still implement them on the document interface. documentorshadowroot.getselection() returns a selection object representing the range of text selected by the user, or the current position of the caret. documentorshadowroot.elementfrompoint() returns the topmost elemen...
...t. documentorshadowroot.elementfrompoint() returns the topmost element at the specified coordinates. documentorshadowroot.elementsfrompoint() returns an array of all elements at the specified coordinates. documentorshadowroot.caretpositionfrompoint() returns a caretposition object containing the dom node containing the caret, and caret's character offset within that node. examples the following snippets are taken from our life-cycle-callbacks example (see it live also), which creates an element that displays a square of a size and color specified in the element's attributes. inside the <custom-square> element's class definition we include some life cycle callbacks that make a call to an external function, updatestyle(), which actually applies the size and color to the element. you'l...
SharedWorker() - Web APIs
ng the url of the script the worker will execute. it must obey the same-origin policy. name optional a domstring specifying an identifying name for the sharedworkerglobalscope representing the scope of the worker, which is mainly useful for debugging purposes. options optional an object containing option properties that can set when creating the object instance. available properties are as follows: type: a domstring specifying the type of worker to create. the value can be classic or module. if not specified, the default used is classic. credentials: a domstring specifying the type of credentials to use for the worker. the value can be omit, same-origin, or include. if not specified, or if type is classic, the default used is omit (no credentials required). name: a domstring speci...
...e omit, same-origin, or include. if not specified, or if type is classic, the default used is omit (no credentials required). name: a domstring specifying an identifying name for the sharedworkerglobalscope representing the scope of the worker, which is mainly useful for debugging purposes. return value the created worker. ...
... return value the created worker. exceptions a securityerror is raised if the document is not allowed to start workers, for example if the url has an invalid syntax or if the same-origin policy is violated. a networkerror is raised if the mime type of the worker script is incorrect. it should always be text/javascript. a syntaxerror is raised if aurl cannot be parsed. ...
Storage API - Web APIs
on caches notification data other kinds of site-accessible, site-specific data that may be maintained site storage units the site storage system described by the storage standard and interacted with using the storage api consists of a single site storage unit for each origin. in essence, every web site or web application has its own storage unit into which its data gets placed. the diagram below shows a site storage pool with three storage units within, showing how storage units can have different data types stored within and may have different quotas (maximum storage limits). origin 1 has some web storage data as well as some indexeddb data, but also has some free space left; its current usage hasn't yet reached its quota. origin 2 has no data stored in it yet; it's just an empty ...
...ithin, showing how storage units can have different data types stored within and may have different quotas (maximum storage limits). origin 1 has some web storage data as well as some indexeddb data, but also has some free space left; its current usage hasn't yet reached its quota. origin 2 has no data stored in it 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 t...
...the actual data storage within each site storage unit is called its box. each site storage unit has exactly one box into which all of its data is placed, and has a box mode that describes the data retention policy for that box. there are two modes: "best-effort" the user agent will try to retain the data contained in the box for as long as it can, but will not warn users if storage space runs low and it becomes necessary to clear the box in order to relieve the storage pressure. "persistent" the user agent will retain the data as long as possible, clearing all "best-effort" boxes before considering clearing a box marked "persistent". if it becomes necessary to consider clearing persistent boxes, the user agent will notify the user and provide a way to clear one or more persistent boxes ...
SubtleCrypto.deriveKey() - Web APIs
will be used for. for hmac: pass an hmackeygenparams object. for aes-ctr, aes-cbc, aes-gcm, or aes-kw: pass an aeskeygenparams object. extractable is a boolean indicating whether it will be possible to export the key using subtlecrypto.exportkey() or subtlecrypto.wrapkey(). keyusages is an array indicating what can be done with the derived key. note that the key usages must be allowed by the algorithm set in derivedkeyalgorithm. possible values of the array are: encrypt: the key may be used to encrypt messages. decrypt: the key may be used to decrypt messages. sign: the key may be used to sign messages. verify: the key may be used to verify signatures. derivekey: the key may be used in deriving a new key. "derivebits": the key may be used in deriving bit...
... verify: the key may be used to verify signatures. derivekey: the key may be used in deriving a new key. "derivebits": the key may be used in deriving bits. "wrapkey": the key may be used to wrap a key. "unwrapkey": the key may be used to unwrap a key. return value result is a promise that fulfills with a cryptokey. exceptions the promise is rejected when one of the following exceptions are encountered: invalidaccesserror raised when the master key is not a key for the requested derivation algorithm or if the cryptokey.usages value of that key doesn't contain derivekey. notsupported raised when trying to use an algorithm that is either unknown or isn't suitable for derivation, or if the algorithm requested for the derived key doesn't define a key length. syn...
... secret as a symmetric key to secure their communication, or can use the secret as an input to derive such a key (for example, using the hkdf algorithm). ecdh is specified in rfc 6090. hkdf hkdf is a key derivation function. it's designed to derive key material from some high-entropy input, such as the output of an ecdh key agreement operation. it's not designed to derive keys from relatively low-entropy inputs such as passwords. for that, use pbkdf2. hkdf is specified in rfc 5869. pbkdf2 pbkdf2 is also a key derivation function. it's designed to derive key material from some relatively low-entropy input, such as a password. it derives key material by applying a function such as hmac to the input password along with some salt, and repeating this process many times. the more times the p...
SubtleCrypto - Web APIs
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. ...
...fills with a cryptokey corresponding to the wrapped key given in the parameter. using subtlecrypto we can split the functions implemented by this api into two groups: cryptography functions and key management functions. cryptography functions these are the functions you can use to implement security features such as privacy and authentication in a system. the subtlecrypto api provides the following cryptography functions: * sign() and verify(): create and verify digital signatures. * encrypt() and decrypt(): encrypt and decrypt data. * digest(): create a fixed-length, collision-resistant digest of some data. key management functions except for digest(), all the cryptography functions in the api use cryptographic keys. in the subtlecrypto api a cryptographic key is represented using ...
...to store cryptokey objects. supported algorithms the cryptographic functions provided by the web crypto api can be performed by one or more different cryptographic algorithms: the algorithm argument to the function indicates which algorithm to use. some algorithms need extra parameters: in these cases the algorithm argument is a dictionary object that includes the extra parameters. ...
User Timing API - Web APIs
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. ...
...rmance marks a performance mark is a named performance entry that is created by the application. the mark is a timestamp in the browser's performance timeline. creating a performance mark the performance.mark() method is used to create a performance mark. the method takes one argument, the name of the mark (for example performance.mark("mark-1")). the mark's performance entry will have the following property values: entrytype - set to "mark". name - set to the "name" given when the mark was created. starttime - set to the timestamp when mark() was called. duration - set to "0" (a mark has no duration). retrieving performance marks the performance interface has three methods that can be used to retrieve a mark: performance.getentries() returns all performance entries in the pe...
...midpoint between two marks. creating a performance measure a measure is created by calling performance.measure(measurename, startmarkname, endmarkname) where measurename is the measure's name and startmarkname and endmarkname are the start and end names, respectively, of the marks the measure 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...
WakeLock.request() - Web APIs
Web › API › WakeLock › request
the request() method of the wakelock interface returns a promise that resolves with a wakelocksentinel object, which allows control over screen dimming and locking. syntax var wakelock = navigator.wakelock.request(type); parameters type options are as follows: 'screen': requests a screen wake lock. prevents devices from dimming or locking the screen. 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. document is not fully active. ...
...the screen. 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. document is not fully active. document is hidden. user agent could not acquire platform's wake lock. examples the following asynchronous function requests a wakelocksentinel object. the request() method is wrapped in a try...catch statement to account for if the browser refuses the request for any reason. ...
...les the following asynchronous function requests a wakelocksentinel object. the request() method is wrapped in a try...catch statement to account for if the browser refuses the request for any reason. const requestwakelock = async () => { try { const wakelock = await navigator.wakelock.request('screen'); } catch (err) { // the wake lock request fails - usually system related, such low as battery console.log(`${err.name}, ${err.message}`); } } requestwakelock(); specifications specification status comment screen wake lock apithe definition of 'request()' in that specification. unknown initial definition. ...
WaveShaperNode - Web APIs
waveshapernode.curve is a float32array of numbers describing the distortion to apply. waveshapernode.oversample is an enumerated value indicating if oversampling must be used. oversampling is a technique for creating more samples (up-sampling) before applying the distortion effect to the audio signal. methods no specific method; inherits methods from its parent, audionode. ...
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ... ...
...hows basic usage of an audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; cur...
WebGLRenderingContext.blendFuncSeparate() - Web APIs
ngcontext.blendfuncseparate() method of the webgl api defines which function is used for blending pixel arithmetic for rgb and alpha components separately. syntax void gl.blendfuncseparate(srcrgb, dstrgb, srcalpha, dstalpha); parameters srcrgb a glenum specifying a multiplier for the red, green and blue (rgb) source blending factors. the default value is gl.one. for possible values, see below. dstrgb a glenum specifying a multiplier for the red, green and blue (rgb) destination blending factors. the default value is gl.zero. for possible values, see below. srcalpha a glenum specifying a multiplier for the alpha source blending factor. the default value is gl.one. for possible values, see below. dstalpha a glenum specifying a multiplier for the alpha destination blending factor. ...
...green and blue (rgb) destination blending factors. the default value is gl.zero. for possible values, see below. srcalpha a glenum specifying a multiplier for the alpha source blending factor. the default value is gl.one. for possible values, see below. dstalpha a glenum specifying a multiplier for the alpha destination blending factor. the default value is gl.zero. for possible values, see below. return value none. exceptions if srcrgb, dstrgb, srcalpha, or dstalpha is not one of the listed possible values, a gl.invalid_enum error is thrown. ...
... factor. the default value is gl.zero. for possible values, see below. return value none. exceptions if srcrgb, dstrgb, srcalpha, or dstalpha is not one of the listed possible values, a gl.invalid_enum error is thrown. if a constant color and a constant alpha value are used together as source (srcrgb) and destination (dstrgb) factors, a gl.invalid_enum error is thrown. ...
WebGLRenderingContext.bufferData() - Web APIs
void gl.bufferdata(target, arraybufferview srcdata, usage, srcoffset, length); parameters target a glenum specifying the binding point (target). possible values: gl.array_buffer: buffer containing vertex attributes, such as vertex coordinates, texture coordinate data, or vertex color data. gl.element_array_buffer: buffer used for element indices. when using a webgl 2 context, the following values are available additionally: gl.copy_read_buffer: buffer for copying from one buffer object to another. gl.copy_write_buffer: buffer for copying from one buffer object to another. gl.transform_feedback_buffer: buffer for transform feedback operations. gl.uniform_buffer: buffer used for storing uniform blocks. gl.pixel_pack_buffer: buffer used for pixel transfer operatio...
... gl.dynamic_draw: the contents are intended to be respecified repeatedly by the application, and used many times as the source for webgl drawing and image specification commands. gl.stream_draw: the contents are intended to be specified once by the application, and used at most a few times as the source for webgl drawing and image specification commands. when using a webgl 2 context, the following values are available additionally: gl.static_read: the contents are intended to be specified once by reading data from webgl, and queried many times by the application. gl.dynamic_read: the contents are intended to be respecified repeatedly by reading data from webgl, and queried many times by the application. gl.stream_read: the contents are intended to be specified once by readin...
...t a gluint specifying the element index offset where to start reading the buffer. length optional a gluint defaulting to 0. return value none. exceptions a gl.out_of_memory error is thrown if the context is unable to create a data store with the given size. a gl.invalid_value error is thrown if size is negative. a gl.invalid_enum error is thrown if target or usage are not one of the allowed enums. examples using bufferdata var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, 1024, gl.static_draw); getting buffer information to check the current buffer usage and buffer size, use the webglrenderingcontext.getbufferparameter() method. gl.getbu...
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
ufferstatus() method of the webgl api returns the completeness status of the webglframebuffer object. syntax glenum gl.checkframebufferstatus(target); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. return value a glenum indicating the completeness status of the framebuffer or 0 if an error occurs. possible enum return values: gl.frameb...
...r attachment points are framebuffer attachment complete. gl.framebuffer_incomplete_missing_attachment: there is no attachment. gl.framebuffer_incomplete_dimensions: height and width of the attachment are not the same. gl.framebuffer_unsupported: the format of the attachment is not supported or if depth and stencil attachments are not the same renderbuffer. ...
...h and stencil attachments are not the same renderbuffer. when using a webgl 2 context, the following values can be returned additionally: gl.framebuffer_incomplete_multisample: the values of gl.renderbuffer_samples are different among attached renderbuffers, or are non-zero if the attached images are a mix of renderbuffers and textures. when using the ovr_multiview2 extension, the following value can be returned additionally: ext.framebuffer_incomplete_view_targets_ovr: if baseviewindex is not the same for all framebuffer attachment points where the value of framebuffer_attachment_object_type is not none, the framebuffer is considered incomplete. examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.create...
WebGLRenderingContext.framebufferRenderbuffer() - Web APIs
object to a webglframebuffer object. syntax void gl.framebufferrenderbuffer(target, attachment, renderbuffertarget, renderbuffer); parameters target a glenum specifying the binding point (target) for the framebuffer. possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. attachment a glenum specifying the attachment point for the render buffer. possible values: gl.color_attachment0: color buffer. gl.depth_...
...ng operations. gl.read_framebuffer: used as a source for reading operations. attachment a glenum specifying the attachment point for the render buffer. possible values: gl.color_attachment0: color buffer. gl.depth_attachment: depth buffer. gl.depth_stencil_attachment: depth and stencil buffer. gl.stencil_attachment: stencil buffer. ...
...gle images in a renderable internal format. renderbuffer a webglrenderbuffer object to attach. return value none. exceptions a gl.invalid_enum error is thrown if target is not gl.framebuffer, gl.draw_framebuffer, or gl.read_framebuffer. a gl.invalid_enum error is thrown if renderbuffertarget is not gl.renderbuffer. a gl.invalid_enum error is thrown if attachment is not one of the allowed enums. examples gl.framebufferrenderbuffer(gl.framebuffer, gl.color_attachment0, gl.renderbuffer, renderbuffer); specifications specification status comment webgl 1.0the definition of 'framebufferrenderbuffer' in that specification. recommendation initial definition for webgl. opengl es 2.0the definition of 'glframebufferrenderbuffer' in that specifi...
WebGLRenderingContext.getFramebufferAttachmentParameter() - Web APIs
hod of the webgl api returns information about a framebuffer's attachment. syntax any gl.getframebufferattachmentparameter(target, attachment, pname); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. attachment a glenum specifying the attachment point for the texture. possible values: gl.color_attachment0: texture attachment for the fram...
...the texture. possible values: gl.color_attachment0: texture attachment for the framebuffer's color buffer. gl.depth_attachment: texture attachment for the framebuffer's depth buffer. gl.stencil_attachment: texture attachment for the framebuffer's stencil buffer. gl.depth_stencil_attachment: texture attachment for both, the depth and stencil buffer. ...
...er of the attached image (webglrenderbuffer or webgltexture). gl.framebuffer_attachment_texture_level: mipmap level. default value: 0. gl.framebuffer_attachment_texture_cube_map_face: the name of cube-map face of the texture. when using the ext_srgb extension: ext.framebuffer_attachment_color_encoding_ext: the framebuffer color encoding. ...
WebGLRenderingContext.getParameter() - Web APIs
the webglrenderingcontext.getparameter() method of the webgl api returns a value for the passed parameter name. syntax any gl.getparameter(pname); parameters pname a glenum specifying which parameter value to return. see below for possible values. return value depends on the parameter. parameter names webgl 1 you can query the following pname parameters when using a webglrenderingcontext. constant returned type description gl.active_texture glenum gl.aliased_line_width_range float32array (with 2 elements) gl.aliased_point_size_range float32array (with 2 elements) gl.alpha_bits glint gl.array_buffer_binding webglbuffer gl.blend glboolean gl.blend_color ...
... constant returned type description gl.copy_read_buffer_binding webglbuffer or null see bindbuffer. gl.copy_write_buffer_binding webglbuffer or null see bindbuffer. gl.draw_bufferi glenum gl.back, gl.none or gl.color_attachment{0-15}. see also drawbuffers. gl.draw_fram...
...glint see pixelstorei. gl.unpack_row_length glint see pixelstorei. gl.unpack_skip_images glint see pixelstorei. gl.unpack_skip_pixels glint see pixelstorei. gl.unpack_skip_rows glint see pixelstorei. gl.vertex_array_binding webglvertexarrayobject or null see bindvertexarray. webgl extensions you can query the following pname parameters when using webgl extensions: constant returned type extension description ext.max_texture_max_anisotropy_ext glfloat ext_texture_filter_anisotropic maximum available anisotropy. ext.fragment_shader_derivative_hint_oes glenum oes_standard_derivatives accuracy of the derivative calculation for the glsl built-in functions...
Basic scissoring - Web APIs
squares using webgl scissoring operations. scissoring establishes a clipping region outside which drawing will not occur. clearing the drawing buffer when scissoring applies this is a simple demonstration of a rendering with scissor(). although the clear() drawing command writes the clear color (set by clearcolor()) to all pixels in the drawing buffer, scissor() defines a mask that only allows pixels inside the specified rectangular area to be updated. this is a good opportunity to talk about the difference between pixels and fragments. a pixel is a picture element (in practice, a point) on the screen, or a single element of the drawing buffer, that area in memory that holds your pixel data (such as rgba color components). a fragment refers to the pixel while it is being handled by t...
... 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...
... paragraph.innerhtml = "failed to get webgl context. " + "your browser or device may not support webgl."; return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); // enable scissoring operation and define the position and // size of the scissoring area. gl.enable(gl.scissor_test); gl.scissor(40, 20, 60, 130); // clear the drawing buffer solid yellow. gl.clearcolor(1.0, 1.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); }, false); the source code of this example is also available on github. « previousnext » ...
Adding 2D content to a WebGL context - Web APIs
ded 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 position is then multiplied by two 4x4 matrices we provide called uprojectionmatrix and umodelviewmatrix; gl_position is set to the result. for more info on projection and other matrixes you might find this article useful. // vertex shader program const vssource = ` attribute vec4 avertexposition; ...
...the shape's corresponding pixel. in this case, we're simply returning white every time, since we're just drawing a white square, with no lighting in use. const fssource = ` void main() { gl_fragcolor = vec4(1.0, 1.0, 1.0, 1.0); } `; initializing the shaders now that we've defined the two shaders we need to pass them to webgl, compile them, and link them together. the code below creates the two shaders by calling loadshader(), passing the type and source for the shader. it then creates a program, attaches the shaders and links them together. if compiling or linking fails the code displays an alert. // // initialize a shader program, so webgl knows how to draw our data // function initshaderprogram(gl, vssource, fssource) { const vertexshader = loadshader(gl, gl.vertex...
... the shader's source code is sent to the shader by calling gl.shadersource(). once the shader has the source code, it's compiled using gl.compileshader(). to check to be sure the shader successfully compiled, the shader parameter gl.compile_status is checked. to get its value, we call gl.getshaderparameter(), specifying the shader and t...
A simple RTCDataChannel sample - Web APIs
brtc api which lets you open a channel between two peers over which you may send and receive arbitrary data. the api is intentionally similar to the websocket api, so that the same programming model can be used for each. 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. we'll cover the mechanics of accomplishing the connection and transmitting and receiving data, but we will save the bits about locating and linking to a remote computer for another example. the html first, let's take a quick look at the html that's needed. there's nothing incredibly complicated here. first, we have a couple of buttons for establishing and closing the co...
...isabled> </label> <button id="sendbutton" name="sendbutton" class="buttonright" disabled> send </button> </div> finally, there's the little box into which we'll insert the messages. this <div> block will be the second peer. <div class="messagebox" id="receivebox"> <p>messages received:</p> </div> the javascript code while you can just look at the code itself on github, below we'll review the parts of the code that do the heavy lifting. the webrtc api makes heavy use of promises. they make it very easy to chain the steps of the connection process together; if you haven't already read up on this functionality of ecmascript 2015, you should read up on them. similarly, this example uses arrow functions to simplify syntax. starting up when the script is run, we set up ...
...on.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 datachannel event handler; this will be called when the data channel is opened; this handler will receive an rtcdatachannel object; you'll see this below. set up the ice candidates the next step is to set up each connection with ice candidate listeners; these will be called when there's a new ice candidate to tell the other side about. note: in a real-world scenario in which the two peers aren't running in the same context, the process is a bit more involved; each side provides, one at a time, a suggested way to connect (for example, udp, udp ...
Taking still photos with WebRTC - Web APIs
it playing by calling htmlmediaelement.play(). the error callback is called if opening the stream doesn't work. this will happen for example if there's no compatible camera connected, or the user denied access. listen for the video to start playing after calling htmlmediaelement.play() on the <video>, there's a (hopefully brief) 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. video.addeventlistener('canplay', function(ev){ if (!streaming) { height = video.videoheight / (video.videowidth/width)...
...gain. handle clicks on the button to capture a still photo each time the user clicks the startbutton, we need to add an event listener to the button, to be called when the click event is issued: startbutton.addeventlistener('click', function(ev){ takepicture(); ev.preventdefault(); }, false); this method is simple enough: it just calls our takepicture() function, defined below in the section capturing a frame from the stream, then calls event.preventdefault() on the received event to prevent the click from being handled more than once. wrapping up the startup() method there are only two more lines of code in the startup() method: clearphoto(); } this is where we call the clearphoto() method we'll describe below in the section clearing the photo box. clearing...
...er tools' style editor; see edit css filters for details on how to do so. using specific devices you can, if needed, restrict the set of permitted video sources to a specific device or set of devices. to do so, call navigator.mediadevices.enumeratedevices(). when the promise is fulfilled with an array of mediadeviceinfo objects describing the available devices, find the ones that you want to allow and specify the corresponding deviceid or deviceids in the mediatrackconstraints object passed into getusermedia(). ...
Using WebRTC data channels - Web APIs
th 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 it to the remote peer for you (by causing it to receive a datachannel event). this is the easy way, and works for a wide variety of use cases, but may not be flexible enough for your needs. write your own code...
... event). this is the easy way, and works for a wide variety of use cases, but may not be flexible enough for your needs. write your own code to negotiate the data transport and write your own code to signal to the other peer that it needs to connect to the new channel. let's look at each of these cases, starting with the first, which is the most common. automatic negotiation often, you can allow the peer connection to handle negotiating the rtcdatachannel connection for you. to do this, simply call createdatachannel() without specifying a value for the negotiated property, or specifying the property with a value of false. this will automatically trigger the rtcpeerconnection to handle the negotiations for you, causing the remote peer to create a data channel and linking the two together...
...th each peer using different properties, and to create channels declaratively by simply using the same value for id. buffering webrtc data channels support buffering of outbound data. this is handled automatically. while there's no way to control the size of the buffer, you can learn how much data is currently buffered, and you can choose to be notified by an event when the buffer starts to run low on queued data. this makes it easy to write efficient routines that make sure there's always data ready to send without over-using memory or swamping the channel completely. <<<write more about using bufferedamount, bufferedamountlowthreshold, onbufferedamountlow, and bufferedamountlow here>>> ... understanding message size limits for any data being transmitted over a network, there are size ...
Writing WebSocket client applications - Web APIs
u need to create a websocket object; this will automatically attempt to open the connection to the server. the websocket constructor accepts one required and one optional parameter: websocket = new websocket(url, protocols); url the url to which to connect; this should be the url to which the websocket server will respond. this should use the url scheme wss://, although some software may allow you to use the insecure ws:// for local connections. protocols optional either a single protocol string or an array of protocol strings. these strings are used to indicate sub-protocols, so that a single server can implement multiple websocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol). if you d...
...ings. these strings are used to indicate sub-protocols, so that a single server can implement multiple websocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol). if you don't specify a protocol string, an empty string is assumed. the constructor will throw a securityerror if the destination doesn't allow access. this may happen if you attempt to use an insecure connection (most user agents now require a secure link for all websocket connections unless they're on the same device or possibly on the same network). connection errors if an error occurs while attempting to connect, first a simple event with the name error is sent to the websocket object (thereby invoking its onerror handler), and the...
...ction to determine if any data has yet to be transmitted on the network. if this value isn't 0, there's pending data still, so you may wish to wait before closing the connection. security considerations websockets should not be used in a mixed content environment; that is, you shouldn't open a non-secure websocket connection from a page loaded using https or vice-versa. most browsers now only allow secure websocket connections, and no longer support using them in insecure contexts. ...
Writing a WebSocket server in C# - Web APIs
to rfc 6455 so it will only handle connections from chrome version 16, firefox 11, ie 10 and over. first steps websockets communicate over a tcp (transmission control protocol) connection. luckily, c# has a tcplistener class which does as the name suggests. it is in the system.net.sockets namespace. it is a good idea to include the namespace with the using keyword in order to write less. it allows usage of a namespace's classes without typing the full namespace every time. tcplistener constructor: tcplistener(system.net.ipaddress localaddr, int port) localaddr specifies the ip of the listener, and port specifies the port. to create an ipaddress object from a string, use the parse static method of ipaddress. methods: start() system.net.sockets.tcpclient accepttcpclient() wai...
... 0) payload length (bit 1:7) 1 0x83=0000011 mask bit: defines whether the "payload data" is masked. if set to 1, a masking key is present in masking-key, and this is used to unmask the "payload data". all messages from the client to the server have this bit set. payload length: if this value is between 0 and 125, then it is the length of message. if it is 126, the following 2 bytes (16-bit unsigned integer) are the length. if it is 127, the following 8 bytes (64-bit unsigned integer) are the length. because the first bit is always 1 for client-to-server messages, you can subtract 128 from this byte to get rid of the mask bit. note that the mask bit is set in our message. this means that the next four bytes (61, 84, 35, and 6) are the mask bytes used to decod...
...offset + i] ^ masks[i % 4]); string text = encoding.utf8.getstring(decoded); console.writeline("{0}", text); } else console.writeline("mask bit not set"); console.writeline(); } } } } client.html <!doctype html> <style> textarea { vertical-align: bottom; } #output { overflow: auto; } #output > p { overflow-wrap: break-word; } #output span { color: blue; } #output span.error { color: red; } </style> <h2>websocket test</h2> <textarea cols=60 rows=6></textarea> <button>send</button> <div id=output></div> <script> // http://www.websocket.org/echo.html var button = document.queryselector("button"), output = document.queryselector("#output"), ...
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
n of the viewer in order to place the virtual camera and render the scene. the only way to obtain a pose that adapts positional information from one space to another is through the xrframe object received by your frame rendering callback function specified when you called the xrsession method requestanimationframe(). ...
...not only does your app need to determine what to show the user during these periods, but it needs to cleanly recover when tracking resumes. once the xr hardware begins providing tracking information, it will continue to do so until the xr session is clsoed. this data is obtained during each f...
... has resumed after being lost when the user position jumps while at the same time the value of emulatedposition changes from true to false. how you handle this depends on your application. if your app provides a way for the user to move through the virtual world without physically moving in the real world (a so-called teleportation mechanic), you can simply accept the new position and continue, allowing the jump from your previously-assumed position to be immediately corrected with the new position. on the other hand, if your app involves the user physically moving in real space to move around through your virtual world, simply adopting the new tracking position and jumping there can be unsettling to the user, and should be avoided if possible. instead, use the difference between the current...
Web Animations API Concepts - Web APIs
s and css transitions specs. the internet explorer team requested an animations api to consolidate and normalize animation functionality across all browsers, and thus efforts began 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...
...r until the window is closed. spread along that timeline according to their durations are our animations. each animation is anchored to a point in the timeline by its starttime, representing the moment along the document’s timeline when the animation starts playing. all the animation's playback relies on this timeline: seeking the animation moves the animation’s position along the timeline; slowing down or speeding up the playback rate condenses or expands its spread across the timeline; repeating the animation lines up additional iterations of it along the timeline. in the future, we might have timelines based on gestures or scroll position or even parent and child timelines. the web animations api opens up so many possibilities! animation the animation model can be thought of as an a...
...ve already been outlined in the currently-in-progress level 2 spec of the web animations api. assembling the animation from disparate pieces we can assemble all these pieces together to create a working animation with the animation() constructor or we can use the element.animate() shortcut function. (read more about how to use element.animate() in using the web animations api.) uses the api allows for the creation of dynamic animations that can be updated on the fly as well as more straightforward, declarative animations like those css creates. it can be used in automated tests to ensure that your ui animations are running correctly. it opens up the browser’s rendering engine for building animation development tools like timelines. it is also a performant base on which to build a custom...
Visualizations with Web Audio API - Web APIs
dataarray); we now have the audio data for that moment in time captured in our array, and can proceed to visualize it however we like, for example by plotting it onto an html5 <canvas>. let's go on to look at some specific examples. ...
...ata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); now we set our barwidth to be equal to the canvas width divided by the number of bars (the buffer length). however, we are also multiplying that width by 2.5, because most of the frequencies will come back as having no audio in them, as most of the sounds we hear every day are in a certain lower frequency range. we don't want to display loads of empty bars, therefore we simply shift the ones that will display regularly at a noticeable height across so they fill the canvas display. we also set a barheight variable, and an x variable to record how far across the screen to draw the current bar. var barwidth = (width / bufferlength) * 2.5; var barheight; var x = 0; as before, we now sta...
...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 invoke the draw() function to set the whole process in motion. draw(); this code gives us a result like the following: note: the examples listed in this article have shown usage of analysernode.getbytefrequencydata() and analysernode.getbytetimedomaindata(). for working examples showing analysernode.getfloatfrequencydata() and analysernode.getfloattimedomaindata(), refer to our voice-change-o-matic-float-data demo (see the source code too) — this is exactly the same as the original voice-change-o-matic,...
Using the Web Storage API - Web APIs
es all set the (same) colorsetting entry: localstorage.colorsetting = '#a4509b'; localstorage['colorsetting'] = '#a4509b'; localstorage.setitem('colorsetting', '#a4509b'); note: it's recommended to use the web storage api (setitem, getitem, removeitem, key, length) to prevent the pitfalls associated with using plain objects as key-value stores. the two mechanisms within web storage are as follows: sessionstorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores). localstorage does the same thing, but persists even when the browser is closed and reopened. these mechanisms are available via the window.sessionstorage and window.localstorage properties (to be...
...ing localstorage to be able to use localstorage, we should first verify that it is supported and available in the current browsing session. testing for availability note: this api is available in current versions of all major browsers. testing for availability is necessary only if you must support very old browsers, such as internet explorer 6 or 7, or in the limited circumstances described below. browsers that support localstorage have a property on the window object named localstorage. however, just asserting that that property exists may throw exceptions. if the localstorage object does exist, there is still no guarantee that the localstorage api is actually available, as various browsers offer settings that disable localstorage. so a browser may support localstorage, but not make it...
...ver a change is made to the storage object (note that this event is not fired for sessionstorage changes). this won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. pages on other domains can't access the same storage objects. ...
Window.localStorage - Web APIs
localstorage is similar to sessionstorage, except that while data stored in localstorage has no expiration time, data stored in sessionstorage gets cleared when the page session ends — that is, when the page is closed. (data in a localstorage object created in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.) data stored in either localstorage is specific to the protocol of the page. ...
...h can be used to access the current origin's local storage space. exceptions securityerror the request violates a policy decision, or the origin is not a valid scheme/host/port tuple (this can happen if the origin uses the file: or data: scheme, for example). for example, the user may have their browser configured to deny permission to persist data for the specified origin. ...
...origin uses the file: or data: scheme, for example). for example, the user may have their browser configured to deny permission to persist data for the specified origin. example the following snippet accesses the current domain's local storage object and adds a data item to it using storage.setitem(). localstorage.setitem('mycat', 'tom'); the syntax for reading the localstorage item is as follows: const cat = localstorage.getitem('mycat'); the syntax for removing the localstorage item is as follows: localstorage.removeitem('mycat'); the syntax for removing all the localstorage items is as follows: localstorage.clear(); note: please refer to the using the web storage api article for a full example. specifications specification status comment html living ...
Privileged features - Web APIs
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. ...
... or 0, this feature removes the titlebar from the new secondary window. mozilla and firefox users can force new windows to always render the titlebar by setting dom.disable_window_open_feature.titlebar to true in about:config or in their user.js file. alwaysraised if on, the new window will always be displayed on top of other browser windows, regardless of whether it is active or not. alwayslowered if on, the new created window floats below, under its own parent when the parent window is not minimized. alwayslowered windows are often referred as pop-under windows. the alwayslowered window can not be on top of the parent but the parent window can be minimized. in ns 6.x, the alwayslowered window has no minimize system command icon and no restore/maximize system command. alwaysontop if...
... close when set to no or 0, this feature removes the system close command icon and system close menu item. it will only work for dialog windows (dialog feature set). close=no will override minimizable=yes. ...
Window.openDialog() - Web APIs
Web › API › Window › openDialog
same way window.open() does; that is, an empty string sets all features to off) except chrome and dialog, which default to on. if the features parameter is a zero-length string, or contains only one or more of the behavior features (chrome, dependent, dialog and modal) the chrome features are assumed "os' choice." that is, window creation code is not given specific instructions, but is instead allowed to select the chrome that best fits a dialog on that operating system. passing extra parameters to the dialog to pass extra parameters into the dialog, you can simply supply them after the windowfeatures parameter: opendialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98); the extra parameters will then get packed into a property named arguments of type array, and this property ge...
... to pass extra parameters into the dialog, you can simply supply them after the windowfeatures parameter: opendialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98); the extra parameters will then get packed into a property named arguments of type array, and this property gets added to the newly opened dialog window. to access these extra parameters from within dialog code, use the following scheme: var food = window.arguments[0]; var price = window.arguments[1]; note that you can access this property from within anywhere in the dialog code. (another example). returning values from the dialog since window.close() erases all properties associated with the dialog window (i.e. the variables specified in the javascript code which gets loaded from the dialog), it is not possible ...
...ters. you can then access this object from within the dialog code and set properties on it, containing the values you want to return or preserve past the window.close() operation. var retvals = { address: null, delivery: null }; opendialog("http://example.tld/zzz.xul", "dlg", "modal", "pizza", 6.98, retvals); if you set the properties of the retvals object in the dialog code as described below, you can now access them via the retvals array after the opendialog() call returns. inside the dialog code, you can set the properties as follows: var retvals = window.arguments[2]; retvals.address = enteredaddress; retvals.delivery = "immediate"; specification this is not part of any specification. browser compatibility the compatibility table in this page is generated from structured da...
window.postMessage() - Web APIs
window.postmessage() provides a controlled mechanism to securely circumvent this restriction (if used properly). ...
...iling to provide a specific target discloses the data you send to any interested malicious site. transfer optional is a sequence of transferable objects that are transferred with the message. the ownership of these objects is given to the destination side and they are no longer usable on the sending side. the dispatched event otherwindow can listen for dispatched messages by executing the following javascript: window.addeventlistener("message", receivemessage, false); function receivemessage(event) { if (event.origin !== "http://example.org:8080") return; // ... } the properties of the dispatched message are: data the object passed from the other window. origin the origin of the window that sent the message at the time postmessage was called. this string is the concate...
...; function receivemessage(event) { if (event.origin !== "http://example.org:8080") return; // ... } the properties of the dispatched message are: data the object passed from the other window. origin the origin of the window that sent the message at the time postmessage was called. this string is the concatenation of the protocol and "://", the host name if one exists, and ":" followed by a port number if a port is present and differs from the default port for the given protocol. examples of typical origins are https://example.org (implying port 443), http://example.net (implying port 80), and http://example.com:8080. note that this origin is not guaranteed to be the current or future origin of that window, which might have been navigated to a different location since postmes...
Window - Web APIs
Web › API › Window
even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as resizeto() and innerheight. generally, anything that can't reasonably pertain to a tab pertains to the window instead. ...
...used for creating a web worker. xmlserializer converts a dom tree into xml or html source. properties this interface inherits properties from the eventtarget interface and implements properties from the windoworworkerglobalscope and windoweventhandlers mixins. note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below. window.closed read only this property indicates whether the current window is closed or not. window.console read only returns a reference to the console object which provides access to the browser's debugging console. window.controllers read only returns the xul controller objects for the current chrome window. window.customelements read only returns a reference to the customelem...
...n connected or the first time a button/axis of the gamepad is used. also available via the ongamepadconnected property. gamepaddisconnected fired when the browser detects that a gamepad has been disconnected. also available via the ongamepaddisconnected property history events hashchange fired when the fragment identifier of the url has changed (the part of the url beginning with and following the # symbol). also available via the onhashchange property. pagehide sent when the browser hides the current document while in the process of switching to displaying in its place a different document from the session's history. this happens, for example, when the user clicks the back button or when they click the forward button to move ahead in session history. also available through the ...
Worker() - Web APIs
Web › API › Worker › Worker
y 2.7) and later accept data uris, that's not the case in all other browsers. syntax var myworker = new worker(aurl, options); parameters aurl a usvstring representing the url of the script the worker will execute. it must obey the same-origin policy. options optional an object containing option properties that can be set when creating the object instance. available properties are as follows: type: a domstring specifying the type of worker to create. the value can be classic or module. if not specified, the default used is classic. credentials: a domstring specifying the type of credentials to use for the worker. the value can be omit, same-origin, or include. if not specified, or if type is classic, the default used is omit (no credentials required). name: a domstring speci...
... for the worker. the value can be omit, same-origin, or include. if not specified, or if type is classic, the default used is omit (no credentials required). name: a domstring specifying an identifying name for the dedicatedworkerglobalscope representing the scope of the worker, which is mainly useful for debugging purposes. ...
...s mainly useful for debugging purposes. exceptions a securityerror is raised if the document is not allowed to start workers, e.g. if the url has an invalid syntax or if the same-origin policy is violated. a networkerror is raised if the mime type of the worker script is incorrect. it should always be text/javascript. a syntaxerror is raised if aurl cannot be parsed. examples the following code snippet shows creation of a worker object using the worker() constructor and subsequent usage of the object: var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } for a full example, see our basic dedicated worker example (run dedicated worker). specifications spe...
Worklet.addModule() - Web APIs
Web › API › Worklet › addModule
the addmodule() method of the worklet interface loads the module in the given javascript file and adds it to the current worklet. syntax addpromise = worklet.addmodule(moduleurl); addpromise = worklet.addmodule(moduleurl, options); parameters moduleurl a string containing the url of a javascript file with the module to add. options optional an object with any of the following options: credentials: a requestcredentials value that indicates whether to send credentials (e.g. cookies and http authentification) when loading the module. can be one of "omit", "same-origin", or "include". defaults to "same-origin". see also request.credentials. return value a promise that resolves once the module from the given url has been added. the promise doesn't return any value. ...
...dentials (e.g. cookies and http authentification) when loading the module. can be one of "omit", "same-origin", or "include". defaults to "same-origin". see also request.credentials. return value a promise that resolves once the module from the given url has been added. the promise doesn't return any value. exceptions if addmodule() fails, it rejects the promise, delivering one of the following errors to the rejection handler. aborterror the specified script is invalid or could not be loaded. syntaxerror the specified moduleurl is invalid. examples audioworklet example const audioctx = new audiocontext(); const audioworklet = audioctx.audioworklet; await audioworklet.addmodule('modules/bypassfilter.js', { credentials: 'omit', }); paintworklet example css.paintworklet.a...
... working draft ...
WritableStream.WritableStream() - Web APIs
the writablestream() constructor creates a new writablestream object instance. syntax var writablestream = new writablestream(underlyingsink[, queuingstrategy]); parameters underlyingsink an object containing methods and properties that define how the constructed stream instance will behave. underlyingsink can contain the following: start(controller) optional this is a method, called immediately when the object is constructed. the contents of this method are defined by the developer, and should aim to get access to the underlying sink. if this process is to be done asynchronously, it can return a promise to signal success or failure. the controller parameter passed to this method is a writablestreamdefaultcontroller. this can be used by the developer to control the stream dur...
...nderlying sink. it can return a promise to signal success or failure of the write operation. the controller parameter passed to this method is a writablestreamdefaultcontroller that can be used by the developer to control the stream as more chunks are submitted for writing. this method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). close(controller) optional this method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. the contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. if this process is asynchronous, it can return a promise to signal success or failure. this method will be called only afte...
...s the size to use for each chunk, in bytes. note: you could define your own custom queuingstrategy, or use an instance of bytelengthqueuingstrategy or countqueuingstrategy for this object value. if no queuingstrategy is supplied, the default used is the same as a countqueuingstrategy with a high water mark of 1. return value an instance of the writablestream object. examples the following example illustrates several features of this interface. it shows the creation of the writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is use...
HTML in XMLHttpRequest - Web APIs
to get an overview of how to use xmlhttprequest in general, see using xmlhttprequest. limitations to discourage the synchronous use of xmlhttprequest, html support is not available in the synchronous mode. also, html support is only available if the responsetype property has been set to "document". ...
.... function htmlinxhr() { if (!window.xmlhttprequest) return false; var req = new window.xmlhttprequest(); req.open('get', window.location.href, false); try { req.responsetype = 'document'; } catch(e) { return true; } return false; } view on jsfiddle this method is synchronous, does not rely on external assets though it may not be as reliable as method 2 described below since it does not check the actual feature but an indication of that feature. method 2 there are two challenges to detecting exactly if a browser supports html parsing in xmlhttprequest. first, the detection result is obtained asynchronously, because html support is only available in the asynchronous mode. second, you have to actually fetch a test document over http, because testing with a data...
...html support is only available in the asynchronous mode. second, you have to actually fetch a test document over http, because testing with a data: url would end up testing data: url support at the same time. thus, to detect html support, a test html file is needed on the server. ...
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
here is a an example javascript function that prints the security details of an xmlhttprequest sent over ssl. the function is passed the channel property of an xmlhttprequest to extract the following information: was the connection secure? was the used ssl certificate valid and what are its details (owner, expiration, certificate authority, etc.)? notes: this code requires elevated privileges to run; you can only call it from a browser extension or from a xulrunner application. the channel property becomes available only after the request is sent and the connection was established, that is, on readystate loaded, interactive or completed. by setting the mozbackgroundrequest property of the request object and modifying the example appropriately, you can create your own alert dia...
...ed errors. try { errorclass = nsserrorsservice.geterrorclass(status); } catch (ex) { //catching security protocol exception errorclass = 'securityprotocol'; } if (errorclass == nsinsserrorsservice.error_class_bad_cert) { errtype = 'securitycertificate'; } else { errtype = 'securityprotocol'; } // nss_sec errors (happen below the base value because of negative vals) if ((status & 0xffff) < math.abs(nsinsserrorsservice.nss_sec_error_base)) { // the bases are actually negative, so in our positive numeric space, we // need to subtract the base off our value. let nsserr = math.abs(nsinsserrorsservice.nss_sec_error_base) - (status & 0xffff); switch (nsserr) { case 11: // sec_error_expir...
... sha1 fingerprint = f4:99:64:18:6b:7d:c8:fa:c0:0c:2e:a9:61:77:28:67:13:c4:97:7b valid from 7/14/2011 0:00:00 am valid until 8/20/2013 23:59:59 pm ...
XRSession.requestReferenceSpace() - Web APIs
requestreferencespace(referencespacetype); parameters type a domstring specifying the type of reference space for which an instance is to be returned. the string must be one of those found in the xrreferencespacetype enumerated type. the reference space returned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace. the "interface" column in the table below indicates which of the two types is returned 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 use...
...placed in a safe location for the viewer to stand, where the value of the y axis is 0 at floor level. if that floor level isn't known, the user agent will estimate the floor level. if the estimated floor level is non-zero, the browser is expected to round it such a way as to avoid fingerprinting (likely to the nearest centimeter). xrreferencespace unbounded a tracking space which allows the user total freedom of movement, possibly over extremely long distances from their origin point. the viewer isn't tracked at all; tracking is optimized for stability around the user's current position, so the native origin may drift as needed to accommodate that need. xrreferencespace viewer a tracking space whose native origin tracks the viewer's position and orientation. this...
...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 name is found in the list below: notsupportederror the requested reference space is not supported. specifications specification status comment webxr device apithe definition of 'requestreferencespace()' in that specification. working draft initial definition. ...
XRSession.updateRenderState() - Web APIs
face of webxr api schedules changes to be applied to the active render state prior to rendering of the next frame. syntax xrsession.updaterenderstate(newstate) parameters newstate an object conforming to the xrrenderstateinit dictionary specifying the properties of the session's renderstate to update before rendering the next frame. the specified object may have any combination of the following fields. baselayer optional an xrwebgllayer object from which the webxr compositor will obtain imagery. this is null by default. depthfar optional a floating-point value specifying the distance in meters from the viewer to the far clip plane, which is a plane parallel to the display surface beyond which no further rendering will occur. all rendering will take place between the distances s...
...puting the projection matrix for an inline xrsession. the projection matrix calculation also takes into account the output canvas's aspect ratio. this property must not be specified for immersive sessions, so the value is null by default for immersive sessions. the default value is otherwise π * 0.5 (half of the value of pi). return value none. exceptions this method may throw any of the following exceptions. these are true exceptions, since this method does not return a promise. invalidstateerror this may occur for one of the following reasons: the xrsession has already ended, so you cannot change its render state. the baselayer specified in newstate was created by an xrsession other than the one on which updaterenderstate() was called. the inlineverticalfieldofview prop...
... examples this example creates a webgl context that is compatible with an immersive xr device and then uses it to create an xrwebgllayer. updaterenderstate() is then called to associate the new xrwebgllayer. ...
XRSession - Web APIs
Web › API › XRSession
session. to open a webxr session, use the xrsystem interface's requestsession() method. with xrsession methods, you can poll the viewer's position and orientation (the xrviewerpose), gather information about the user's environment, and present imagery to the user. xrsession supports both inline and immersive virtual and augmented reality modes. properties in addition to the properties listed below, xrsession inherits properties from its parent interface, eventtarget. environmentblendmode read only returns this session's blend mode which denotes how much of the real-world environment is visible through the xr device and how the device will blend the device imagery with it. note: environmentblendmode() is part of the webxr augmented reality module, which has not been completed. ...
...nd how far away objects can be and still get rendered), as well as field of view information. visibilitystate read only a domstring whose value is one of those found in the xrvisibilitystate enumerated type, indicating whether or not the session's imagery is visible to the user, and if so, if it's being visible but not currently the target for user events. methods xrsession provides the following methods in addition to those inherited from its parent interface, eventtarget. cancelanimationframe() removes a callback from the animation frame painting callback from xrsession's set of animation frame rendering callbacks, given the identifying handle returned by a previous call to requestanimationframe(). end() ends the webxr session. returns a promise which resolves when the session ...
...rboundedreferencespace which was requested, or throws a notsupportederror if the requested space type isn't supported by the device. updaterenderstate() updates the properties of the session's render state to match the values specified in the specified xrrenderstateinit dictionary. any properties not included in the given dictionary are left unchanged from their current values. events the following events are delivered to xrsession objects. event description end sent to the xrsession object after the webxr session has ended and all hardware-related functions have completed. the event is represented by an object of type xrsessionevent. also available through the onend event handler property. inputsourceschange an event of type xrinputsourcescha...
XRSystem: requestSession() - Web APIs
onfigure the new xrsession. see specifying session options for details on how to configure a webxr session. return value a promise that resolves with an xrsession object if the device and user agent support the requested mode and features. exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: invalidstateerror the requested session mode is immersive-vr but there is already an immersive vr session either currently active or in the process of being set up. there can only be one immersive vr session at a time. notsupportederror there is no webxr-compatible device available, or the device does not support the specified sessionmode; this can also be thrown if any of the required ...
...le device available, or the device does not support the specified sessionmode; this can also be thrown if any of the required options are unsupported. securityerror permission to enter the specified xr mode is denied. this can happen for a number of reasons, which are covered in more detail in permissions and security in webxr device api. examples creating an immersive vr session the following example calls requestsession() requesting an "immersive-vr" session. if the promise resolves, it sets up a session and initiates the animation loop. navigator.xr.requestsession("immersive-vr") .then((xrsession) => { xrsession.addeventlistener('end', onxrsessionended); // do necessary session setup here. // begin the session’s animation loop. xrsession.requestanimationframe(onxranima...
...ner('end', onxrsessionended); // do necessary session setup here. // begin the session’s animation loop. xrsession.requestanimationframe(onxranimationframe); }).catch(function(error) { // "immersive-vr" sessions are not supported console.warn("'immersive-vr' isn't supported, or an error occurred activating vr!"); }); verifying webxr support and using a button to start vr mode the following example shows how to use both issessionsupported() and requestsession(). first, it checks to see if webxr is available by verifying the existence of navigator.xr. next, it calls issessionsupported(), passing it the desired session option before enabling controls for entering xr. adding controls is a necessary step because entering xr requires a user action. finally, the onbuttonclicked() metho...
ARIA live regions - Accessibility
h as role="alert") on the element you want to announce changes to works as long as you add the attribute before the changes occur — either in the original markup, or dynamically using javascript. simple live regions dynamic content which updates without a page reload is generally either a region or a widget. simple content changes which are not interactive should be marked as live regions. below is a list of each related aria live region property with a description. aria-live: the aria-live=politeness_setting is used to set the priority with which screen reader should treat updates to live regions - the possible settings are: off, polite or assertive. the default setting is off. this attribute is by far the most important. aria-controls: the aria-controls=[idlist] is used to assoc...
...l wait until the user pauses before announcing the update. thus, moving down in the list and selecting another planet will not announce updates in the live region. updates in the live region will only be announced for the planet finally chosen. here is a screenshot of voiceover on mac announcing the update (via subtitles) to the live region: preferring specialized live region roles in the following well-known predefined cases it is better to use a specific provided "live region role": role description compatibility notes log chat, error, game or other type of log to maximize compatibility, add a redundant aria-live="polite" when using this role. status a status bar or area of the screen that provides an updated status of some kind. screen re...
...d). <ul id="roster" aria-live="polite" aria-relevant="additions removals"> <!-- use javascript to add remove users here--> </ul> breakdown of aria live properties: aria-live="polite" indicates that the screen reader should wait until the user is idle before presenting updates to the user. this is the most commonly used value, as interrupting the user with "assertive" might interrupt their flow. aria-atomic is not set (false by default) so that only the added or removed users should be spoken and not the entire roster each time. aria-relevant="additions removals" ensures that both users added or removed to the roster will be spoken. ...
Using the aria-describedby attribute - Accessibility
t described them. this is very similar to aria-labelledby: a label describes the essence of an object, while a description provides more information that the user might need. the aria-describedby attribute is not used only for form elements; it is also used to associate static text with widgets, groups of elements, panes, regions that have a heading, definitions, and more. the examples section below provides more information about how to use the attribute in these cases. this attribute can be used with any typical html form element; it is not limited to elements that have an aria role assigned. value a space-separated list of element ids possible effects on user agents and assistive technology note: opinions may differ on how assistive technology should handle this technique. the inf...
...ted to elements that have an aria role assigned. value a space-separated list of element ids possible effects on user agents and 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: application landmark descriptions in the example below, an introductory paragraph describes a calendar application. aria-describedby is used to associate the paragraph with the application container. <div role="application" aria-labelledby="calendar" aria-describedby="info"> <h1 id="calendar">calendar</h1> <p id="info"> this calendar shows the game schedule for the boston red sox. </p> <div role="grid"> ... </div>...
...cation. aria-describedby is used to associate the paragraph with the application container. <div role="application" aria-labelledby="calendar" aria-describedby="info"> <h1 id="calendar">calendar</h1> <p id="info"> this calendar shows the game schedule for the boston red sox. </p> <div role="grid"> ... </div> </div> example 2: a close button in the example below, a link that functions as a 'close' button on a dialog is described elsewhere in the document. the aria-describedby attribute is used to associate the description with the link. <button aria-label="close" aria-describedby="descriptionclose" onclick="mydialog.close()">x</button> ... <div id="descriptionclose">closing this window will discard any information entered and return you back to th...
Using the aria-invalid attribute - Accessibility
nform the user when a field is invalid. application authors should provide suggestions for correcting the problem, if possible. authors may prevent a form from being submitted. 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: simple form validation the following snippet shows a simplified version of two form fields with a validation function attached to the blur event. note that since the default value for aria-required is false, it is not strictly necessary to add the attribute to input. <input name="name" id="name" aria-required="true" aria-invalid="false" onblur="checkvalidity('name', ' ', 'invalid name entered (requires both first and la...
... entered (requires both first and last name)');"/> <br /> <input name="email" id="email" aria-required="true" aria-invalid="false" onblur="checkvalidity('email', '@', 'invalid e-mail address');"/> note that it is not necessary to validate the fields immediately on blur; the application could wait until the form is submitted (though this is not necessarily recommended). ...
...ion will likely be more sophisticated): function checkvalidity(aid, asearchterm, amsg){ var elem = document.getelementbyid(aid); var invalid = (elem.value.indexof(asearchterm) < 0); if (invalid) { elem.setattribute("aria-invalid", "true"); updatealert(amsg); } else { elem.setattribute("aria-invalid", "false"); updatealert(); } } the snippet below shows the alert functions, which add (or remove) the error message: function updatealert(msg) { var oldalert = document.getelementbyid("alert"); if (oldalert) { document.body.removechild(oldalert); } if (msg) { var newalert = document.createelement("div"); newalert.setattribute("role", "alert"); newalert.setattribute("id", "alert"); var con...
ARIA: figure role - Accessibility
the aria figure role can be used to identify a figure inside page content where appropriate semantics do not already exist. a figure is generally considered to be one or more images, code snippets, or other content that puts across information in a different way to a regular flow of text. <div role="figure" aria-labelledby="caption"> <img src="image.png" alt="full alternative image description"> <p id="caption">figure 1: the caption</p> </div> in the above example, we have a figure that consists of two separate content items — an image and a caption. this is wrapped by a <div> element that identifies the content as a figure using role="figure". instead of using aria to create a figure, consider using the native, semantic html <figure> element. along with the <figcaption> elem...
...ure 1: the caption</p> </div> in the above example, we have a figure that consists of two separate content items — an image and a caption. this is wrapped by a <div> element that identifies the content as a figure using role="figure". instead of using aria to create a figure, consider using the native, semantic html <figure> element. along with the <figcaption> element. see best practices below. description any content that should be grouped together and consumed as a figure (which could include images, video, audio, code snippets, or other content) can be identified as a figure using role="figure". there are no hard and fast rules about how you should write your figure content. you should make sure that it is accessible just like any other content. for example, make sure it is perce...
...</div> best practices only use role="figure" if you have to — for example if you don't have control over your html but are able to improve accessibility dynamically after the fact with javascript. if at all possible, you should use the appropriate semantic html elements to mark up a figure and its caption — <figure> and <figcaption>. ...
ARIA: gridcell role - Accessibility
columns, and aria-rowindex to describe a gridcell's order in the list of rows. use aria-colcount and aria-rowcount on the parent element with role="grid" applied to it to set the total number of columns or rows. this sample code demonstrates a table-style grouping of information where the third and fourth columns have been removed. ...
...le grouping of content does not provide information about the columns and rows, gridcells must have their positions programatically described by using aria-describedby. the ids provided for aria-describedby should correspond to parent elements intended to be the rows and columns. by referencing the parent elements with roles of rowheader or columnheader applied to them via aria-describedby, it allows assistive technology to understand the position and relationship of the gridcell element to the rest of the table-style grouping of content. interactive grids and treegrids editable cells both td elements and elements with a role of gridcell applied to them can be made editable, mimicking functionality similar to editing a spreadsheet. this is done by applying the html contenteditable attribu...
...ch element is the associated column header. aria-colindex identifies the position of an element in relation to the rest of the table-style grouping of information's columns. rowheader specifies which element is the associated row header. aria-rowindex identifies the position of an element in relation to the rest of the table-style grouping of information's rows. ...
ARIA: Region role - Accessibility
, it may be worth reinvestigating the page's overall structure. best practices prefer html using the <section> element will automatically communicate that a section has a role of region if it is given an accessible name. if at all possible, prefer using it instead. labeling landmarks if there is more than one region landmark role in a document, provide a label for each one. this label will allow an assitive technology user to be able to quickly understand the purpose of each landmark. <div role="region" aria-labelledby="heading"> <h3 id="use-discretion">please use the <code>region</code> role with discretion</h3> <!-- content --> </div> ... <div role="region" aria-labelledby="please-reconsider"> <h3 id="please-reconsider">please reconsider your document structure</h3> <!-- con...
...h3 id="use-discretion">please use the <code>region</code> role with discretion</h3> <!-- content --> </div> ... <div role="region" aria-labelledby="please-reconsider"> <h3 id="please-reconsider">please reconsider your document structure</h3> <!-- content --> </div> in this example, the region's label is being generated by the aria-labelledby attribute. scrolling content areas with overflow text if there is a content area with tabindex="0", add role="region" to convey to screen reader users that is a generic region. this is done to allow keyboard-only users to scroll regions with overflow text. svg role="region" can be declared on areas of svg along with an aria-label to allow individual sections of the svg to be described. added benefits certain technologies such as browser ex...
... landmarks browser extension specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'aria region role' in that specification. ...
ARIA: checkbox role - Accessibility
html <span role="checkbox" id="chkpref" aria-checked="false" onclick="changecheckbox()" onkeypress="changecheckbox()" tabindex="0" aria-labelledby="chk1-label"></span> <label id="chk1-label" onclick="changecheckbox()" onkeypress="changecheckbox()">remember my prefer...
... note: opinions may differ on how assistive te...
... note: opinions may differ on how assistive technology should handle this technique. ...
WAI-ARIA Roles - Accessibility
a stream of rich content that may continue scrolling infinitely by loading more content as the user reads.aria: figure rolethe aria figure role can be used to identify a figure inside page content where appropriate semantics do not already exist. a figure is generally considered to be one or more images, code snippets, or other content that puts across information in a different way to a regular flow of text.aria: form rolethe form landmark role can be used to identify a group of elements on a page that provide equivalent functionality to an html form.aria: grid rolethe grid role is for a widget that contains one or more rows of cells. the position of each cell is significant and can be focused using keyboard input.aria: gridcell rolethe gridcell role is used to make a cell in a grid or treeg...
...aria: timer rolethe timer role indicates to assistive technologies that an element is a numerical counter the amount of elapsed time from a starting point or the remaining time until an end point. please claim the role you want to work on by adding your name after the role's name: (old pages are linked from https://developer.mozilla.org/docs/web/accessibility/aria/...
...logies that an element is a numerical counter the amount of elapsed time from a starting point or the remaining time until an end point. please claim the role you want to work on by adding your name after the role's name: (old pages are linked from https://developer.mozilla.org/docs/web/accessibility/aria/aria_techniques). ones for which the first draft is completed have been removed from the below list. alertdialog banner combobox command columnheader (estelle) complementary composite definition directory feed gridcell (eric e) group input landmark link - old page listbox log - old page marquee math menu menubar menuitem menuitemcheckbox menuitemradio none note option presentation progressbar - old page radio - old page radiogroup range region roletype...
Accessibility and Spacial Patterns - Accessibility
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. ...
...d the guidelines for characterizing patterned images that could precipitate seizures. they revised the guidelines to their fundamental core, and came up with a surprisingly simple, but powerful test. which they published in the paper, characterizing the patterned images that precipitate seizures and optimizing guidelines to prevent them the steps necessary to evaluate material reduce to the following: look at the screen are there more than five stripes? if so, do they last longer than 0.5 s? if so, does the brightness exceed the stated limit? if so, categorize the motion of the pattern are the guidelines contravened? if so, reduce brightness. text and padding wcag standards for contrast perception do not take into account the effect of padding. for example, blue text on a gray b...
...the manner in which he displays math. animation figures strongly in this arena. for example, "how" an object looks when it is rotated, from different angles, how they look sliced, and how they relate to each other in space all make a difference in an ability to understand math in spatial terms. braille modern technology enalbes non-experts to print braille. adobe illustrator, for example, allows one to typeset ada braille for printing out. the ability to represent spatial patterns accurate to those who are blind is critical for accessibility. for example, knowing braille is not enough. the braille dots have to be spatially apart from one another so as to be readable in a "human" way. the human touch does distinguish with ease braille dots that are too close or too far apart from o...
Accessibility
ility learning area contains modern, up-to-date tutorials covering accessibility essentials: what is accessibility? this article starts off the module with a good look at what accessibility actually is — this includes what groups of people we need to consider and why, what tools different people use to interact with the web, and how we can make accessibility part of our web development workflow. ...
...t workflow. html: a good basis for accessibility a great deal of web content can be made accessible just by making sure the correct html elements are used for the correct purpose at all times. this article looks in detail at how html can be used to ensure maximum accessibility. css and javascript accessibility best practices css and javascript, when used properly, also have the potential to allow for accessible web experiences ... or they can significantly harm accessibility if misused. this article outlines some css and javascript best practices that should be considered to ensure even complex content is as accessible as possible. ...
... accessibility. css and javascript accessibility best practices css and javascript, when used properly, also have the potential to allow for accessible web experiences ... or they can significantly harm accessibility if misused. this article outlines some css and javascript best practices that should be considered to ensure even complex content is as accessible as possible. wai-aria basics following on from the previous article, sometimes making complex ui controls that involve unsemantic html and dynamic javascript-updated content can be difficult. wai-aria is a technology that can help with such problems by adding in further semantics that browsers and assistive technologies can recognize and use to let users know what is going on. here we'll show how to use it at a basic level to impro...
-moz-image-rect - CSS: Cascading Style Sheets
mage within the specified image. right the right edge, specified as an <integer> or <percentage>, of the sub-image within the specified image. bottom the bottom edge, specified as an <integer> or <percentage>, of the sub-image within the specified image. left the left edge, specified as an <integer> or <percentage>, of the sub-image within the specified image. description this property allows you to, for example, use different parts of one larger image as backgrounds in different parts of your content. this works very similarly to the -moz-image-region property, which is used with the list-style-image property to use parts of an image as the bullets in lists. however, this can be used for any css background. the syntax for the rectangle is similar to the rect() function generating ...
...absolute; } this is the top-left corner of the image. it defines a rectangle containing the top-left quarter of the image in the file firefox.jpg. #box2 { background-image: -moz-image-rect(url(https://mdn.mozillademos.org/files/12053/firefox.png), 0%, 100%, 50%, 50%); width:133px; height:136px; position:absolute; } this defines the top-right corner of the image. ...
...notice that before it begins doing so it saves a copy of the last box's style since it will be overwritten by the third element's style. by simply copying the values of the background-image property from one element to the next with each mouse click, we achieve the desired effect. what it looks like specifications not part of any standard. ...
-webkit-line-clamp - CSS: Cascading Style Sheets
the -webkit-line-clamp css property allows limiting of the contents of a block container to the specified number of lines. it only works in combination with the display property set to -webkit-box or -webkit-inline-box and the -webkit-box-orient property set to vertical. in most cases you will also want to set overflow to hidden, otherwise the contents won't be clipped but an ellipsis will still be shown after the specified number of lines. when applied to anchor elements, the truncating can happen in the middle of the text, not necessarily at the end. note: this property was originally implemented in webkit and has some issues. it got standardized for legacy support. ...
...l also want to set overflow to hidden, otherwise the contents won't be clipped but an ellipsis will still be shown after the specified number of lines. when applied to anchor elements, the truncating can happen in the middle of the text, not necessarily at the end. note: this property was originally implemented in webkit and has some issues. it got standardized for legacy support. the css overflow module level 3 specification also defines a line-clamp property, which is meant to replace this property and avoid its issues. syntax /* keyword value */ -webkit-line-clamp: none; /* <integer> values */ -webkit-line-clamp: 3; -webkit-line-clamp: 10; /* global values */ -webkit-line-clamp: inherit; -webkit-line-clamp: initial; -webkit-line-clamp: unset; none this value specifies that the...
...al syntax none | <integer> examples truncating a paragraph html <p> in this example the <code>-webkit-line-clamp</code> property is set to <code>3</code>, which means the text is clamped after three lines. an ellipsis will be shown at the point where the text is clamped. </p> css p { width: 300px; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; } result specifications specification status comment css overflow module level 3the definition of '-webkit-line-clamp' in that specification. working draft initial definition ...
::-webkit-meter-even-less-good-value - CSS: Cascading Style Sheets
syntax ::-webkit-meter-even-less-good-value specifications not part of any standard. ...
... syntax ::-webkit-meter-even-less-good-value specifications not part of any standard. ...
... syntax ::-webkit-meter-even-less-good-value specifications not part of any standard. ...
::cue - CSS: Cascading Style Sheets
Web › CSS › ::cue
the ::cue css pseudo-element matches webvtt cues within a selected element. this can be used to style captions and other cues in media with vtt tracks. ::cue { color: yellow; font-weight: bold; } the properties are applied to the entire set of cues as if they were a single unit. the only exception is that background and its longhand properties apply to each cue individually, to avoid creating boxes and obscuring unexpectedly large areas of the media. ...
...weight: bold; } the properties are applied to the entire set of cues as if they were a single unit. the only exception is that background and its longhand properties apply to each cue individually, to avoid creating boxes and obscuring unexpectedly large areas of the media. ...
... ::cue { color: #fff; background-color: rgba(0, 0, 0, 0.6); } specifications specification status comment webvtt: the web video text tracks formatthe definition of '::cue' in that specification. candidate recommendation initial definition. ...
:host-context() - CSS: Cascading Style Sheets
the :host-context() css pseudo-class function selects the shadow host of the shadow dom containing the css it is used inside (so you can select a custom element from inside its shadow dom) — but only if the selector given as the function's parameter matches the shadow host's ancestor(s) in the place it sits inside the dom hierarchy. ...
... note: this has no effect when used outside a shadow dom. ...
... in this example we have a simple custom element — <context-span> — that you can wrap around text: <h1>host selectors <a href="#"><context-span>example</context-span></a></h1> inside the element's constructor, we create style and span elements, fill the span with the content of the custom element, and fill the style e...
:placeholder-shown - CSS: Cascading Style Sheets
aceholder-shown { border: 2px solid silver; } syntax :placeholder-shown examples basic example this example applies special font and border styles when the placeholder is shown. ...
...ial font and border styles when the placeholder is shown. html <input placeholder="type something here!"> css input { border: 1px solid black; padding: 3px; } input:placeholder-shown { border-color: teal; color: purple; font-style: italic; } result overflowing text when form fields are too small, placeholder text can get cropped in an undesirable way. you can use the text-overflow property to alter the way overflowing text is displayed. html <input id="input1" placeholder="name, rank, and serial number"> <br><br> <input id="input2" placeholder="name, rank, and serial number"> css #input2:placeholder-shown { text-overflow: ellipsis; } result customized input field the following example highlights the branch and id code fields with a custom style. html <form id=...
... working draft initial definition. ...
:valid - CSS: Cascading Style Sheets
Web › CSS › :valid
the :valid css pseudo-class represents any <input> or other <form> element whose contents validate successfully. this allows to easily make valid fields adopt an appearance that helps the user confirm that their data is formatted properly. /* selects any valid <input> */ input:valid { background-color: powderblue; } this pseudo-class is useful for highlighting correct fields for the user. ...
...syntax :valid examples indicating valid and invalid form fields in this example, we use structures like this, which include extra <span>s to generate content on; we'll use these to provide indicators of valid/invalid data: <div> <label for="fname">first name *: </label> <input id="fname" name="fname" type="text" required> <span></span> </div> to provide these indicators, we use the following css: input + span { position: relative; } input + span::before { position: absolute; right: -20px; top: 5px; } input:invalid { border: 2px solid red; } input:invalid + span::before { content: '✖'; color: red; } input:valid + span::before { content: '✓'; color: green; } we set the <span>s to position: relative so that we can position the generated content relative to...
...e then absolutely position different generated content depending on whether the form's data is valid or invalid — a green check or a red cross, respectively. to add a bit of extra urgency to the invalid data, we've also given the inputs a thick red border when invalid. note: we've used ::before to add these labels, as we were already using ::after for the "required" labels. you can try it below: notice how the 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...
:visited - CSS: Cascading Style Sheets
Web › CSS › :visited
ink, :hover, or :active) that has at least equal specificity. to style links appropriately, put the :visited rule after the :link rule but before the :hover and :active rules, as defined by the lvha-order: :link — :visited — :hover — :active. styling restrictions for privacy reasons, browsers strictly limit which styles you can apply using this pseudo-class, and how they can be used: allowable css properties are color, background-color, border-color, border-bottom-color, border-left-color, border-right-color, border-top-color, column-rule-color, outline-color, text-decoration-color, and text-emphasis-color. allowable svg attributes are fill and stroke. the alpha component of the allowed styles will be ignored. the alpha component of the element's non-:visited state will be used i...
...ur browser probably has a default value for color and column-rule-color only. thus, if you want to modify the other properties, you'll need to give them a base value outside the :visited selector. html <a href="#test-visited-link">have you visited this link yet?</a><br> <a href="">you've already visited this link.</a> css a { /* specify non-transparent defaults to certain properties, allowing them to be styled with the :visited state */ background-color: white; border: 1px solid white; } a:visited { background-color: yellow; border-color: hotpink; color: hotpink; } result specifications specification status comment html living standardthe definition of ':visited' in that specification. living standard selectors level 4the ...
... chromium has never matched <link> elements with link pseudo-classes.safari ios full support 12samsung internet android full support 1.0notes full support 1.0notes notes chromium has never matched <link> elements with link pseudo-classes.restrict css properties allowed in a statement using :visited for privacychrome full support 6edge full support 12firefox full support 4ie full support 8opera full support 15safari full su...
:where() - CSS: Cascading Style Sheets
Web › CSS › :where
ny element that can be selected by one of the selectors in that list. the difference between :where() and :is() is that :where() always has 0 specificity, whereas :is() takes on the specificity of the most specific selector in its arguments. examples comparing :where() and :is() this example shows how :where() works, and also illustrates the difference between :where() and :is(). take the following html: <article> <h2>:is()-styled links</h2> <section class="is-styling"> <p>here is my main content. this <a href="https://mozilla.org">contains a link</a>. </section> <aside class="is-styling"> <p>here is my aside content. this <a href="https://developer.mozilla.org">also contains a link</a>. </aside> <footer class="is-styling"> <p>this is my footer, also containing...
...ling"> <p>this is my footer, also containing <a href="https://github.com/mdn">a link</a>. </footer> </article> in this somewhat-contrived example, we have two articles that each contain a section, an aside, and a footer. they differ by the classes used to mark the child elements. ...
...using a simple selector? 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-selec...
font-style - CSS: Cascading Style Sheets
for a particular font family, authors can download various font faces which correspond to the different styles of the same font family, and then use the font-style descriptor to explicitly specify the font face's style. the values for the css descriptor is same as that of its corresponding font property. syntax font-style: normal; font-style: italic; font-style: oblique; font-style: oblique 30deg; font-style: oblique 30deg 50deg; values normal selects the normal version of the font-family. italic specifies that font-face is an italicized version of the normal font. ...
...talic specifies that font-face is an italicized version of the normal font. oblique specifies that the font-face is an artificially sloped version of the normal font. oblique with angle selects a font classified as oblique, and additionally specifies an angle for the slant of the text. oblique with angle range selects a font classified as oblique, and additionally specifies a range of allowable angle for the slant of the text. note that a range is only supported when the font-style is oblique; for font-style: normal or italic, no second value is allowed. formal definition related at-rule@font-faceinitial valuenormalcomputed valueas specified formal syntax normal | italic | oblique <angle>{0,2} examples specifying an italic font style as an example, consider the garamond font...
...that a range is only supported when the font-style is oblique; for font-style: normal or italic, no second value is allowed. formal definition related at-rule@font-faceinitial valuenormalcomputed valueas specified formal syntax normal | italic | oblique <angle>{0,2} examples specifying an italic font style as an example, consider the garamond font family, in its normal form, we get the following result: @font-face { font-family: garamond; src: url('garamond.ttf'); } the italicized version of this text uses the same glyphs present in the unstyled version, but they are artificially sloped by a few degrees. on the other hand, if a true italicized version of the font family exists, we can include it in the src descriptor and specify the font style as italic, so that it is clear...
@font-face - CSS: Cascading Style Sheets
browsers) this also accepts two values to specify a range that is supported by a font-face, for example font-style: oblique 20deg 50deg; font-weight a font-weight 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-weight: 100 400; font-variant a font-variant value. font-feature-settings allows control over advanced typographic features in opentype fonts. font-variation-settings allows low-level control over opentype or truetype font variations, by specifying the four letter axis names of the features to vary, along with their variation values. src specifies the resource containing the font data. this can be a url to a remote font file location or the name of a font on the user's...
...", "truetype", "opentype", "embedded-opentype", and "svg". unicode-range the range of unicode code points to be used from the font. description if the local() function is provided, specifying a font name to look for on the user's computer, and the user agent finds a match, that local font is used. otherwise, the font resource specified using the url() function is downloaded and used. by allowing authors to provide their own fonts, @font-face makes it possible to design content without being limited to the so-called "web-safe" fonts (that is, the fonts which are so common that they're considered to be universally available). the ability to specify the name of a locally-installed font to look for and use makes it possible to customize the font beyond the basics while making it possible ...
... font/ttf opentype font/otf web open font format font/woff web open font format 2 font/woff2 notes web fonts are subject to the same domain restriction (font files must be on the same domain as the page using them), unless http access controls are used to relax this restriction. @font-face cannot be declared within a css selector. ...
Using CSS animations - CSS: Cascading Style Sheets
ss animation sequence, you style the element you want to animate with the animation property or its sub-properties. this lets you configure the timing, duration, and other details of how the animation sequence should progress. this does not configure the actual appearance of the animation, which is done using the @keyframes at-rule as described in defining the animation sequence using keyframes below. the sub-properties of the animation property are: animation-name specifies the name of the @keyframes at-rule describing the animation’s keyframes. animation-duration configures the length of time that an animation should take to complete one cycle. animation-timing-function configures the timing of the animation; that is, how the animation transitions through keyframes, by establishi...
...ck to see in your browser include the -webkit prefixed syntax. making text slide across the browser window this simple example styles the <p> element so that the text slides in from off the right edge of the browser window. note that animations like this can cause the page to become wider than the browser window. to avoid this problem put the element to be animated in a container, and set overflow:hidden on the container. p { animation-duration: 3s; animation-name: slidein; } @keyframes slidein { from { margin-left: 100%; width: 300%; } to { margin-left: 0%; width: 100%; } } in this example the style for the <p> element specifies that the animation should take 3 seconds to execute from start to finish, using the animation-duration property, and that the nam...
...o “slidein”; we do this to start the animation. why? because the animationstart event fires as soon as the animation starts, and in our case, that happens before our code runs. so we’ll start the animation ourselves by setting the class of the element to the style that gets animated after the fact. receiving the events the events get delivered to the listener() function, which is shown below. function listener(event) { var l = document.createelement("li"); switch(event.type) { case "animationstart": l.innerhtml = "started: elapsed time is " + event.elapsedtime; break; case "animationend": l.innerhtml = "ended: elapsed time is " + event.elapsedtime; break; case "animationiteration": l.innerhtml = "new loop started at time " + event.elapse...
Resizing background images with background-size - CSS: Cascading Style Sheets
length> values, the background-size css property offers two special size values, contain and cover. let's take a look at these. contain the contain value specifies that, regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container. ...
...de of the container. try resizing the example below to see this in action. html <div class="bgsizecontain"> <p>try resizing this element!</p> </div> css .bgsizecontain { background-image: url(https://www.mozilla.org/media/img/logos/firefox/logo-quantum.9c5e96634f92.png); background-size: contain; width: 160px; height: 160px; border: 2px solid; color: pink; resize: both; overflow: scroll; } result cover the cover value specifies that the background image should be sized so that it is as small as possible while ensuring that both dimensions are greater than or equal to the corresponding size of the container. try resizing the example below to see this in action. html <div class="bgsizecover"> <p>try resizing this element!</p> </div> css .bgsizecover { backgrou...
...ing size of the container. try resizing the example below to see this in action. ...
Handling content breaks in multicol - CSS: Cascading Style Sheets
us places we might want to control our breaks: breaks inside boxes, for example inside 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. ...
... breaks between lines the orphans and widows properties are also useful. ...
...rt of a fragment. the orphans and widows properties take an integer as a value, which represents the number of lines to keep together at the end and start of a fragment, respectively. note that these properties only work inside a block container, such as a paragraph. if the block has fewer lines in it than the number that you specify as a value, all lines will be kept together. in the example below, we are using the orphans property to control the number of lines left at the bottom of a column. you can change that value to see the effect on the breaking of the content. when things don’t work as expected if you have small amounts of content and are trying to control breaks in a number of ways or on several elements, your content needs to break somewhere, so you may not always get the r...
Using multi-column layouts - CSS: Cascading Style Sheets
the css multi-column layout module extends the block layout mode to allow the easy definition of multiple columns of text. people have trouble reading text if lines are too long; if it takes too long for the eyes to move from the end of the one line to the beginning of the next, they lose track of which line they were on. therefore, to make maximum use of a large screen, authors should have limited-width columns of text placed side by side, just as newspapers do. unfortunately this is impossible to do with css and html without forcing column breaks at fixed positions, or severely restricting the markup allowed in the text, or using heroic scripting. this limitation is solved by adding new css properties to extend the traditional block layout mode. using columns column count and width two...
...nsequat. 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 </div> css #wid { column-width: 100px; } result the exact details are described in the css3 specification. in a multi-column block, content is automatically flowed from one column into the next as needed. all html, css and dom functionality is supported within columns, as are editing and printing. the columns shorthand most of the time, a web designer will use one of the two css properties: column-count or column-width. as values for these properties do not overlap, it is often convenient to use the shorthand columns. e.g. the css declaration column-wi...
...mn heights must be balanced: that is, the browser automatically sets the maximum column height so that the heights of the content in each column are approximately equal. firefox does this. however, in some situations it is also useful to set the maximum height of the columns explicitly, and then lay out content starting at the first column and creating as many columns as necessary, possibly overflowing to the right. therefore, if the height is constrained, by setting the css height or max-height properties on a multi-column block, each column is allowed to grow to that height and no further before adding new column. this mode is also much more efficient for layout. column gaps there is a gap between columns. the recommended default is 1em. this size can be changed by applying the column-ga...
CSS Multi-column Layout - CSS: Cascading Style Sheets
as the value of column-count is 3, the content is arranged into 3 columns of equal size. ...
...as the value of column-count is 3, the content is arranged into 3 columns of equal size. ...
...d css fragmentation properties break-after break-before break-inside orphans widows guides basic concepts of multicol an overview of the multiple-column layout specification styling columns how to use column rules and manage the spacing between columns. spanning and balancing how to make elements span across all columns and controlling the way columns are filled. handling overflow in multicol what happens when an item overflows the column it is in and what happens when there is too much columned content to fit a container. content breaks in multicol introduction to the fragmentation specification and how to control where column content breaks. specifications specification status comment css multi-column layout module working draft in...
CSS Fonts - CSS: Cascading Style Sheets
Web › CSS › CSS Fonts
css fonts is a module of css that defines font-related properties and how font resources are loaded. it lets you define the style of a font, such as its family, size and weight, line height, and the glyph variants to use when multiple are available for a single character. basic example the following example shows a simple use of basic font properties to style a paragraph of text. ...
...of text. p { width: 600px; margin: 0 auto; font-family: "helvetica neue", "arial", sans-serif; font-style: italic; font-weight: 100; font-variant-ligatures: normal; font-size: 2rem; letter-spacing: 1px; } <p>three hundred years ago<br> i thought i might get some sleep<br> i stretched myself out onna antique bed<br> an' my spirit did a midnite creep</p> the result is as follows: variable fonts examples you can find a number of variable fonts examples at v-fonts.com and axis-praxis.org; see also our variable fonts guide for more information and usage information. reference properties font font-family font-feature-settings font-kerning font-language-override font-optical-sizing font-size font-size-adjust font-stretch font-style font-synthesis font-va...
...hs or character styles contained within an opentype font. these include things like ligatures (special glyphs that combine characters like 'fi' or 'ffl'), kerning (adjustments to the spacing between specific letterform pairings), fractions, numeral styles, and a number of others. these are all referred to as opentype features, and are made available to use on the web via specific properties and a low-level control property — font-feature-settings. this article provides you with all you need to know about using opentype font features in css. variable fonts guide variable fonts are an evolution of the opentype font specification that enables many different variations of a typeface to be incorporated into a single file, rather than having a separate font file for every width, weight, or styl...
Layout using named grid lines - CSS: Cascading Style Sheets
col-start 5</div> <div class="item2">i am placed from col-start line 7 spanning 3 lines</div> </div> if you take a look at this layout in the firefox grid highlighter you can see how the column lines are shown, and how our items are placed against these lines. the repeat syntax can also take a track list, it doesn’t just need to be a single track size that is being repeated. the code below would create an eight track grid, with a narrower 1fr width column named col1-start followed by a wider 3fr column named col2-start. .wrapper { grid-template-columns: repeat(4, [col1-start] 1fr [col2-start] 3fr); } if your repeating syntax puts two lines next to each other then they will be merged, and create the same result as giving a line multiple names in a non-repeating track definition...
... .wrapper { grid-template-columns: repeat(4, [col-start] 1fr [col-end] ); } if we write this definition out without using repeat notation it would look like this. ...
...ode to do all of the calculations to make sure that the columns add up to 100%. with grid layout the only code we need for our grid “framework” is: .wrapper { display: grid; grid-gap: 10px; grid-template-columns: repeat(12, [col-start] 1fr); } we can then use that framework to layout our page. for example, to create a three column layout with a header and footer, i might have the following markup. * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > * { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } <div class="wrapper"> <header class="main-header">i am the header</header> <aside class="side1">i am sidebar 1</aside> <art...
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
grid-column: col-start / span 12; } at the next breakpoint we want to move to a two-column layout. our header and navigation still span the full grid, so we do not need to 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; } na...
...o tracks, and then they won’t be so tall. i have a class of wide on my larger item, and i add a rule grid-column-end with a value of span 2. now when grid encounters this item, it will assign it two tracks. at some breakpoints, this means that we'll get a gap in the grid – where there isn’t space to lay out a two-track item. i can cause a grid to backfill those gaps by setting grid-auto-flow: dense on the grid container. take care when doing this however as it does take items away from their logical source order. you should only do this if your items do not have a set order – and be aware of the issues of the tab order following the source and not your reordered display. <ul class="listing"> <li> <h2>item one</h2> <div class="body"><p>the content of this listing item ...
...; margin: 0; padding: 20px; } .listing li { border: 1px solid #ffe066; border-radius: 5px; display: flex; flex-direction: column; } .listing .cta { margin-top: auto; border-top: 1px solid #ffe066; padding: 10px; text-align: center; } .listing .body { padding: 10px; } .listing { list-style: none; margin: 2em; display: grid; grid-gap: 20px; grid-auto-flow: dense; grid-template-columns: repeat(auto-fill,minmax(200px, 1fr)); } .listing .wide { grid-column-end: span 2; } this technique of using auto-placement with some rules applied to certain items is very useful, and can help you to deal with content that is being output by a cms for example, where you have repeated items and can perhaps add a class to certain ones as they are rendered into...
CSS Logical Properties and Values - CSS: Cascading Style Sheets
logical, rather than physical, direction and dimension mappings. the module also defines logical properties and values for properties previously defined in css 2.1. logical properties define direction‐relative equivalents of their corresponding physical properties. block vs. inline logical properties and values use the abstract terms block and inline to describe the direction in which they flow. ...
...roperties previously defined in css 2.1. logical properties define direction‐relative equivalents of their corresponding physical properties. block vs. inline logical properties and values use the abstract terms block and inline to describe the direction in which they flow. the physical meaning of these terms depends on the writing mode. block dimension the dimension perpendicular to the flow of text within a line, i.e., the vertical dimension in horizontal writing modes, and the horizontal dimension in vertical writing modes. for 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 e...
...g-block-start padding-inline padding-inline-end padding-inline-start properties for floating and positioning clear (inline-end and inline-start keywords) float (inline-end and inline-start keywords) inset inset-block inset-block-end inset-block-start inset-inline inset-inline-end inset-inline-start other properties caption-side (inline-end and inline-start keywords) overflow-block overflow-inline overscroll-behavior-block overscroll-behavior-inline resize (block and inline keywords) text-align (end and start keywords) deprecated properties offset-block-end (now inset-block-end ) offset-block-start (now inset-block-start ) offset-inline-end (now inset-inline-end ) offset-inline-start (now inset-inline-start ) guides basic conce...
Shapes From Images - CSS: Cascading Style Sheets
rs. setting a threshold the shape-image-threshold property enables the creation of shapes from areas which are not fully transparent. if the value of shape-image-threshold is 0.0 (which is the initial value) then the area must be fully transparent. if the value is 1.0 then it is fully opaque. values in between mean that you can set a semi-transparent area as the defining area. in the example below i am using a similar image to the initial example, however in this image the background of the star is not fully transparent, it has a 20% opacity as created in my graphics programme. if i set shape-image-threshold to 0.3 then i see the shape, if i set it to something smaller than 0.2 i do not get the shape. using images with generated content in the above example i have both used the image a...
...parent, it has a 20% opacity as created in my graphics programme. if i set shape-image-threshold to 0.3 then i see the shape, if i set it to something smaller than 0.2 i do not get the shape. using images with generated content in the above example i have both used the image as the value of shape-outside and also added it to the page. many demos do this as it helps to show the shape we are following, however the shape-outside property is not related to the image that is displayed on the page and so you do not need to display an image to use an image to create a shape. you do need something to float, but that could be some generated content as in the below example. i am floating generated content and using a larger star image to shape my content without displaying any image on the page. ...
...next example i have used generated content and floated this content, giving it a background image of a linear gradient. i am using that same value as the value of shape-outside. the linear gradient goes from purple to transparent, so by changing the value of shape-image-threshold i can decide how transparent the pixels need to be that create my shape. you can play with that value in the example below to see how the diagonal line will move across the shape depending on that value. you could also try removing the background image completely, thus using the gradient purely to create the shape and not displaying it on the page at all. in this next example i am using a radial gradient with an ellipse, once again using a transparent part of the gradient to create the shape. you can experimen...
Using Media Queries for Accessibility - CSS: Cascading Style Sheets
reduced motion blinking and flashing animation can be problematic for people with cognitive concerns such as attention deficit hyperactivity disorder (adhd). additionally, certain kinds of motion can be a trigger for vestibular 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 ...
...0.3s linear infinite both; animation: vibrate 0.3s linear infinite both; } @media (prefers-reduced-motion: reduce) { .animation { animation: none; } } high contrast mode the -ms-high-contrast css media feature is a microsoft extension that describes whether the application is being displayed in high contrast mode, and with what color variation. this will help not only users with low vision and contrast sensitivity issues but also users that are working on a computer or phone with direct sunlight. syntax the -ms-high-contrast media feature is specified as one of the following values. values 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 th...
...igh contrast mode with any color variation. black-on-white indicates that the subsequent styling rules will be applied when the system is placed in high contrast mode with a black-on-white color variation. white-on-black indicates that the subsequent styling rules will be applied when the system is placed in high contrast mode with a white-on-black color variation. example the following declarations will match applications that are being displayed in high contrast mode with any color variation, a black-on-white color variation, and a white-on-black color variation, respectively. @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'); } } @m...
Mozilla CSS extensions - CSS: Cascading Style Sheets
oz-box-align -moz-box-direction -moz-box-flex -moz-box-ordinal-group -moz-box-orient -moz-box-pack c–i -moz-context-properties -moz-float-edge -moz-force-broken-image-icon -moz-image-region o -moz-orient -moz-osx-font-smoothing -moz-outline-radius -moz-outline-radius-bottomleft -moz-outline-radius-bottomright -moz-outline-radius-topleft -moz-outline-radius-topright overflow-clip-box overflow-clip-box-block overflow-clip-box-inline s–z -moz-stack-sizing :-moz-system-metric(images-in-menus) :-moz-system-metric(mac-graphite-theme) :-moz-system-metric(scrollbar-end-backward) :-moz-system-metric(scrollbar-end-forward) :-moz-system-metric(scrollbar-start-backward) :-moz-system-metric(scrollbar-start-forward) :-moz-system-metric(scrollbar-thumb-...
...bar-thumb-proportional) :-moz-system-metric(touch-enabled) :-moz-system-metric(windows-default-theme) -moz-user-focus -moz-user-input -moz-user-modify -moz-window-dragging -moz-window-shadow formerly proprietary properties that are now standard note: to maximize the compatibility of your css, you should use the unprefixed standard properties instead of the prefixed ones listed below. once a given property is standardized and implemented without the prefix, the prefixed version is typically dropped after a while. a -moz-animation [prefixed version still accepted] -moz-animation-delay [prefixed version still accepted] -moz-animation-direction [prefixed version still accepted] -moz-animation-duration [prefixed version still accepted] -moz-animation-fill-m...
...ame-ti-et -moz-ethiopic-numeric -moz-gujarati -moz-gurmukhi -moz-hangul -moz-hangul-consonant -moz-japanese-formal -moz-japanese-informal -moz-kannada -moz-khmer -moz-lao -moz-malayalam -moz-myanmar -moz-oriya -moz-persian -moz-simp-chinese-formal -moz-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-cla...
Privacy and the :visited selector - CSS: Cascading Style Sheets
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. ...
...le) will be styled as if the link were unvisited. in rare scenarios, if you're using nested link elements and the element being matched is different from the link whose presence in history is being tested, the element will be rendered as if the link were unvisited, as well. limits to visited link styles you can style visited links, but there are limits to which styles you can use. ...
...d restrictions: :link { outline: 1px dotted blue; background-color: white; /* the default value of background-color is `transparent`. you need to specify a different value, otherwise changes on :visited won't apply. */ } :visited { outline-color: orange; /* visited links have an orange outline */ background-color: green; /* visited links have a green background */ color: yellow; /* visited links have yellow colored text */ } impact on web developers overall, these restrictions shouldn't affect web developers too significantly. they may, however, require the following changes to existing sites: using background images to style links based on whether they've been visited will no longer work, since only colors can be used to style visited links. colors th...
border-block-end - CSS: Cascading Style Sheets
y for setting the individual logical block-end border property values in a single place in the style sheet. 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. constituent properties this property is a shorthand for the following css properties: border-block-end-color border-block-end-style border-block-end-width syntax border-block-end: 1px; border-block-end: 2px dotted; border-block-end: medium dashed blue; border-block-end can be used to set the values for one or more of border-block-end-width, border-block-end-style, and border-block-end-color. the physical border to which it maps depends on the elemen...
...y, and text orientation. it corresponds to the border-top, border-right, border-bottom, or border-left property depending on the values defined for writing-mode, direction, and text-orientation. related properties are border-block-start, border-inline-start, and border-inline-end, which define the other borders of the element. values the border-block-end is specified with one or more of the following, in any order: <'border-width'> the width of the border. see border-width. <'border-style'> the line style of the border. see border-style. <'color'> the color of the border. see color. formal definition initial valueas each of the properties of the shorthand:border-top-width: mediumborder-top-style: noneborder-top-color: currentcolorapplies toall elementsinheritednocomputed valueas...
... editor's draft initial definition ...
border-block-start - CSS: Cascading Style Sheets
for setting the individual logical block-start border property values in a single place in the style sheet. 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. constituent properties this property is a shorthand for the following css properties: border-block-start-color border-block-start-style border-block-start-width syntax border-block-start: 1px; border-block-start: 2px dotted; border-block-start: medium dashed blue; border-block-start can be used to set the values for one or more of border-block-start-width, border-block-start-style, and border-block-start-color. the physical border to which it maps d...
...y, and text orientation. it corresponds to the border-top, border-right, border-bottom, or border-left property depending on the values defined for writing-mode, direction, and text-orientation. related properties are border-block-end, border-inline-start, and border-inline-end, which define the other borders of the element. values the border-block-start is specified with one or more of the following, in any order: <'border-width'> the width of the border. see border-width. <'border-style'> the line style of the border. see border-style. <'color'> the color of the border. see color. formal definition initial valueas each of the properties of the shorthand:border-width: as each of the properties of the shorthand:border-top-width: mediumborder-right-width: mediumborder-bottom-widt...
... editor's draft initial definition ...
border-inline-end - CSS: Cascading Style Sheets
for setting the individual logical inline-end border property values in a single place in the style sheet. 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. constituent properties this property is a shorthand for the following css properties: border-inline-end-color border-inline-end-style border-inline-end-width syntax border-inline-end: 1px; border-inline-end: 2px dashed; border-inline-end: medium dashed blue; the physical border to which border-inline-end maps depends on the element's writing mode, directionality, and text orientation. it corresponds to the border-top, border-right, border-bottom, or bo...
...see border-width. <'border-style'> the line style of the border. see border-style. <'color'> the color of the border. see color. formal definition initial valueas each of the properties of the shorthand:border-width: as each of the properties of the shorthand:border-top-width: mediumborder-right-width: mediumborder-bottom-widt...
... editor's draft initial definition ...
border-inline-start - CSS: Cascading Style Sheets
or setting the individual logical inline-start border property values in a single place in the style sheet. 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. constituent properties this property is a shorthand for the following css properties: border-inline-start-color border-inline-start-style border-inline-start-width syntax border-inline-start: 1px; border-inline-start: 2px dotted; border-inline-start: medium dashed green; the physical border to which border-inline-start maps depends on the element's writing mode, directionality, and text orientation. it corresponds to the border-top, border-right, borde...
...y, and text orientation. it corresponds to the border-top, border-right, border-bottom, or border-left property depending on the values defined for writing-mode, direction, and text-orientation. related properties are border-block-start, border-block-end, and border-inline-end, which define the other borders of the element. values the border-inline-start is specified with one or more of the following, in any order: <'border-width'> the width of the border. see border-width. <'border-style'> the line style of the border. see border-style. <'color'> the color of the border. see color. formal definition initial valueas each of the properties of the shorthand:border-width: as each of the properties of the shorthand:border-top-width: mediumborder-right-width: mediumborder-bottom-widt...
... editor's draft initial definition ...
border-inline - CSS: Cascading Style Sheets
see border-width. <'border-style'> the line style of the border. see border-style. <'color'> the color of the border. see color. formal definition initial valueas e...
...see border-width. <'border-style'> the line style of the border. see border-style. ...
... editor's draft initial definition ...
border-style - CSS: Cascading Style Sheets
the border-style shorthand css property sets the line style for all four sides of an element's border. 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. ...
...n two values are specified, the first style applies to the top and bottom, the second to the left and right. when three values are specified, the first style applies to the top, the second to the left and right, the third to the bottom. when four values are specified, the styles apply to the top, right, bottom, and left in that order (clockwise). each value is a keyword chosen from the list below. ...
...d to the left and right. when three values are specified, the first style applies to the top, the second to the left and right, the third to the bottom. when four values are specified, the styles apply to the top, right, bottom, and left in that order (clockwise). each value is a keyword chosen from the list below. values <line-style> describes the style of the border. it can have the following values: none like the hidden keyword, displays no border. unless a background-image is set, the computed value of the same side's border-width will be 0, even if the specified value is something else. in the case of table cell and border collapsing, the none value has the lowest priority: if any other conflicting border is set, it will be displayed. ...
border-width - CSS: Cascading Style Sheets
the border-width shorthand css property sets the width of an element's border. 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. ...
...hen three values are specified, the first width applies to the top, the second to the left and right, the third to the bottom. when four values are specified, the widths apply to the top, right, bottom, and left in that order (clockwise). values <line-width> defines the width of the border, either as an explicit nonnegative <length> or a keyword. ...
... formal definition initial valueas each of the properties of the shorthand:border-top-width: mediumborder-right-width: mediumborder-bottom-width: mediumborder-left-width: mediumapplies toall elements. ...
border - CSS: Cascading Style Sheets
Web › CSS › border
css property sets an element's border. it sets the values of border-width, border-style, and border-color. 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. ...
...wing css properties: border-color border-style border-width syntax /* style */ border: solid; /* width | style */ border: 2px dotted; /* style | color */ border: outset #f33; /* width | style | color */ border: medium dashed green; /* global values */ border: inherit; border: initial; border: unset; the border property may be specified using one, two, or three of the values listed below. the order of the values does not matter. note: the border will be invisible if its style is not defined. this is because the style defaults to none. values <line-width> sets the thickness of the border. defaults to medium if absent. see border-width. <line-style> sets the style of the border. defaults to none if absent. see border-style. <color> sets the color of the border. defaults...
...other, however, you can use the longhand border-width, border-style, and border-color properties, which accept different values for each side. alternatively, you can target one border at a time with the physical (e.g., border-top ) and logical (e.g., border-block-start) border properties. borders vs. outlines borders and outlines are very similar. however, outlines differ from borders in the following ways: outlines never take up space, as they are drawn outside of an element's content. according to the spec, outlines don't have to be rectangular, although they usually are. formal definition initial valueas each of the properties of the shorthand:border-width: as each of the properties of the shorthand:border-top-width: mediumborder-right-width: mediumborder-bottom-width: mediumborde...
box-sizing - CSS: Cascading Style Sheets
amples and send us a pull request. by default in the css box model, the width and height you assign to an element is applied only to the element's content box. if the element has any border or padding, this is then added to the width and height to arrive at the size of the box that's rendered on the screen. this means that when you set width and height, you have to adjust the value you give to allow for any border or padding that may be added. for example, if you have four boxes with width: 25%;, if any has left or right padding or a left or right border, they will not by default fit on one line within the constraints of the parent container. the box-sizing property can be used to adjust this behavior: content-box gives you the default css box-sizing behavior. if you set an element's wid...
...dth. 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 from the list of values below. values content-box this is the initial and default value as specified by the css standard. the width and height properties include the content, but ...
...l syntax content-box | border-box examples box sizes with content-box and border-box this example shows how different box-sizing values alter the rendered size of two otherwise identical elements. ...
clear - CSS: Cascading Style Sheets
Web › CSS › clear
the clear css property sets whether an element must be moved below (cleared) floating elements that precede it. the clear property applies to floating and non-floating elements. 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. when applied to non-floating blocks, it moves the border edge of the element down until it is below the margin edge of all relevant floats. the non-floated block's top margin collapses. vertical margins between two floated elements on the other hand will not collapse. ...
...this affects the position of later floats, since later floats cannot be positioned higher than earlier ones. the floats that are relevant to be cleared are the earlier floats within the same block formatting context. ...
... 1chrome android full support 18firefox android full support 4opera android full support 10.1safari ios full support 1samsung internet android full support 1.0flow-relative values inline-start and inline-endchrome no support noedge no support nofirefox full support 55ie no support noopera no support nosafari no support ...
color-adjust - CSS: Cascading Style Sheets
the color-adjust css property sets what, if anything, the user agent may do to optimize the appearance of the element on the output device. by default, the browser is allowed to make any adjustments to the element's appearance it determines to be necessary and prudent given the type and capabilities of the output device. syntax color-adjust: economy; color-adjust: exact; the color-adjust property's value must be one of the following keywords. values economy the user agent is allowed to make adjustments to the element as it deems appropriate and prudent in order to optimize the output for the device it's being rendered for. for example, when printing, a browser might opt to leave out all background images and to adjust text colors to be sure the contrast is optimized for reading on wh...
...ses text and background colors that will be too similar on the output device for legibility purposes. if the output device is a printer, and to save ink, dark or extremely dense background images might be removed. when printing a page, the browser might want to replace light-colored text on a dark background with dark text on a white background. any options the user agent offers the user to allow them to control the use of color and images will take priority over the value of color-adjust. in other words, there isn't any guarantee that color-adjust will do anything. not only can the user override the behavior, but each user agent is allowed to decide for itself how to handle color-adjust in any given situation. formal definition initial valueeconomyapplies toall elementsinheritedyescom...
...ther words, there isn't any guarantee that color-adjust will do anything. not only can the user override the behavior, but each user agent is allowed to decide for itself how to handle color-adjust in any given situation. formal definition initial valueeconomyapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax economy | exact examples preserving low contrast in this example, a box is shown which uses a background-image and a translucent linear-gradient() function atop a black background color to have a dark blue gradient behind medium red text. for whatever reason, this is the desired appearance in any rendering environment, including on paper, so we also use color-adjust: exact to tell the browser not to make color or style adjustments to ...
color - CSS: Cascading Style Sheets
Web › CSS › color
<color> value. note that the value must be a uniform color. it can't be a <gradient>, which is actually 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. ...
...a( <number>#{3} , <alpha-value>? )<hsl()> = hsl( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsl( <hue>, <percentage>, <percentage>, <alpha-value>? )<hsla()> = hsla( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsla( <hue>, <percentage>, <percentage>, <alpha-value>? ...
... { color: hsl(0, 100%, 50%); } /* 50% translucent */ p { color: #ff000080; } p { color: rgba(255, 0, 0, 0.5); } p { color: hsla(0, 100%, 50%, 0.5); } specifications specification status comment css color module level 4the definition of 'color' in that specification. working draft adds commaless syntaxes for the rgb(), rgba(), hsl(), and hsla() functions. allows alpha values in rgb() and hsl(), turning rgba() and hsla() into (deprecated) aliases for them. adds color keyword rebeccapurple. adds 4- and 8-digit hex color values, where the last digit(s) represents the alpha value. adds hwb(), device-cmyk(), and color() functions. css color module level 3the definition of 'color' in that specification. recommendation deprecates sys...
column-span - CSS: Cascading Style Sheets
rty makes it possible for an element to span across all columns when its value is set to all. /* keyword values */ column-span: none; column-span: all; /* global values */ column-span: inherit; column-span: initial; column-span: unset; an element that spans more than one column is called a spanning element. syntax the column-span property is specified as one of the keyword values listed below. ...
...ne; column-span: all; /* global values */ column-span: inherit; column-span: initial; column-span: unset; an element that spans more than one column is called a spanning element. syntax the column-span property is specified as one of the keyword values listed below. values none the element does not span multiple columns. all the element spans across all columns. content in the normal flow that appears before the element is automatically balanced across all columns before the element appears. ...
... html <article> <h2>header spanning all of the columns</h2> <p> the h2 should span all the columns. ...
columns - CSS: Cascading Style Sheets
Web › CSS › columns
rty sets the number of columns to use when drawing an element's contents, as well as those columns' widths. 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 for the following css properties: column-count column-width syntax /* column width */ columns: 18em; /* column count */ columns: auto; columns: 2; /* both column width and count */ columns: 2 auto; columns: auto 12em; columns: auto auto; /* global values */ columns: inherit; columns: initial; columns: unset; the columns property may be specified as one or two of the values listed below, in any order. values <'column-width'> the ideal column width, defined as a <length> or the keyword auto. the actual width may be wider or narrower to fit the available space. see column-width. <'column-count'> the ideal number of columns into which the element's content should be flowed, defined as an <integer> or the keyword auto. if neither this value nor the column's width are auto, it...
...see column-count. ...
env() - CSS: Cascading Style Sheets
Web › CSS › env
a-inset-bottom, 20px) env(safe-area-inset-left, 20px); } in addition, unlike custom properties, which cannot be used outside of declarations, the env() function can be used in place of any part of a property value, or any part of a descriptor (e.g. in media query rules). as the spec evolves, it may also be usable in other places such as selectors. originally provided by the ios browser to allow developers to place their content in a safe area of the viewport, the safe-area-inset-* values defined in the specification can be used to help ensure content is visible even to viewers using non‑rectangular displays. syntax /* using the four safe area inset values with no fallback values */ env(safe-area-inset-top); env(safe-area-inset-right); env(safe-area-inset-bottom); env(safe-area-inset...
... your average laptop monitor, their value is equal to zero. for non-rectangular displays — like a round watch face — the four values set by the user agent form a rectangle such that all content inside the rectangle is visible. note: unlike other css properties, user agent-defined property names are case-sensitive. formal syntax env( <custom-ident> , <declaration-value>? ) examples the below example makes use of the optional second parameter of env(), which allows you to provide a fallback value in case the environment variable is not available. <p> if the <code>env()</code> function is supported in your browser, this paragraph’s text will have 50px of padding between it and the left border — but not the top, right and bottom. this is because the accompanying css is the ...
...but, if the property value doesn't support commas, the value is not valid. note: user agent properties are not reset by the all property. specifications specification status comment css environment variables module level 1the definition of 'env()' in that specification. editor's draft initial definition. ...
drop-shadow() - CSS: Cascading Style Sheets
mage. its result is a <filter-function>. 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 drop shadow is effectively a blurred, offset version of the input image's alpha mask, drawn in a specific color and composited below the image. note: this function is somewhat similar to the box-shadow property. the box-shadow property creates a rectangular shadow behind an element's entire box, while the drop-shadow() filter function 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 ty...
...lar shadow behind an element's entire box, while the drop-shadow() filter function 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 (...
...es 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, the larger and more blurred the shadow becomes. if unspecified, it defaults to 0, resulting in a sharp, unblurred edge. negative values are not allowed. color (optional) the color of the shadow, specified as a <color>. if unspecified, the value of the color property is used. examples setting a drop shadow using pixel offsets and blur radius /* black shadow with 10px blur */ drop-shadow(16px 16px 10px black) setting a drop shadow using rem offsets and blur radius /* reddish shadow with 1rem blur */ drop-shadow(.5rem .5rem 1rem #e23) s...
flex-direction - CSS: Cascading Style Sheets
ht. syntax /* the direction text is laid out in a line */ flex-direction: row; /* like <row>, but reversed */ flex-direction: row-reverse; /* the direction in which lines of text are stacked */ flex-direction: column; /* like <column>, but reversed */ flex-direction: column-reverse; /* global values */ flex-direction: inherit; flex-direction: initial; flex-direction: unset; values the following values are accepted: row the flex container's main-axis is defined to be the same as the text direction. the main-start and main-end points are the same as the content direction. row-reverse behaves the same as row but the main-start and main-end points are permuted. column the flex container's main-axis is the same as the block-axis. the main-start and main-end points are the same as ...
...end points are the same as the before and after points of the writing-mode. column-reverse behaves the same as column but the main-start and main-end are permuted. accessibility concerns using the flex-direction property with values of row-reverse or column-reverse will create a disconnect between the visual presentation of content and dom order. this will adversely affect users experiencing low vision navigating with the aid of assistive technology such as a screen reader. if the visual (css) order is important, then screen reader users will not have access to the correct reading order. flexbox & the keyboard navigation disconnect — tink source order matters | adrian roselli mdn understanding wcag, guideline 1.3 explanations understanding success criterion 1.3.2 | w3c understand...
...sinheritednocomputed valueas specifiedanimation typediscrete formal syntax row | row-reverse | column | column-reverse examples reversing flex container columns and rows html <h4>this is a column-reverse</h4> <div id="content"> <div class="box" style="background-color:red;">a</div> <div class="box" style="background-color:lightblue;">b</div> <div class="box" style="background-color:yellow;">c</div> </div> <h4>this is a row-reverse</h4> <div id="content1"> <div class="box1" style="background-color:red;">a</div> <div class="box1" style="background-color:lightblue;">b</div> <div class="box1" style="background-color:yellow;">c</div> </div> css #content { width: 200px; height: 200px; border: 1px solid #c3c3c3; display: flex; flex-direction: column-reverse; } .box { ...
flex-grow - CSS: Cascading Style Sheets
Web › CSS › flex-grow
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 values are set. formal definition initial value0applies toflex items, including in-flow pseudo-elementsinheritednocomputed valueas specifiedanimation typea number formal syntax <number> examples setting flex item grow factor html <h4>this is a flex-grow</h4> <h5>a,b,c and f are flex-grow:1 . d and e are flex-grow:2 .</h5> <div id="content"> <div class="box" style="background-color:red;">a</div> <div class="box" style="background-color:lightblue;">b</div> <div class="box...
...mputed valueas specifiedanimation typea number formal syntax <number> examples setting flex item grow factor html <h4>this is a flex-grow</h4> <h5>a,b,c and f are flex-grow:1 . ...
... candidate recommendation initial definition ...
flex-wrap - CSS: Cascading Style Sheets
Web › CSS › flex-wrap
the flex-wrap css property sets whether flex items are forced onto one line or can wrap onto multiple lines. if wrapping is allowed, it sets the direction that lines are stacked. 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. see using css flexible boxes for more properties and information. ...
... https://github.com/mdn/interactive-examples and send us a pull request. see using css flexible boxes for more properties and information. syntax flex-wrap: nowrap; /* default value */ flex-wrap: wrap; flex-wrap: wrap-reverse; /* global values */ flex-wrap: inherit; flex-wrap: initial; flex-wrap: unset; the flex-wrap property is specified as a single keyword chosen from the list of values below. values the following values are accepted: nowrap the flex items are laid out in a single line which may cause the flex container to overflow. the cross-start is either equivalent to start or before depending on the flex-direction value. this is the default value. wrap the flex items break into multiple lines. the cross-start is either equivalent to start or before depending flex-directio...
..."> <div class="red">1</div> <div class="green">2</div> <div class="blue">3</div> </div> css /* common styles */ .content, .content1, .content2 { color: #fff; font: 100 24px/100px sans-serif; height: 150px; text-align: center; } .content div, .content1 div, .content2 div { height: 50%; width: 300px; } .red { background: orangered; } .green { background: yellowgreen; } .blue { background: steelblue; } /* flexbox styles */ .content { display: flex; flex-wrap: wrap; } .content1 { display: flex; flex-wrap: nowrap; } .content2 { display: flex; flex-wrap: wrap-reverse; } results specifications specification status comment css flexible box layout modulethe definition of 'flex-wrap' in that speci...
font-size - CSS: Cascading Style Sheets
Web › CSS › font-size
larger, smaller relative-size keywords. the font will be larger or smaller relative to the...
...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. 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>...
...ch 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 “outer inner outer” are all displ...
font-stretch - CSS: Cascading Style Sheets
semi-condensed, condensed, extra-condensed, ultra-condensed specifies a more condensed font face than normal, with ultra-condensed as the most condensed. semi-expanded, expanded, extra-expanded, ultra-expanded specifies a more expanded font face than normal, with ultra-expanded as the most expanded. <percentage> a <percentage> value between 50% and 200% (inclusive). negative values are not allowed for this property. in earlier versions of the font-stretch specification, the property accepts only the nine keyword values. css fonts level 4 extends the syntax to accept a <percentage> value as well. this enables variable fonts to offer something more like a continuum of character widths. for truetype or opentype variable fonts, the "wdth" variation is used to implement varying widths. how...
...accept a <percentage> value as well. this enables variable fonts to offer something more like a continuum of character widths. for truetype or opentype variable fonts, the "wdth" variation is used to implement varying widths. however, note that the <percentage> syntax is not yet supported by all browsers: check the browser compatibility table for details. ...
... not offer condensed or expanded faces, this property has no effect. font face selection the face selected for a given value of font-stretch depends on the faces supported by the font in question. if the font does not provide a face that exactly matches the given value, then values less than 100% map to a narrower face, and values greater than or equal to 100% map to a wider face. ...
font-variant-caps - CSS: Cascading Style Sheets
s: normal; font-variant-caps: small-caps; font-variant-caps: all-small-caps; font-variant-caps: petite-caps; font-variant-caps: all-petite-caps; font-variant-caps: unicase; font-variant-caps: titling-caps; /* global values */ font-variant-caps: inherit; font-variant-caps: initial; font-variant-caps: unset; the font-variant-caps property is specified using a single keyword value from the list below. in each case, if the font doesn't support the opentype value, then it synthesizes the glyphs. values normal deactivates of the use of alternate glyphs. small-caps enables display of small capitals (opentype feature: smcp). small-caps glyphs typically use the form of uppercase letters but are reduced to the size of lowercase letters. all-small-caps enables display of small capitals for b...
..., if the font doesn't support the opentype value, then it synthesizes the glyphs. values normal deactivates of the use of alternate glyphs. small-caps enables display of small capitals (opentype feature: smcp). small-caps glyphs typically use the form of uppercase letters but are reduced to the size of lowercase letters. all-small-caps enables display of small capitals for both upper and lowercase letters (opentype features: c2sc, smcp). petite-caps enables display of petite capitals (opentype feature: pcap). all-petite-caps enables display of petite capitals for both upper and lowercase letters (opentype features: c2pc, pcap). unicase enables display of mixture of small capitals for uppercase letters with normal lowercase letters (opentype feature: unic). titling-caps enable...
...when used in all uppercase titling sequences they can appear too strong. titling capitals are designed specifically for this situation. ...
<frequency-percentage> - CSS: Cascading Style Sheets
value that can be either a <frequency> or a <percentage>. frequency values, e.g. the pitch of a speaking voice, are not currently used in any css properties. syntax the value of a <frequency-percentage> is either a <frequency> or a <percentage>; see their individual reference pages for details about their syntaxes. ...
...) where a <frequency-percentage> is specified as an allowable type, this means that the percentage resolves to a frequency and therefore can be used in a calc() expression. examples valid percentage values 90% positive percentage +90% positive percentage with leading + -90% negative percentage — not valid for all properties that use percentages invalid percentage values 90 % no space is allowed between the number and the unit valid frequency values 12hz positive integer 4.3hz non-integer 14khz the unit is case-insensitive, though non-si capitalization is not recommended. +0hz zero, with a leading + and a unit -0khz zero, with a leading - and a unit invalid frequency values 12.0 this is a <number>, not an <frequency>, because it is missing a unit. 7 hz no s...
... the number and the unit valid frequency values 12hz positive integer 4.3hz non-integer 14khz the unit is case-insensitive, though non-si capitalization is not recommended. +0hz zero, with a leading + and a unit -0khz zero, with a leading - and a unit invalid frequency values 12.0 this is a <number>, not an <frequency>, because it is missing a unit. 7 hz no space is allowed between the number and the unit. 0 although unitless zero is an allowable <length>, it's an invalid <frequency>. specifications specification status comment css values and units module level 4the definition of '<frequency-percentage>' in that specification. editor's draft css values and units module level 3the definition of '<frequency-percen...
grid-template - CSS: Cascading Style Sheets
the grid-template css property is a shorthand property for defining grid columns, rows, and areas. 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. ...
...d 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 following each string (filling in auto for any missing sizes), and splicing in the named lines defined before/after each size, and grid-template-columns to the track listing specified after the slash (or none, if not specified). note: the repeat() function isn’t allowed in these track listings, as the tracks are intended to visually line up one-to-one with the rows/columns in the “ascii art”. ...
... candidate recommendatio...
hyphens - CSS: Cascading Style Sheets
Web › CSS › hyphens
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; hyphens: manual; hyphens: auto; /* global values */ hyphens: inherit; hyphens: initial; hyphens: unset; the hyphens property is specified as a single keyword value chosen from the list below. values none words are not broken at line breaks, even if characters inside the words suggest line break points. lines will only wrap at whitespace. manual words are broken for line-wrapping only where characters inside the word suggest line break opportunities. see suggesting line break opportunities below for details. auto the browser is free to automatically break words at appropriate...
... are not broken at line breaks, even if characters inside the words suggest line break points. lines will only wrap at whitespace. manual words are broken for line-wrapping only where characters inside the word suggest line break opportunities. see suggesting line break opportunities below for details. auto the browser is free to automatically break words at appropriate hyphenation points, following whatever rules it chooses. however, suggested line break opportunities (see suggesting line break opportunities below) will override automatic break point selection when present. note: the auto setting's behavior depends on the language being properly tagged to select the appropriate hyphenation rules. you must specify a language using the lang html attribute to guarantee that automatic hyp...
...> element leads to a line break, no hyphen is added. formal definition initial valuemanualapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax none | manual | auto examples specifying text hyphenation this example uses three classes, one for each possible configuration of the hyphens property. ...
ident - CSS: Cascading Style Sheets
Web › CSS › ident
the <ident> css data type denotes an arbitrary string used as an identifier. syntax the syntax of <custom-ident> is similar to css identifiers (such as property names), except that it is case-sensitive. it consists of one or more characters, where characters can be any of the following: any alphabetical character (a to z, or a to z), any decimal digit (0 to 9), a hyphen (-), an underscore (_), an escaped character (preceded by a backslash, \), a unicode character (in the format of a backslash, \, followed by one to six hexadecimal digits, representing its unicode code point) note that id1, id1, id1 and id1 are all different identifiers as they are case-sensitive. on the other hand, as there are several ways to escape a character, toto\? and toto\3f are the same identifiers. ex...
...ng its unicode code point) note that id1, id1, id1 and id1 are all different identifiers as they are case-sensitive. on the other hand, as there are several ways to escape a character, toto\? and toto\3f are the same identifiers. ...
...nsitive. on the other hand, as there are several ways to escape a character, toto\? and toto\3f are the same identifiers. examples valid identifiers nono79 a mix of alphanumeric characters and numbers ground-level a mix of alphanumeric characters and a dash -test a dash followed by alphanumeric characters --toto a custom-property like identifier _internal an underscore followed by alphanumeric characters \22 toto a unicode character followed by a sequence of alphanumeric characters bili\.bob a correctly escaped period invalid identifiers 34rem it must not start with a decimal digit. -12rad it must not start with a dash followed by a decimal digit. bili.bob only alphanumeric characters, _, and - needn't be escaped. 'bilibob' this would be a <string>. "bi...
ime-mode - CSS: Cascading Style Sheets
Web › CSS › ime-mode
ft with internet explorer 5 as a proprietary extension: -ms-ime-mode attribute | imemode property. note: in general, it's not appropriate for a public web site to change the ime mode. this property should only be used for private web applications or to undo the property if it was previously set by legacy code. syntax the ime-mode property is specified using one of the keyword values listed below. values auto no change is made to the current input method editor state. this is the default. normal the ime state should be normal; this value can be used in a user style sheet to override the page's setting. this value is not supported by internet explorer. active the input method editor is initially active; text entry is performed through it unless the user specifically dismisses it. ...
...active; text entry is performed through it unless the user specifically dismisses it. not supported on linux. inactive the input method editor is initially inactive, but the user may activate it if they wish. not supported on linux. disabled the input method editor is disabled and may not be activated by the user. ...
.... not supported on linux. disabled the input method editor is disabled and may not be activated by the user. description unlike internet explorer, firefox's implementation of ime-mode allows this property on <input type="password">. however, this makes for a bad user experience, and password fields should not enable the ime. users may correct the inappropriate behavior of sites that don't follow this recommendation by placing the following css into their user stylesheet: input[type=password] { ime-mode: auto !important; } the mac version of gecko 1.9 (firefox 3) can't recover the previous state of the ime when a field for which it is disabled loses focus, so mac users may get grumpy when you use the disabled value. formal definition initial valueautoapplies totext fieldsinheritedno...
justify-self - CSS: Cascading Style Sheets
layouts. */ justify-self: flex-end; /* equivalent to 'end'. note that justify-self is ignored in flexbox layouts. */ justify-self: self-start; justify-self: self-end; justify-self: left; /* pack item from the left */ justify-self: right; /* pack item from the right */ /* baseline alignment */ justify-self: baseline; justify-self: first baseline; justify-self: last baseline; /* overflow alignment (for positional alignment only) */ justify-self: safe center; justify-self: unsafe center; /* global values */ justify-self: inherit; justify-self: initial; justify-self: unset; this property can take one of three different forms: basic keywords: one of the keyword values normal, auto, or stretch. baseline alignment: the baseline keyword, plus optionally one of first or last. po...
...for last baseline is end. stretch if the combined size of the items is less than the size of the alignment container, any auto-sized items have their size increased equally (not proportionally), while still respecting the constraints imposed by max-height/max-width (or equivalent functionality), so that the combined size exactly fills the alignment container. safe if the size of the item overflows the alignment container, the item is instead aligned 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 toblock-level boxes, absolutely-positioned boxes, and grid itemsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto ...
...igned 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 toblock-level boxes, absolutely-positioned boxes, and grid itemsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | normal | stretch | <baseline-position> | <overflow-position>? [ <self-position> | left | right ]where <baseline-position> = [ first | last ]? baseline<overflow-position> = unsafe | safe<self-position> = center | start | end | self-start | self-end | flex-start | flex-end examples simple demonstration in the following example we have a simple 2 x 2 grid layout. initially the grid container is given a justify-items value of stretch — the defau...
list-style-type - CSS: Cascading Style Sheets
ntical to trad-chinese-informal; it exists for legacy reasons. values <custom-ident> a identifier matching the value of a @counter-style or one of the predefined styles: symbols() defines an anonymous style of the list. <string> the specified string will be used as the item's marker. none no item marker is shown. disc a filled circle (default value) circle a hollow circle square a filled square decimal decimal numbers beginning with 1 cjk-decimal han decimal numbers e.g. 一, 二, 三, ..., 九八, 九九, 一〇〇 decimal-leading-zero decimal numbers padded by initial zeros e.g. 01, 02, 03, … 98, 99 lower-roman lowercase roman numerals e.g. i, ii, iii, iv, v… upper-roman upp...
... decimal numbers beginning with 1 cjk-decimal han decimal numbers e.g. 一, 二, 三, ..., 九八, 九九, 一〇〇 decimal-leading-zero decimal numbers padded by initial zeros e.g. 01, 02, 03, … 98, 99 lower-roman lowercase roman numerals e.g. i, ii, iii, iv, v… upper-roman uppercase roman numerals e.g. i, ii, iii, iv, v… lower-greek lowercase classical greek alpha, beta, gamma… e.g. α, β, γ… lower-alpha lower-latin lowercase ascii letters e.g. a, b, c, … z lower-latin is unsupported in ie7 and earlier see browser compatibility section. upper-alpha upper-latin uppercase ascii letters e.g. a, b, c, … z upper-latin is unsupported in ie7 and earlier arabic-indic...
...ha is the old japanese ordering of syllabs. khmer -moz-khmer example korean-hangul-formal korean hangul numbering. e.g., 일만 일천일백일십일 korean-hanja-formal formal korean han numbering. e.g. 壹萬 壹仟壹百壹拾壹 korean-hanja-informal korean hanja numbering. e.g., 萬 一千百十一 lao -moz-lao example lower-armenian * example malayalam -moz-malayalam example mongolian example myanmar -moz-myanmar example oriya -moz-oriya example persian -moz-persian example simp-chinese-formal simplified chinese formal numbering. e.g. 壹万壹仟壹佰壹拾壹 simp-chinese-informal simplified chinese informal number...
list-style - CSS: Cascading Style Sheets
the list-style css shorthand property allows you set all the list style properties at once. 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 property is applied to list items, i.e., elements with display: list-item; . by default this includes <li> elements. because this property is inherited, it can be set on a parent element (normally <ol> or <ul>) to make the same list styling apply to all the items inside. ...
...interactive-examples and send us a pull request. note: this property is applied to list items, i.e., elements with display: list-item; . by default this includes <li> elements. because this property is inherited, it can be set on a parent element (normally <ol> or <ul>) to make the same list styling apply to all the items inside. ...
...apply to all the items inside. constituent properties this property is a shorthand for the following css properties: list-style-image list-style-position list-style-type syntax /* type */ list-style: square; /* image */ list-style: url('../img/shape.png'); /* position */ list-style: inside; /* type | position */ list-style: georgian inside; /* type | image | position */ list-style: lower-roman url('../img/shape.png') outside; /* keyword value */ list-style: none; /* global values */ list-style: inherit; list-style: initial; list-style: unset; the list-style property is specified as one, two, or three keywords in any order. if list-style-type and list-style-image are both set, then list-style-type is used as a fallback if the image is unavailable. values list-style-type ...
margin-trim - CSS: Cascading Style Sheets
the margin-trim property allows the container to trim the margins of its children where they adjoin the container’s edges. syntax none margins are not trimmed by the container. in-flow for in-flow boxes contained by this box, block-axis margins adjacent to the box's edges are truncated to zero. it also truncates any margins collapsed with such a margin. all trims the margins of in-flow boxes and floats whose margins coincide with the container's content edge. formal definition initial valuenoneapplies toblock containers and multi-column containers. ...
...lso truncates any margins collapsed with such a margin. all trims the margins of in-flow boxes and floats whose margins coincide with the container's content edge. formal definition initial valuenoneapplies toblock containers and multi-column containers. ...
...} specifications specification status css box model module level 4the definition of 'margin-trim' in that specification. editor's draft ...
mask-composite - CSS: Cascading Style Sheets
add the source is placed over the destination. ...
... add the source is placed over the destination. ...
... add the source is placed over the destination. subtract the source is placed, where it falls outside of the destination. intersect the parts of source that overlap the destination, replace the destination. exclude the non-overlapping regions of source and destination are combined. ...
mask-size - CSS: Cascading Style Sheets
Web › CSS › mask-size
and height, you can supply one or two values: if only one value is given it sets the width, with the height set to auto. if two values are given, the first sets width 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 co...
...e 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. contain a keyword that scales the image as large as possible and maintains image aspect ratio (image doesn't get squished). the image is letterboxed within the container. the image is automatically centered unless over-ridden by another property such as mask-position. c...
...dimensions and an intrinsic proportion. a vector image may have both intrinsic dimensions and thus it has an intrinsic proportion too. it also may have one or no intrinsic dimensions and in either case it might or might not have an intrinsic proportion. gradients are treated as images with no intrinsic dimensions or intrinsic proportion. the rendered size of the mask image is then computed as follows: if both components of mask-size are specified and are not auto: the mask image renders at the specified size. if the mask-size is contain or cover: the image is rendered by preserving its intrinsic proportion at the largest size contained within or covering the mask positioning area. if the image has no intrinsic proportion, then it is rendered at the size of the mask positioning area. i...
max() - CSS: Cascading Style Sheets
Web › CSS › 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. ...
...max() values, or use max() within a clamp() or calc() function. formal syntax max( <calc-sum># )where <calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]*where <calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]*where <calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> ) examples setting a minimum size for a font another use case for css functions is allow a font size to grow while ensuring it is at least a mimum size, enabling responsive font sizes while ensuring legibility. let's look at some css: h1 { font-size: 2rem; } h1.responsive { font-size: max(4vw, 2em, 2rem); } the font-size will at minimum be 2rems, or twice the default size of font for the page. this ensure it is legible and ensures accessibility <h1>this text is always legibl...
...onsive { font-size: max(4vw, 2em, 2rem); } the font-size will at minimum be 2rems, or twice the default size of font for the page. this ensure it is legible and ensures accessibility <h1>this text is always legible, but doesn't change size</h1> <h1 class="responsive">this text is always legible, and is responsive, to a point</h1> think of the max() function as finding the minimum value allowed for a property. accessibility concerns when max() is used for controlling text size, make sure the text is always large enough to read. a suggestion is to use the min() function nested within a max() that has as its second value a relative length unit that is always large enough to read. for example: small { font-size: max(min(0.5vw, 0.5em), 1rem); } this ensures a minimum size of 1rem, w...
overscroll-behavior-x - CSS: Cascading Style Sheets
ched. see overscroll-behavior for a full explanation. /* keyword values */ overscroll-behavior-x: auto; /* default */ overscroll-behavior-x: contain; overscroll-behavior-x: none; /* global values */ overscroll-behavior-x: inherit; overscroll-behavior-x: initial; overscroll-behavior-x: unset; syntax the overscroll-behavior-x property is specified as a keyword chosen from the list of values below. values auto the default scroll overflow behavior occurs as normal. contain default scroll overflow behavior is observed inside the element this value is set on (e.g. "bounce" effects or refreshes), but no scroll chaining occurs to neighbouring scrolling areas, e.g. underlying elements will not scroll. none no scroll chaining occurs to neighbouring scrolling areas, and default scroll ove...
... values auto the default scroll overflow behavior occurs as normal. contain default scroll overflow behavior is observed inside the element this value is set on (e.g. "bounce" effects or refreshes), but no scroll chaining occurs to neighbouring scrolling areas, e.g. underlying elements will not scroll. none no scroll chaining occurs to neighbouring scrolling areas, and default scroll overflow behavior is prevented. formal definition initial valueautoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax contain | none | auto examples preventing an underlying element from scrolling horizontally in our simple overscroll-behavior-x example (see source code also), we have two block...
...n it so it sits comforably inside the viewport, but its content is given a large width so it will scroll horizontally. by default, when the inner box is scrolled and a scroll boundary is reached, the whole page will begin to scroll, which is probably not what we want. to avoid this, you can set overscroll-behavior-x: contain on the inner box: main > div { height: 300px; width: 500px; overflow: auto; position: relative; top: 100px; left: 100px; overscroll-behavior-x: contain; } specifications specification status comment css overscroll behavior module level 1the definition of 'overscroll-behavior-x' in that specification. working draft ...
overscroll-behavior-y - CSS: Cascading Style Sheets
ll-behavior-y: none; /* global values */ overscroll-behavior-y: inherit; overscroll-behavior-y: initial; overscroll-behavior-y: unset; initial valueautoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete syntax the overscroll-behavior-y property is specified as a keyword chosen from the list of values below. values auto the default scroll overflow behavior occurs as normal. contain default scroll overflow behavior is observed inside the element this value is set on (e.g. "bounce" effects or refreshes), but no scroll chaining occurs to neighbouring scrolling areas, e.g. underlying elements will not scroll. none no scroll chaining occurs to neighbouring scrolling areas, and default scroll ove...
... values auto the default scroll overflow behavior occurs as normal. contain default scroll overflow behavior is observed inside the element this value is set on (e.g. "bounce" effects or refreshes), but no scroll chaining occurs to neighbouring scrolling areas, e.g. underlying elements will not scroll. none no scroll chaining occurs to neighbouring scrolling areas, and default scroll overflow behavior is prevented. ...
...ouring scrolling areas, and default scroll overflow behavior is prevented. formal definition initial valueautoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax contain | none | auto examples preventing an underlying element from scrolling vertically .messages { height: 220px; overflow: auto; overscroll-behavior-y: contain; } see overscroll-behavior for a full example and explanation. specifications specification status comment css overscroll behavior module level 1the definition of 'overscroll-behavior-y' in that specification. working draft ...
overscroll-behavior - CSS: Cascading Style Sheets
ed, the underlying page will then start to scroll — this is called scroll chaining. in some cases these behaviors are not desirable. you can use overscroll-behavior to get rid of unwanted scroll chaining and the browser's facebook/twitter app-inspired "pull to refresh"-type behavior. syntax the overscroll-behavior property is specified as one or two keywords chosen from the list of values below. two keywords specifies the overscroll-behavior value on the x and y axes respectively. if only one value is specified, both x and y are assumed to have the same value. values auto the default scroll overflow behavior occurs as normal. contain default scroll overflow behavior is observed inside the element this value is set on (e.g. "bounce" effects or refreshes), but no scroll chaining o...
... values auto the default scroll overflow behavior occurs as normal. contain default scroll overflow behavior is observed inside the element this value is set on (e.g. "bounce" effects or refreshes), but no scroll chaining occurs to neighbouring scrolling areas, e.g. underlying elements will not scroll. none no scroll chaining occurs to neighbouring scrolling areas, and default scroll overflow behavior is prevented. formal definition initial valueautoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ contain | none | auto ]{1,2} examples preventing an underlying element from scrolling in our overscroll-behavior example (see the source code also), we present a full-page list...
...fake contacts, and a dialog box containing a chat window. both of these areas scroll; normally if you scrolled the chat window until you hit a scroll boundary, the underlying contacts window would start to scroll too, which is not desirable. this can be stopped using overscroll-behavior-y (overscroll-behavior would also work) on the chat window, like this: .messages { height: 220px; overflow: auto; overscroll-behavior-y: contain; } we also wanted to get rid of the standard overscroll effects when the contacts are scrolled to the top or bottom (e.g. chrome on android refreshes the page when you scroll past the top boundary). this can be prevented by setting overscroll-behavior: none on the <body> element: body { margin: 0; overscroll-behavior: none; } specifications ...
paint() - CSS: Cascading Style Sheets
Web › CSS › paint
custom properties are accessible to the pain...
...custom properties are accessible to the paintworklet. specifications specification status comment css painting api level 1the definition...
...custom properties are accessible to the paintworklet. ...
perspective-origin - CSS: Cascading Style Sheets
ve-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. ...
...the value may be negative. left, a keyword being a shortcut for the 0 length value. center, a keyword being a shortcut for the 50% percentage value. ...
...tion as an absolute length value or relative to the width of the element. the value may be negative. left, a keyword being a shortcut for the 0 length value. center, a keyword being a shortcut for the 50% percentage value. right, a keyword being a shortcut for the 100% percentage value. y-position indicates the position of the ordinate of the vanishing point. it can have one of the following values: <length-percentage> indicating the position as an absolute length value or relative to the height of the element. the value may be negative. top, a keyword being a shortcut for the 0 length value. center, a keyword being a shortcut for the 50% percentage value. bottom, a keyword being a shortcut for the 100% percentage value. formal definition initial value50% 50%appli...
repeat() - CSS: Cascading Style Sheets
Web › CSS › repeat
this function can be used in the css grid properties grid-template-columns and grid-template-rows. ...
...pying the grid track. auto as a maximum, identical to max-content. as a minimum it represents the largest minimum size (as specified by min-width/min-height) of the grid items occupying the grid track. auto-fill if the grid container has a definite or maximal size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container. treating each track as its maximal track sizing function (each independant value used to define grid-template-rows or grid-template-columns), if that is definite. otherwise, as its minimum track sizing function, and taking grid-gap into account. if any number of repetitions would overflow, then the repetition is 1. otherwise, if the grid container has a definite minimal size i...
...ise, if the grid container has a definite minimal size in the relevant axis, the number of repetitions is the smallest possible positive integer that fulfills that minimum requirement. otherwise, the specified track list repeats only once. auto-fit behaves the same as auto-fill, except that after placing the grid items any empty repeated tracks are collapsed. an empty track is one with no in-flow grid items placed into or spanning across it. (this can result in all tracks being collapsed, if they’re all empty.) a collapsed track is treated as having a single fixed track sizing function of 0px, and the gutters on either side of it collapse. for the purpose of finding the number of auto-repeated tracks, the user agent floors the track size to a user agent specified value (e.g., 1px), ...
<resolution> - CSS: Cascading Style Sheets
as with all css dimensions, there is no space between the unit literal and the number. ...
...as with all css dimensions, there is no space between the unit literal and the number. ...
...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 specification. editor's draft adds the x unit. css values and units module level 3the definition of '<resolution>' in tha...
scroll-behavior - CSS: Cascading Style Sheets
active examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. note that any other scrolls, such as those performed by the user, are not affected by this property. when this property is specified on the root element, it applies to the viewport instead. this property specified on the body element will not propagate to the viewport. user agents are allowed to ignore this property. 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 u...
... /* 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-container> <scroll-page id="page-1">1</scroll-page> <scroll-page...
... working draft initial specification ...
scroll-margin-inline-end - CSS: Cascading Style Sheets
blocks, the second and third of which snap into place, near but not quite at the right of each block. html the html that represents the blocks is very simple: <div class="scroller"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> </div> css let's walk through the css. ...
...roller"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> </div> css let's walk through the css. ...
... border: 1px solid #000; scroll-snap-type: x mandatory; } the main parts relevant to the scroll snapping are overflow-x: scroll, which makes sure the contents will scroll and not be hidden, and scroll-snap-type: x mandatory, which dictates that scroll snapping must occur along the horizontal axis, and the scrolling will always come to rest on a snap point. ...
scroll-margin-inline-start - CSS: Cascading Style Sheets
blocks, the second and third of which snap into place, near but not quite at the left of each block. html the html that represents the blocks is very simple: <div class="scroller"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> </div> css let's walk through the css. ...
...roller"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> </div> css let's walk through the css. ...
... border: 1px solid #000; scroll-snap-type: x mandatory; } the main parts relevant to the scroll snapping are overflow-x: scroll, which makes sure the contents will scroll and not be hidden, and scroll-snap-type: x mandatory, which dictates that scroll snapping must occur along the horizontal axis, and the scrolling will always come to rest on a snap point. ...
scroll-snap-type - CSS: Cascading Style Sheets
y mand. rtl</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> </div> <div class="container y proximity-scroll-snapping" dir="rtl"> <div>y prox. ...
...<div class="container y proximity-scroll-snapping" dir="rtl"> <div>y prox. ...
... <div>4</div> <div>5</div> </div> </div> css /* setup */ html, body, .holster { height: 100%; } .holster { 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; height: 256px; flex-flow: column nowrap; } /* scroll-snap */ .x.mandatory-scroll-snapping { scroll-snap-type: x mandatory; } .y.mandatory-scroll-snapping { scroll-snap-type: y mandatory; } .x.proximity-scroll-snapping { scroll-snap-type: x proximity; } .y.proximity-scroll-snapping { scroll-snap-type: y proximity; } .container > div { ...
text-emphasis-position - CSS: Cascading Style Sheets
rizontal writing mode. right draws marks to the right of the text in vertical writing mode. left draw marks to the left of the text in vertical writing mode. description the preferred position of emphasis marks depends on the language. in japanese for example, the preferred position is over right. in chinese, on the other hand, the preferred position is under right. ...
...ot reset either, using the text-emphasis shorthand property. formal definition initial valueover rightapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ over | under ] && [ right | left ] examples preferring ruby over emphasis marks some editors prefer to hide emphasis marks when they conflict with ruby. ...
...r | under ] && [ right | left ] examples preferring ruby over emphasis marks some editors prefer to hide emphasis marks when they conflict with ruby. in html, this can be done with the following style rule: ruby { text-emphasis: none; } preferring emphasis marks over ruby some other editors prefer to hide ruby when they conflict with emphasis marks. in html, this can be done with the following pattern: em { text-emphasis: dot; /* set text-emphasis for <em> elements */ } em rt { display: none; /* hide ruby inside <em> elements */ } specifications specification status comment css text decoration module level 3the definition of 'text-emphasis' in that specification. candidate recommendation initial definition ...
text-underline-position - CSS: Cascading Style Sheets
line-position: unset; syntax values auto the user agent uses its own algorithm to place the line at or under the alphabetic baseline. from-font if the font file includes information about a preferred position, use that value. if the font file doesn't include this information, behave as if auto was set, with the browser choosing an appropriate position. under forces the line to be set below the alphabetic baseline, at a position where it won't cross any descenders. this is useful for ensuring legibility with chemical and mathematical formulas, which make a large use of subscripts. left in vertical writing-modes, this keyword forces the line to be placed on the left side of the text. in horizontal writing-modes, it is a synonym of under. right in vertical writing-modes, this keyw...
...ting-modes, it is a synonym of under. right in vertical writing-modes, this keyword forces the line to be placed on the right side of the text. in horizontal writing-modes, it is a synonym of under. auto-pos a synonym of auto, which should be used instead. above forces the line to be above the text. when used with east-asian text, using the auto keyword will lead to a similar effect. below forces the line to be below the text. when used with alphabetic text, using the auto keyword will lead to a similar effect. formal definition initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | from-font | [ under | [ left | right ] ] examples a simple example let's take a couple of simple example paragraphs: <p clas...
... font-size: 1.5rem; text-transform: capitalize; text-decoration: underline; text-decoration-thickness: 2px; } .horizontal { text-underline-position: under; } .vertical { writing-mode: vertical-rl; text-underline-position: left; } in this example we set both the paragraphs to have a thick underline. in the horizontal text we use text-underline-position: under; to put the underline below all the descenders. in the text with a vertical writing-mode set, we can then use values of left or right to make the underline appear on the left or right of the text as required. the live example looks like this: setting text-underline-position globally because the text-underline-position property inherits and is not reset by the text-decoration shorthand property, it may be appropriate t...
<time> - CSS: Cascading Style Sheets
Web › CSS › time
the <time> css data type represents a time value expressed in seconds or milliseconds. it is used in animation, transition, and related properties. syntax the <time> data type consists of a​ ​​​​​​<number> followed by one of the units listed below. optionally, it may be preceded by a single + or - sign. as with all dimensions, there is no space between the unit literal and the number. 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 0s or 0ms. units s represents a time in seconds. examples: 0s, 1.5s, -60s. ms represents a time in milliseconds. examples: 0ms, 150.25ms, -60000ms. note: conversion between s and ms follows the logical 1s = 1000ms. examples valid time...
... specifications specification status comment css values and units module level 4the definition of '<time>' in that specification. ...
... non-integer 14ms the unit is case-insensitive, although capital letters are not recommended. +0s zero with a leading + and a unit -0ms zero with a leading - and a unit invalid times 0 although unitless zero is allowed for <length>s, it's invalid for <time>s. 12.0 this is a <number>, not a <time>, because it's missing a unit. 7 ms no space is allowed between the number and the unit. specifications specification status comment css values and units module level 4the definition of '<time>' in that specification. editor's draft css values and units module level 3the definition of '<time>' in that specification. candidate recommendation normative definition of s and ms. css level 2 (r...
<transform-function> - CSS: Cascading Style Sheets
each function applies a geometric operation in either 2d or 3d. ...
...re must be special-cased when using this notation: translation. the translation vector (tx, ty) must be expressed separately, as two additional parameters. note: though trickier than cartesian coordinates, homogeneous coordinates in projective geometry lead to 3×3 transformation matrices, and can simply express translations as linear functions. examples transform function comparison the following example provides a 3d cube created from dom elements and transforms, and a select menu allowing you to choose different transform functions to transform the cube with, so you can compare the effects of the different types. choose one, and the transform is applied to the cube; after 2 seconds, the cube reverts back to its starting state. the cube's starting state is slightly rotated using tran...
...ides a 3d cube created from dom elements and transforms, and a select menu allowing you to choose different transform functions to transform the cube with, so you can compare the effects of the different types. choose one, and the transform is applied to the cube; after 2 seconds, the cube reverts back to its starting state. the cube's starting state is slightly rotated using transform3d(), to allow you to see the effect of all the transforms. html <main> <section id="example-element"> <div class="face front">1</div> <div class="face back">2</div> <div class="face right">3</div> <div class="face left">4</div> <div class="face top">5</div> <div class="face bottom">6</div> </section> <div class="select-form"> <label>select a transform function</...
white-space - CSS: Cascading Style Sheets
the white-space css property sets how white space inside an element is handled. 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: to make words break within themselves, use overflow-wrap, word-break, or hyphens instead. syntax /* keyword values */ white-space: normal; white-space: nowrap; white-space: pre; white-space: pre-wrap; white-space: pre-line; white-space: break-spaces; /* global values */ white-space: inherit; white-space: initial; white-space: unset; the white-space property is specified as a single keyword chosen from the list of values below. values normal sequences of white space are co...
... 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). ...
.... ...
word-break - CSS: Cascading Style Sheets
the word-break css property sets whether line breaks appear wherever the text would otherwise overflow its content box. 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 values */ word-break: normal; word-break: break-all; word-break: keep-all; word-break: break-word; /* deprecated */ /* global values */ word-break: inherit; word-break: initial; word-break: unset; the word-break property is specified as a single keyword chosen from the list of values below. ...
...est. syntax /* keyword values */ word-break: normal; word-break: break-all; word-break: keep-all; word-break: break-word; /* deprecated */ /* global values */ word-break: inherit; word-break: initial; word-break: unset; the word-break property is specified as a single keyword chosen from the list of values below. values normal use the default line break rule. break-all to prevent overflow, word breaks should be inserted between any two characters (excluding chinese/japanese/korean text). keep-all word breaks should not be used for chinese/japanese/korean (cjk) text. non-cjk text behavior is the same as for normal. break-word has the same effect as word-break: normal and overflow-wrap: anywhere, regardless of the actual value of the overflow-wrap property. note: in contras...
...een any two characters (excluding chinese/japanese/korean text). keep-all word breaks should not be used for chinese/japanese/korean (cjk) text. non-cjk text behavior is the same as for normal. break-word has the same effect as word-break: normal and overflow-wrap: anywhere, regardless of the actual value of the overflow-wrap property. note: in contrast to word-break: break-word and overflow-wrap: break-word (see overflow-wrap), word-break: break-all will create a break at the exact place where text would otherwise overflow its container (even if putting an entire word on its own line would negate the need for a break). formal definition initial valuenormalapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | break-all | keep-a...
EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes exslt is a set of extensions to xslt. there are a number of modules; those that are supported by firefox are listed below: common (exsl)the exslt common package provides basic functions that expand upon the capabilities of xslt.math (math)the exslt math package provides functions for working with numeric values and comparing nodes.regular expressions (regexp)the exslt regular expressions package provides functions that allow testing, matching, and replacing text using javascript style regular expressions.sets (set)the exslt sets package offers functions that let you perform set manipulation.strings (str)the exslt strings package provides functions that allow the manipulation of strings. exslt mo...
...lt common package provides 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 tha...
...sions. functions regexp:match() regexp:replace() regexp:test() sets the exslt sets package offers functions that let you perform set manipulation. the namespace for these functions is http://exslt.org/sets. functions set:difference() set:distinct() set:intersection() set:has-same-node() set:leading() set:trailing() strings the exslt strings package provides functions that allow the manipulation of strings. the namespace for the strings package is http://exslt.org/strings. functions str:concat() str:split() str:tokenize() ...
Web Audio playbackRate explained - Developer guides
this article explains playbackrate in detail. playbackrate basics let's starting by looking at a brief example of playbackrate usage: var myaudio = document.createelement('audio'); myaudio.setattribute('src','audiofile.mp3'); myaudio.playbackrate = 0.5; here we create an <audio> element, and set its src to a file of our choice. ...
... note: try out this example live, and try adjusting the playback rate control to see the effect. defaultplaybackrate and ratechange in addition to playbackrate, we also have a defaultplaybackrate property available, which lets us set the default playback rate: the playback rate to which the media resets; for example, if we change the ...
...justing the playback rate control to see the effect. defaultplaybackrate and ratechange in addition to playbackrate, we also have a defaultplaybackrate property available, which lets us set the default playback rate: the playback rate to which the media resets; for example, if we change the source of the video, or (in some browsers) when an ended event is generated. so defaultplaybackrate allows us to set the playback rate before playing the media, while playbackrate allows us to change it during media playback. there is also an event available called ratechange, which fires every time the playbackrate changes. browser support chrome 20+ ✔ firefox 20+ ✔ ie 9+ ✔ safari 6+ ✔ opera 15+ ✔ mobile chrome (android) ✖ mobile firefox 24+ ✔ ie mobile ✖ mobile safari...
Creating and triggering events - Developer guides
this article demonstrates how to create and dispatch dom events. such events are commonly called synthetic events, as opposed to the events fired by the browser itself. creating custom events events can be created with the event constructor as follows: const event = new event('build'); // listen for the event. elem.addeventlistener('build', function (e) { /* ... */ }, false); // dispatch the event. elem.dispatchevent(event); the above code example uses the eventtarget.dispatchevent() method. this constructor is supported in most modern browsers (with internet explorer being the exception). for a more verbose approach (which works with internet explorer), see the old-fashioned way below. adding custom data – customevent() to add more data to the event object, the customevent...
...tor is supported in most modern browsers (with internet explorer being the exception). for a more verbose approach (which works with internet explorer), see the old-fashioned way below. adding custom data – customevent() to add more data to the event object, the customevent interface exists and the detail property can be used to pass custom data. for example, the event could be created as follows: const event = new customevent('build', { detail: elem.dataset.time }); this will then allow you to access the additional data in the event listener: function eventhandler(e) { console.log('the time is: ' + e.detail); } the old-fashioned way the older approach to creating events uses apis inspired by java. the following shows an example with document.createevent(): // create the event. ...
...s elem }, false); // target can be any element or other eventtarget. ...
DOM onevent handlers - Developer guides
such as click) for a given object in different ways: adding an html attribute named on<eventtype>: <button onclick="handleclick()">, or by setting the corresponding property from javascript: document.queryselector("button").onclick = function(event) { … }. an onevent event handler property serves as a placeholder of sorts, to which a single event handler can be assigned. ...
...you don't need to call them yourself, although you can do so in many cases to easily simulate an event taking place. for example, given a button object mybutton, you can do mybutton.onclick(myeventobject) to call the event handler directly. ...
... reasons, some attributes/properties on the <body> and <frameset> elements instead set event handlers on their parent window object. (the html specification names these: onblur, onerror, onfocus, onload, and onscroll.) event handler's parameters, this binding, and the return value when the event handler is specified as an html attribute, the specified code is wrapped into a function with the following parameters: event — for all event handlers except onerror. 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 documen...
Mutation events - Developer guides
observers are the proposed replacement for mutation events in dom4. they are expected to be included in firefox 14 and chrome 18. the practical reasons to avoid the mutation events are performance issues and cross-browser support. performance adding dom mutation listeners to a document profoundly degrades the performance of further dom modifications to that document (making them 1.5 - 7 times slower!). moreover, removing the listeners does not reverse the damage. the performance effect is limited to the documents that have the mutation event listeners. cross-browser support these events are not implemented consistently across different browsers, for example: ie prior to version 9 didn't support the mutation events at all and does not implement some of them correctly in version 9 (for...
...hem correctly in version 9 (for example, domnodeinserted) webkit doesn't support domattrmodified (see webkit bug 8191 and the workaround) "mutation name events", i.e. domelementnamechanged and domattributenamechanged are not supported in firefox (as of version 11), and probably in other browsers as well. ... dottoro documents browser support for mutation events. ...
...& (desc === root || isdescendant(desc.parentnode, root)); }; var onremove = function (element, callback) { var observer = new mutationobserver(function (mutations) { _.foreach(mutations, function (mutation) { _.foreach(mutation.removednodes, function (removed) { if (isdescendant(element, removed)) { callback(); // allow garbage collection observer.disconnect(); observer = undefined; } }); }); }); observer.observe(document, { childlist: true, subtree: true }); }; usage you can register a listener for mutation events using element.addeventlistener as follows: element.addeventlistener("domnodeinserted", functi...
Localizations and character encodings - Developer guides
e utf-8 encoding (which can represent all of unicode) and regardless of the encoding used requires web content to declare what encoding was used. the <meta> element's charset attribute is used to specify the page's character encoding. it must be used within a <head> block. to specify that a page is using, for example, the utf-8 character encoding (as per the recommendation), simply place the following line in the <head> block: <meta charset="utf-8"> details and browser internals when the encoding is declared by web content like the html specification requires, firefox will use that encoding for turning the bytes into the internal representation. unfortunately, using utf-8 and declaring that utf-8 was used was not always the prevalent way of offering web content. in the 1990s, it was com...
...here is a small number of locales where in the 1990s there wasn't an obvious single region-specific encoding and heuristic detection among multiple legacy encodings was introduced to web browsers. this has then had the effect that web authors have depended on heuristic detection being present, so firefox still has heuristic detection in these locales. finding canonical encoding names the text below refers to canonical names of encodings. the canonical names are the values to the right of the equals sign in unixcharset.properties. specifying the fallback encoding as of firefox 28, this section 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 pr...
...uld typically be set to the same value as in internet explorer. you can see the fallback encoding a particular browser has by loading a test page. (be sure to use a browser installation that has its settings left to the defaults when investigating!) for locales where firefox has more market share than internet explorer, it's probably best not to change the fallback encoding even if it doesn't follow the guidance given above. (for example, the fallback encoding for the polish, hungarian and czech locales should probably continue to be iso-8859-2 even though ie has a different fallback encoding.) when in doubt, use windows-1252 as the fallback encoding. specifying the heuristic detection mode the heuristic detection mode is specified by the preference intl.charset.detector in intl.propertie...
A hybrid approach - Developer guides
referred option for layout changes. however, it can be a pain to use client-side techniques to alter site content to fit the user’s context. luckily, we aren’t technically constrained to using client-side techniques here: another option is to use server-side user-agent detection to show the user the proper content. this keeps the complexity of altering content on the server side, but still allows our layouts to benefit from the flexibility and future-readiness of responsive design. using user-agent detection specifically for content and not layout also allows you to have a single url for each piece of content, so that the content can adapt its layout to the user’s browser. this is generally thought to be a good thing. instead of maintaining two completely different sites, we simply re...
... 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 heavily modify the content or user flow for mobile users should probably go for a separate mobile site. content-oriented pages that don’t need to modify their content for mobile users will be satisfied with responsive design. if you need to slightly alter the site’s message for mobile users, but want to reap the benefits of a responsive design, a hybrid approach may be your best bet. decisions like these are at the heart of mobile ...
...eed to slightly alter the site’s message for mobile users, but want to reap the benefits of a responsive design, a hybrid approach may be your best bet. decisions like these are at the heart of mobile web development: be specific about what you would like to accomplish, and pick a practical approach while being aware of the tradeoffs. good luck! approaches to mobile web development see the following articles for background and other approaches to developing for mobile platforms. what is mobile-friendliness? separate sites responsive design original document information this article was originally published on 27 june 2011, on the mozilla webdev blog as "approaches to mobile web development part 4 – a hybrid approach", by jason grlicky. ...
Separate sites for mobile and desktop - Developer guides
for their phone and optimized for speed. conceptually simple, this is the easiest option to add to an existing site, especially if you are using a cms or web application that supports templates. since only the mobile-specific content, styles, and scripts are sent to mobile users, this method also provides for the best performance out of any of the other options presented here. finally, it also allows 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 mini...
... the fact that user-agent detection is inherently flawed, and anything but future-proof. every time a new browser comes out, you must adjust your algorithm to accommodate it. and false positives are particularly scary — it could be embarrassing to serve desktop users your mobile site accidentally. when it is right to choose this option firstly, if your target audience includes users on older or low-end feature phones, it is worth noting that you may need to employ this strategy to some degree no matter what. this is because the default browsers on some feature-phones do not support the same markup that you would use to code a website targeted at the desktop, but instead understand formats like xhtml-mp or the older wml. this factor aside, there is one case where this strategy really shines ...
... in the wild have chosen this path, including facebook, youtube, digg, and flickr. in fact, mozilla picked this strategy for the mobile versions of addons.mozilla.org (amo) and support.mozilla.org (sumo). if you’d like to see the source code behind an example of this approach in action, feel free to check out the github repository for amo or sumo. approaches to mobile web development see the following articles for background and other approaches to developing for mobile platforms. what is mobile-friendliness? responsive design a hybrid approach original document information this article was originally published on 13 may 2011, on the mozilla webdev blog as "approaches to mobile web development part 2 – separate sites", by jason grlicky. ...
Printing - Developer guides
result. you want to adjust the user experience of printing, such as presenting a specially-formatted version of your content before printing begins. there may be other cases in which you want to manage the printing process, but these are some of the most common scenarios. this article 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...
...you can also try changing the code to use <code>beforeprint</code> to see the difference.</p> <p><a href="javascript: popuponclick()">open popup window</a></p> </body> </html> view live examples print an external page without opening it if you want to be able to print an external page without opening it, you can utilize a hidden <iframe> (see: htmliframeelem...
...code>beforeprint</code> to see the difference.</p> <p><a href="javascript: popuponclick()">open popup window</a></p> </body> </html> view live examples print an external page without opening it if you want to be able to print an external page without opening it, you can utilize a hidden <iframe> (see: htmliframeelement), automatically removing it after the user prints its contents. ...
HTML attribute: min - HTML: Hypertext Markup Language
Web › HTML › Attributes › min
this must be less than the minimum value (max attribute), if specified. in both cases, if omitted, the value defaults to 1. syntax for min values for other elements input type syntax example <meter> <number> <meter id="fuel" min="0" max="100...
... 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 min value set, the value is considered invalid in contraint validation and will match the :invalid pseudoclass see client-side validation and rangeunderflow for more information. for the <meter> element, the min attribute defines the lower numeric bound of the measured range. ...
...or more information. for the <meter> element, the min attribute defines the lower numeric bound of the measured range. this must be less than the minimum value (max attribute), if specified. in both cases, if omitted, the value defaults to 1. syntax for min values for other elements input type syntax example <meter> <number> <meter id="fuel" min="0" max="100" low="33" high="66" optimum="80" value="40"> at 40/100</meter> impact on step the value of min and step define what are valid values, even if the step attribute is not included, as step defaults to 0. we add a big red border around invalid inputs: input:invalid { border: solid red 3px; } then define an input with a minimum value of 7.2, omitting the step attribute, wherein it defaults to ...
Block-level elements - HTML: Hypertext Markup Language
nt element (container), thereby creating a "block." this article helps to explain what this means. browsers typically display the block-level element with a newline both before and after the element. you can visualize them as a stack of boxes. a block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can). the following example demonstrates the block-level element's influence: block-level elements html <p>this paragraph is a block-level element; its background has been colored to display the paragraph's parent element.</p> css p { background-color: #8abb55; } usage block-level elements may appear only within a <body> element. block-level vs. inline there are a couple of key differences between ...
...nline elements was used in html specifications up to 4.01. in html5, this binary distinction is replaced with a more complex set of content categories. while the "inline" category roughly corresponds to the category of phrasing content, the "block-level" category doesn't directly correspond to any html5 content category, but "block-level" and "inline" elements combined together correspond to the flow content in html5. there are also additional categories, e.g. interactive content. elements the following is a complete list of all html "block-level" elements (although "block-level" is not technically defined for elements that are new in html5). <address> contact information. <article> article content. <aside> aside content. <blockquote> long ("block") quotation. <details> disclos...
... groups header information. <hr> horizontal rule (dividing line). <li> list item. <main> contains the central content unique to this document. <nav> contains navigation links. <ol> ordered list. <p> paragraph. <pre> preformatted text. <section> section of a web page. <table> table. <ul> unordered list. see also inline elements display block and inline layout in normal flow ...
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
Web › HTML › Element › abbr
ribute can provide an expansion or description for the abbreviation. if present, title must contain this full description and nothing else. 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. permitted parents any element that accepts phrasing content implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this eleme...
...om all others; providing a title for one does not automatically attach the same expansion text to others with the same content text. usage notes typical use cases it's certainly not required that all abbreviations be marked up using <abbr>. there are, though, a few cases where it's helpful to do so: when an abbreviation is used and you want to provide an expansion or definition outside the flow of the document's content, use <abbr> with an appropriate title. to define an abbreviation which may be unfamiliar to the reader, present the term using <abbr> and either a title attribute or inline text providing the definition. when an abbreviation's presence in the text needs to be semantically noted, the <abbr> element is useful. this can be used, in turn, for styling or scripting purposes.
...br> and either a title attribute or inline text providing the definition. when an abbreviation's presence in the text needs to be semantically noted, the <abbr> element is useful. this can be used, in turn, for styling or scripting purposes. you can use <abbr> in concert with <dfn> to establish definitions for terms which are abbreviations or acronyms. see the example defining an abbreviation below. grammar considerations in languages with grammatical number (that is, languages where the number of items affects the grammar of a sentence), use the same grammatical number in your title attribute as inside your <abbr> element. this is especially important in languages with more than two numbers, such as arabic, but is also relevant in english. default styling the purpose of this element i...
<area> - HTML: Hypertext Markup Language
Web › HTML › Element › area
fines a hot-spot region on an image, and optionally associates it with a hypertext link. this element is used only within a <map> 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. content categories flow content, phrasing content. permitted content none, it is an empty element. tag omission must have a start tag and must not have an end tag. permitted parents any element that accepts phrasing content. the <area> element must have an ancestor <map>, but it need not be a direct parent. implicit aria role link when href attribute is present, otherwise ...
...download this attribute, 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" ...
... which defines a circular region; poly, which defines a polygon; and default, which indicates the entire region beyond any defined shapes. many browsers, notably internet explorer 4 and higher, support circ, polygon, and rectangle as valid values for shape, but these values are non-standard. target a keyword or author-defined name of the browsing context to display the linked resource. the following keywords have special meanings: _self (default): show the resource in the current browsing context. _blank: show the resource in a new, unnamed browsing context. _parent: show the resource in the parent browsing context of the current one, if the current page is inside a frame. if there is no parent, acts the same as _self. _top: show the resource in the topmost browsing context (the...
<button>: The Button element - HTML: Hypertext Markup Language
Web › HTML › Element › button
, html buttons are presented in a style resembling the platform the user agent runs on, but you can change buttons’ appearance with css. 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, interactive content, listed, labelable, and submittable form-associated element, palpable content. permitted content phrasing content but there must be no interactive content tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. implicit aria role bu...
...ements. formtarget html5 if the button is a submit button, this attribute is a author-defined name or standardized, underscore-prefixed keyword indicating where to display the response from submitting the form. this is the name of, or keyword for, a browsing context (a tab, window, or <iframe>). if this attribute is specified, it overrides the target attribute of the button's form owner. the following keywords have special meanings: _self: load the response into the same browsing context as the current one. this is the default if the attribute is not specified. _blank: load the response into a new unnamed browsing context — usually a new tab or window, depending on the user’s browser settings. _parent: load the response into the parent browsing context of the current one. if the...
... the giant-button-problem - axess lab firefox firefox will add a small dotted 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 lar...
<caption>: The Table Caption element - HTML: Hypertext Markup Language
Web › HTML › Element › caption
the html <caption> element specifies the caption (or title) of a table. 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 none. permitted content flow content. tag omission the end tag can be omitted if the element is not immediately followed by ascii whitespace or a comment. permitted parents a <table> element, as its first descendant. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmltablecaptionelement attributes this element includes the global attributes. ...
...if the element is not immediately followed by ascii whitespace or a comment. permitted parents a <table> element, as its first descendant. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmltablecaptionelement attributes this element includes the global attributes. deprecated attributes the following attributes are deprecated and should not be used. they are documented below for reference when updating existing code and for historical interest only. align this enumerated attribute indicates how the caption must be aligned with respect to the table. it may have one of the following values: left the caption is displayed to the left of the table. top the caption is displayed a...
... usage note: do not use this attribute, as it has been deprecated. the <caption> element should be styled using the css properties caption-side and text-align. ...
<dl>: The Description List element - HTML: Hypertext Markup Language
Web › HTML › Element › dl
(provided by <dd> elements). common uses for this element are to implement a glossary or to display metadata (a list of key-value pairs). 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, and if the <dl> element's children include one name-value group, palpable content. permitted content either: zero or more groups each consisting of one or more <dt> elements followed by one or more <dd> elements, optionally intermixed with <script> and <template> elements. or: one or more <div> elements, optionally intermixed with <script> and <template> elements. ...
... implicit aria role no corresponding role permitted aria roles group, list, none, presentation dom interface htmldlistelement attributes this element only includes the global attributes. ...
...iption lists are useful for displaying metadata as a list of key-value pairs. <dl> <dt>name</dt> <dd>godzilla</dd> <dt>born</dt> <dd>1952</dd> <dt>birthplace</dt> <dd>japan</dd> <dt>color</dt> <dd>green</dd> </dl> tip: it can be handy to define a key-value separator in the css, such as: dt::after { content: ": "; } wrapping name-value groups in <div> elements whatwg html allows wrapping each name-value group in a <dl> element in a <div> element. this can be useful when using microdata, or when global attributes apply to a whole group, or for styling purposes. <dl> <div> <dt>name</dt> <dd>godzilla</dd> </div> <div> <dt>born</dt> <dd>1952</dd> </div> <div> <dt>birthplace</dt> <dd>japan</dd> </div> <div> <dt>color</dt> <dd>gr...
<figure>: The Figure with Optional Caption element - HTML: Hypertext Markup Language
Web › HTML › Element › figure
al caption, which is specified using the (<figcaption>) element. the figure, its caption, and its contents are referenced as a single unit. 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, sectioning root, palpable content. permitted content a <figcaption> element, followed by flow content; or flow content followed by a <figcaption> element; or flow content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. implicit aria role figure permitted a...
... being a sectioning root, the outline of the content of the <figure> element is excluded from the main outline of the document. a caption can be associated with the <figure> element by inserting a <figcaption> inside it (as the first or the last child). ...
...tion descendant: any, otherwise no permitted roles dom interface htmlelement attributes this element only includes the global attributes. usage notes usually a <figure> is an image, illustration, diagram, code snippet, etc., that is referenced in the main flow of a document, but that can be moved to another part of the document or to an appendix without affecting the main flow. being a sectioning root, the outline of the content of the <figure> element is excluded from the main outline of the document. a caption can be associated with the <figure> element by inserting a <figcaption> inside it (as the first or the last child). the first <figcaption> element found in the figure is presented as the figure's caption. examples images <!-- just an image --> <figure> ...
<kbd>: The Keyboard Input element - HTML: Hypertext Markup Language
Web › HTML › Element › kbd
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. <kbd> may be nested in various combinations with the <samp> (sample output) element to represent various forms of input or output based on visual cues. content categories flow content, phrasing content, palpable content. permitted content phrasing content. tag omission 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 any dom interface htmlelement attributes this el...
...les any dom interface htmlelement attributes this element only includes the global attributes. usage notes other elements can be used in tandem with <kbd> to represent more specific scenarios: nesting a <kbd> element within another <kbd> element represents an actual key or other unit of input as a portion of a larger input. see representing keystrokes within an input below. nesting a <kbd> element inside a <samp> element represents input that has been echoed back to the user by the system. see echoed input, below, for an example. nesting a <samp> element inside a <kbd> element, on the other hand, represents input which is based on text presented by the system, such as the names of menus and menu items, or the names of buttons displayed on the screen. see the exam...
... you can define a custom style to override the browser's default font selection for the <kbd> element, although the user's preferences may potentially override your css. ...
<picture>: The Picture element - HTML: Hypertext Markup Language
Web › HTML › Element › picture
which has too many details, on smaller displays). offering alternative image formats, for cases where certain formats are not supported. saving bandwidth and speeding page load times by loading the most appropriate image for the viewer's display. if providing higher-density versions of an image for high-dpi (retina) display, use srcset on the <img> element instead. this lets browsers opt for lower-density versions in data-saving modes, and you don't have to write explicit media conditions. content categories flow content, phrasing content, embedded content permitted content zero or more <source> elements, followed by one <img> element, optionally intermixed with script-supporting elements. tag omission none, both the starting and ending tag are mandat...
... implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlpictureelement attributes this element includes only global attributes. ...
...ture>. <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, followed by an x (such as 2x) to serve a high-res image for high-dpi screens. <picture> <source srcset="logo-768.png 768w, logo-768-1.5x.png 1.5x"> <source srcset="logo-480.png, logo-480-2x.png 2x"> <img src="logo-320.png" alt="logo"> </picture> the type attribute the type attribute specifies a mime type for the resource url(s) ...
<shadow>: The obsolete Shadow Root element - HTML: Hypertext Markup Language
Web › HTML › Element › shadow
the html <shadow> element—an obsolete part of the web components technology suite—was intended to be used as a shadow dom insertion point. you might have used it if you have created multiple shadow roots under a shadow host. it is not useful in ordinary html. content categories transparent content permitted content flow content tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. permitted aria roles none dom interface htmlshadowelement attributes this element includes the global attributes. example here is a simple example of using the <shadow> element. it is an html file with everything needed in it. note: this is an experimental ...
... specifications this element is no longer defined by any specifications. ...
... &lt;shadow&gt;</p>'; // insert into younger shadow root, including <shadow>. // the previous markup will not be displayed unless // <shadow> is used below. shadowroot2.innerhtml = '<shadow></shadow> <p>younger shadow root, displayed because it is the youngest.</p>'; </script> </body> </html> if you display this in a web browser it should look like the following. specifications this element is no longer defined by any specifications. ...
<sub>: The Subscript element - HTML: Hypertext Markup Language
Web › HTML › Element › sub
permitted content phrasing content. ...
... permitted content phrasing content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. ...
...for example: <p>the horizontal coordinates' positions along the x-axis are represented as <var>x<sub>1</sub></var> ... <var>x<sub>n</sub></var>.</p> the resulting output: chemical formulas when writing a chemical formula, such as h20, the number of atoms of a given element within the described molecule is represented using a subscripted number; in the case of water, the subscripted "2" ...
<sup>: The Superscript element - HTML: Hypertext Markup Language
Web › HTML › Element › sup
be displayed as superscript for solely typographical reasons. superscripts are usually rendered with a raised baseline using smaller 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. content categories flow content, phrasing content, palpable content. permitted content phrasing content. tag omission 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 any dom interface htmlelement attributes this el...
...st likely vertical-align) rather than <sup>. this would be done using, for example, vertical-align: super or, to shift the baseline up 50%, vertical-align: 50%. appropriate use cases for <sup> include (but aren't necessarily limited to): displaying exponents, such as "x3." it may be worth considering the use of mathml for these, especially in more complex cases. see exponents under examples below. displaying superior lettering, which is used in some languages when rendering certain abbreviations. for example, in french, the word "mademoiselle" can be abbreviated "mlle"); this is an acceptable use case. see superior lettering for examples. representing ordinal numbers, such as "4th" instead of "fourth." see ordinal numbers for examples. examples exponents exponents, or powers of a nu...
... living standard html5the definition of '<sub> and <sup>;' in that specification. recommendation ...
<template>: The Content Template element - HTML: Hypertext Markup Language
Web › HTML › Element › template
ed subsequently during runtime using javascript. think of a template as a content fragment that is being stored for subsequent use in the document. while the parser does process the contents of the <template> element while loading the page, it does so only to ensure that those contents are valid; the element's contents are not rendered, however. content categories metadata content, flow content, phrasing content, script-supporting element permitted content no restrictions tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts metadata content, phrasing content, or script-supporting elements. also allowed as a child of a <colgroup> element that does not have a span attribute. impli...
... dom interface htmltemplateelement attributes this element only includes the global attributes. however, the htmltemplateelement has a content property, which is a read-only documentfragment containing the dom subtree which the template represents. note that directly using the value of the content could lead to unexpected behavior, see avoiding documentfragment pitfall section below. examples first we start with the html portion of the example. <table id="producttable"> <thead> <tr> <td>upc_code</td> <td>product_name</td> </tr> </thead> <tbody> <!-- existing data could optionally be included here --> </tbody> </table> <template id="productrow"> <tr> <td class="record"></td> <td></td> </tr> </template> first, we have a table i...
... // the html template element is not supported. } the result is the original html table, with two new rows appended to it via javascript: table { background: #000; } table td { background: #fff; } avoiding documentfragment pitfall a documentfragment is not a valid target for various events, as such it is often preferable to clone or refer to the elements within it. ...
<time> - HTML: Hypertext Markup Language
Web › HTML › Element › time
the html <time> element represents a specific period in time. it may include the datetime attribute to translate dates into machine-readable format, allowing for better search engine results or custom features such as reminders. 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. 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, b...
...parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmltimeelement attributes like all other html elements, this element supports the global attributes. datetime this attribute indicates the time and/or date of the element and must be in one of the formats described below. usage notes this element is for presenting dates and times in a machine readable format. for example, this can help a user agent offer to add an event to a user's calendar. this element should not be used for dates prior to the introduction of the gregorian calendar (due to complications in calculating those dates). the datetime value (the machine-readable value of the datetime) is the valu...
...le format. for example, this can help a user agent offer to add an event to a user's calendar. this element should not be used for dates prior to the introduction of the gregorian calendar (due to complications in calculating those dates). the datetime value (the machine-readable value of the datetime) is the value of the element’s datetime attribute, which must be in the proper format (see below). if the element does not have a datetime attribute, it must not have any element descendants, and the datetime value is the element’s child text content. valid datetime values a valid year string 2011 a valid month string 2011-11 a valid date string 2011-11-18 a valid yearless date string 11-18 a valid week string 2011-w47 a valid time string 14:54 14:54:39 14:54:39.929 a val...
<tt>: The Teletype Text element (obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › tt
pace type, or the <pre> tag for content that should be presented as a separate block. if none of the semantic elements are appropriate for your use case (for example, if you simply need to show some content in a non-proportional font), you should consider using the <span> element, styling it as desired using css. the font-family property is a good place to start. content categories flow content, phrasing content, palpable content. permitted content phrasing 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 ...
...ne, 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. ...
...you can override this using css by creating a rule using the tt selector, as seen in the example overriding the default font above. user-configured c...
contenteditable - HTML: Hypertext Markup Language
false, which indicates that the element is not editable. ...
... false, which indicates that the element is not editable. if the attribute is given without a value, like <label contenteditable>example label</label>, its value is treated as an empty string. ...
... element is editable. false, which indicates that the element is not editable. if the attribute is given without a value, like <label contenteditable>example label</label>, its value is treated as an empty string. if this attribute is missing or its value is invalid, its value is inherited from its parent element: so the element is editable if its parent is editable. note that although its allowed values include true and false, this attribute is an enumerated one and not a boolean one. you can set the color used to draw the text insertion caret with the css caret-color property. specifications specification status comment html living standardthe definition of 'contenteditable' in that specification. living standard no change from latest snapshot, html...
Choosing between www and non-www URLs - HTTP
this domain name is hosted on a server where the document resides. a server isn't necessarily a physical machine: several servers can reside on the same physical machine. or, one server can be handled by several machines, cooperating to produce the answer or balancing the load of the requests between them. ...
...if you're using relative urls in your website) and always sharing links (by email/social networks, etc.) to the same domain. no, you can have two. what is important is that you are coherent and consistent with which one is the official domain. this official domain is called the canonical name. all your absolute links should use it. but even so, you can still have the other domain working: http allows two techniques so that it is clear for your users, or search engines, which domain is the canonical one, while still allowing the non-canonical domain to work and provide the expected pages. so, choose one of your domains as your canonical one! there are two techniques below to allow the non-canonical domain to work still. techniques for canonical urls there are different ways to choose whic...
...nical"> it is possible to add a special html <link> element to a page to indicate what the canonical address of a page is. this has no impact on the human reader of the page, but tells search engine crawlers where the page actually lives. this way, search engines don't index the same page several times, potentially leading to it being considered as duplicate content or spam, and even removing or lowering your page from the search engine result pages. when adding such a tag, you serve the same content for both domains, telling search engines which url is canonical. in the previous example, http://www.example.org/whaddup would serve the same content as http://example.org/whaddup, but with an additional <link> element in the head: <link href="http://example.org/whaddup" rel="canonical"> unli...
Basics of HTTP - HTTP
on top of these basic concepts, numerous extensions have been developed over the years that add updated functionality and semantics with new http methods or headers. articles overview of http describes what http is and its role in web architecture, including its position in the protocol stack. evolution of http http was created in the early 1990s and has been extended several times. ...
...this can be changed with the alt-svc header. mime types since http/1.0, different types of content can be transmitted. this article explains how this is accomplished using the content-type header and the mime standard. choosing between www and non-www urls this article provides guidance on how to choose whether to use a www-prefixed domain or not, along with the consequences of that choice. flow of an http session this fundamental article describes a typical http session: what happens under the hood when you click on a link in your browser. http messages http messages transmitted during requests or responses have a very clear structure. this introductory article describes this structure, its purpose, and its possibilities. frame and message structure in http/2 http/2 encapsulates an...
...ary frame. this article explains the frame structure, its purpose, and the way it's encoded. connection management in http/1.x http/1.1 was the first version of http to support persistent connection and pipelining. this article explains both concepts. connection management in http/2 http/2 completely revisited how connections are created and maintained. this article explains how http frames allow multiplexing and solve the 'head-of-line' blocking problem of former http versions. content negotiation http introduces a set of headers, starting with accept as a way for a browser to announce the format, language, or encoding it prefers. this article explains how this advertisement happens, how the server is expected to react, and how it chooses the most adequate response. ...
HTTP caching - HTTP
Web › HTTP › Caching
se. error responses: a 404 (not found) result page. incomplete results: a 206 (partial content) response. responses other than get if something suitable for use as a cache key is defined. a cache entry might also consist of multiple stored responses differentiated by a secondary key, if the request is target of content negotiation. for more details see the information about the vary header below. controlling caching the cache-control header the cache-control http/1.1 general-header field is used to specify directives for caching mechanisms in both requests and responses. use this header to define your caching policies with the variety of directives it provides. no caching the cache should not store anything about the client request or server response. a request is sent to the server...
...-age=<seconds>" which is the maximum amount of time a resource will be considered fresh. contrary to expires, this directive is relative to the time of the request. for the files in the application that will not change, you can usually add aggressive caching. this includes static files such as images, css files and javascript files, for example. for more details, see also the freshness section below. cache-control: max-age=31536000 validation when using the "must-revalidate" directive, the cache must verify the status of the stale resources before using it and expired ones should not be used. for more details, see the validation section below. cache-control: must-revalidate the pragma header pragma is a http/1.0 header, it is not specified for http responses and is therefore not a reli...
...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 - currentage where responsetime is the time at which the response was received according to the browser. revved resources the more we use cached resources, the better the responsiveness and the performance of a web site will be. to optimize this, good practices recommend to set expiration times as far in the future as possible. this is poss...
Compression in HTTP - HTTP
over the years, algorithms also got more efficient, and new ones are supported by clients and servers. in practice, web developers don't need to implement compression mechanisms, both browsers and servers have it implemented already, but they have to be sure that the server is configured adequately. ...
...usually more efficient than loss-less ones. as compression works better on a specific kind of files, it usually provides nothing to compress them a second time. in fact, this is often counter productive as the cost of the overhead (algorithms usually need a dictionary that add to the initial size) can be higher than the extra gain in compression resulting in a larger file. do not use the two following techniques for files in a compressed format. end-to-end compression for compression, end-to-end compression is where the largest performance improvements of web sites reside. end-to-end compression refers to a compression of the body of a message that is done by the server and will last unchanged until it reaches the client. whatever the intermediate nodes are, they leave the body untouched...
...for end-to-end compression: the node transmitting the request advertizes its will using the te header and the other node chooses the adequate method, applies it, and indicates its choice with the transfer-encoding header. in practice, hop-by-hop compression is transparent for the server and the client, and is rarely used. te and transfer-encoding are mostly used to send a response by chunks, allowing to start transmitting a resource without knowing its length. note that using transfer-encoding and compression at the hop level is so rare that most servers, like apache, nginx, or iis, have no easy way to configure it. such configuration usually happens at the proxy level. ...
Configuring servers for Ogg media - HTTP
this guide covers a few server configuration changes that may be necessary for your web server to correctly serve ogg media files. this information may also be useful if you encounter other media types your server isn't already configured to recognize. serve media with the correct mime type *.ogg and *.ogv files containing video (possibly with an audio track as well, of course), should be served with the video/ogg mime type. *.oga and *.ogg files containing only audio should be served with the audio/ogg mime type. ...
...only audio should be served with the audio/ogg mime type. if you don't know whether the ogg file contains audio or video, you can serve it with the mime type application/ogg, and the browser will treat it as a video file. most servers don't by default serve ogg media with the correct mime types, so you'll likely need to add the appropriate configuration for this. for apache, you can add the following to your configuration: addtype audio/ogg .oga addtype video/ogg .ogv addtype application/ogg .ogg you can find specific information about possible media file types and the codecs used within them in our comprehensive guide to media types and formats on the web. in particular, the article on media container formats will be especially helpful when configuring serers to host media properly. h...
...orts http compression (gzip/deflate) using the accept-encoding: gzip,deflate header when requesting media files. your server should be configured to not do so. the data in media files is already compressed, so you won't get any real benefit from compression, and the use of compression makes it impossible for the browser to properly seek the video or determine its duration. another probelm with allowing http compression for media streaming: apache servers don't send the content-length response header if gzip encoding is used. getting the duration of ogg media you can use the oggz-info tool to get the media duration; this tool is included with the oggz-tools package. the output from oggz-info looks like this: $ oggz-info /g/media/bruce_vs_ironman.ogv content-duration: 00:01:00.046 skele...
Cache-Control - HTTP
the cache-control http header holds directives (instructions) for caching in both requests and responses. a given directive in a request does not mean the same directive should be in the response. header type general header forbidden header name no cors-safelisted response header yes syntax caching directives have the following rules to be valid: case-insensitive, but lowercase is recommended. 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-contro...
...ification. 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 caching to disable caching of a resource,...
...-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 caching to disable caching of a resource, you can send the following response header: good: cache-control: no-store bad: cache-control: private,no-cache,no-store,max-age=0,must-revalidate,pre-check=0,post-check=0 caching static assets for the files in the application that will not change, you can usually add aggressive caching by sending the response header below. this includes static files that are served by the application such as images, css...
Feature-Policy: gyroscope - HTTP
the http feature-policy header gyroscope directive controls whether the current document is allowed to gather information about the orientation of the device through the gyroscope interface. syntax feature-policy: gyroscope <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. '...
...l be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. ...
...re is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. features are each defined to have a default allowlist, which is one of: *: the feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not allowed in cross-origin documents in nested browsing contexts. 'none': the feature is disabled in top-leve...
Feature-Policy: layout-animations - HTTP
the http feature-policy header layout-animations directive controls whether the current document is allowed to show layout animations. syntax feature-policy: layout-animations <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and ...
...l be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. ...
...re is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. features are each defined to have a default allowlist, which is one of: *: the feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not allowed in cross-origin documents in nested browsing contexts. 'none': the feature is disabled in top-leve...
Feature-Policy: legacy-image-formats - HTTP
the http feature-policy header legacy-image-formats directive controls whether the current document is allowed to display images in legacy formats. syntax feature-policy: legacy-image-formats <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled i...
...l be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. ...
...re is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. features are each defined to have a default allowlist, which is one of: *: the feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not allowed in cross-origin documents in nested browsing contexts. 'none': the feature is disabled in top-leve...
Feature-Policy: oversized-images - HTTP
the http feature-policy header oversized-images directive controls whether the current document is allowed to download and display large images. syntax feature-policy: oversized-images <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-l...
...l be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. ...
...re is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. features are each defined to have a default allowlist, which is one of: *: the feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not allowed in cross-origin documents in nested browsing contexts. 'none': the feature is disabled in top-leve...
Feature-Policy: unoptimized-images - HTTP
the http feature-policy header unoptimized-images directive controls whether the current document is allowed to download and display unoptimized images. syntax feature-policy: unoptimized-images <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disable...
...l be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. ...
...re is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. features are each defined to have a default allowlist, which is one of: *: the feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not allowed in cross-origin documents in nested browsing contexts. 'none': the feature is disabled in top-leve...
Feature-Policy: vibrate - HTTP
the http feature-policy header vibrate directive controls whether the current document is allowed to trigger device vibrations via navigator.vibrate() method of vibration api. syntax feature-policy: vibrate <allowlist>; <vibrate> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the featur...
...l be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. ...
...re is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self' and 'src' may be used with one or more origins. features are each defined to have a default allowlist, which is one of: *: the feature is allowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is allowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not allowed in cross-origin documents in nested browsing contexts. 'none': the feature is disabled in top-leve...
SameSite cookies - HTTP
the samesite attribute of the set-cookie http response header allows you to declare if your cookie should be restricted to a first-party or same-site context. values the samesite attribute accepts three values: lax cookies are allowed to be sent with top-level navigations and will be sent along with get request initiated by third party website. this is the default value in modern browsers. strict cookies will only be sent in a first-party context and not be sent along with requests initiated by third party websites. none cookies will be sent in all contexts, i.e sending cross-origin is allowed. none used to be the default value, but recent browser versions made lax the default value to have reasonably robust defense against some classes of cross-site request forgery (csrf) attacks.
... along with requests initiated by third party websites. none cookies will be sent in all contexts, i.e sending cross-origin is allowed. none used to be the default value, but recent browser versions made lax the default value to have reasonably robust defense against some classes of cross-site request forgery (csrf) attacks. none requires the secure attribute in latest browser versions. see below for more information. fixing common warnings samesite=none requires secure the following warning might appear in your console: some cookies are misusing the “samesite“ attribute, so it won’t work as expected. cookie “mycookie” rejected because it has the “samesite=none” attribute but is missing the “secure” attribute. the warning appears because any cookie that requests ...
...site=none cookies. set-cookie: flavor=choco; samesite=none; secure a secure cookie is only sent to the server with an encrypted request over the https protocol. note that insecure sites (http:) can't set cookies with the secure directive. cookies without samesite default to samesite=lax recent versions of modern browsers provide a more secure default for samesite to your cookies and so the following message might appear in your console: some cookies are misusing the “samesite“ attribute, so it won’t work as expected. cookie “mycookie” has “samesite” policy set to “lax” because it is missing a “samesite” attribute, and “samesite=lax” is the default value for this attribute. the warning appears because the samesite policy for a cookie has not specified explici...
X-Frame-Options - HTTP
sites can use this to avoid click-jacking attacks, by ensuring that their content is not embedded into other sites. the added security is provided only if the user accessing the document is using a browser that supports x-frame-options. note: the content-security-policy http header has a frame-ancestors directive which obsoletes this header for supporting browsers. ...
...ameorigin the page can only be displayed in a frame on the same origin as the page itself. the spec leaves it up to browser vendors to decide whether this option applies to the top level, the parent, or the whole chain, although it is argued that the option is not very useful unless all ancestors are also in the same origin (see bug 725490). also see browser compatibility for support details. allow-from uri this is an obsolete directive that no longer works in modern browsers. don't use it. in supporting legacy browsers, a page can be displayed in a frame only on the specified origin uri. note that in the legacy firefox implementation this still suffered from the same problem as sameorigin did — it doesn't check the frame ancestors to see if they are in the same origin. the content-sec...
...to see if they are in the same origin. the content-security-policy http header has a frame-ancestors directive which you can use instead. examples note: setting x-frame-options inside the <meta> element is useless! for instance, <meta http-equiv="x-frame-options" content="deny"> has no effect. do not use it! x-frame-options works only by setting through the http header, as in the examples below. configuring apache to configure apache to send the x-frame-options header for all pages, add this to your site's configuration: header always set x-frame-options "sameorigin" to configure apache to set the x-frame-options deny, add this to your site's configuration: header set x-frame-options "deny" configuring nginx to configure nginx to send the x-frame-options header, add this eithe...
Protocol upgrade mechanism - HTTP
ade an already established connection to a different protocol, using the upgrade header field. this mechanism is optional; it cannot be used to insist on a protocol change. implementations can choose not to take advantage of an upgrade even if they support the new protocol, and in practice, this mechanism is used mostly to bootstrap a websockets connection. note also that http/2 explicitly disallows the use of this mechanism; it is specific to http/1.1. upgrading http/1.1 connections the upgrade header field is used by clients to invite the server to switch to one of the listed protocols, in descending preference order. because upgrade is a hop-by-hop header, it also needs to be listed in the connection header field. this means that a typical request that includes upgrade would look some...
...ng preference order. because upgrade is a hop-by-hop header, it also needs to be listed in the connection header field. this means that a typical request that includes upgrade would look something like: get /index.html http/1.1 host: www.example.com connection: upgrade upgrade: example/1, foo/2 other headers may be required depending on the requested protocol; for example, websocket upgrades allow additional headers to configure details about the websocket connection as well as to offer a degree of security in opening the connection. see upgrading to a websocket connection for more details. if the server 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 cann...
...ling the handshaking and upgrade process for you. you can also use the "wss://" url scheme to open a secure websocket connection. if you need to create a websocket connection from scratch, you'll have to handle the handshaking process yourself. after creating the initial http/1.1 session, you need to request the upgrade by adding to a standard request the upgrade and connection headers, as follows: connection: upgrade upgrade: websocket websocket-specific headers the following headers are involved in the websocket upgrade process. other than the upgrade and connection headers, the rest are generally optional or handled for you by the browser and server when they're talking to each other. sec-websocket-extensions specifies one or more protocol-level websocket extensions to ask the ser...
HTTP range requests - HTTP
partial requests are useful for large media or downloading files with pause and resume functions, for example. checking if a server supports partial requests if the accept-ranges is present in http responses (and its value isn't "none"), the server supports range requests. you can check this by issuing a head request with curl, for example. curl -i http://i.imgur.com/z4d4kwk.jpg http/1.1 200 ok ... accept-ranges: bytes content-length: 146515 in this response, accept-ranges: bytes indicates that bytes can be used as unit to define a range. here the content-length header is also useful as it indicates the full size of the image to retrieve. ...
...with the 206 partial content status: http/1.1 206 partial content content-range: bytes 0-1023/146515 content-length: 1024 ... (binary content) the content-length header now indicates the size of the requested range (and not the full size of the image). the content-range response header indicates where in the full resource this partial message belongs. multipart ranges the range header also allows you to get multiple ranges at once in a multipart document. the ranges are separated by a comma. curl http://www.example.com -i -h "range: bytes=0-50, 100-150" the server responses with the 206 partial content status and a content-type: multipart/byteranges; boundary=3d6b6a416f9b5 header, indicating that a multipart byterange follows. each part contains its own content-type and content-range f...
...nge request that is out of bounds (none of the range values overlap the extent of the resource, i.e first-byte-pos of all ranges is greater than the resource length), the server responds with a 416 requested range not satisfiable status. in case of no support of range requests, 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...
HTTP response status codes - HTTP
Web › HTTP › Status
you can find an updated specification in rfc 7231. ...
... requested resource. in the browser, this means the url is not recognized. in an api, this can also mean that the endpoint is valid but the resource itself does not exist. servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. this response code is probably the most 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 ...
...ver refuses the attempt to brew coffee with a teapot. 421 misdirected request the request was directed at a server that is not able to produce a response. this can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request uri. 422 unprocessable entity (webdav) the request was well-formed but was unable to be followed due to semantic errors. 423 locked (webdav) the resource that is being accessed is locked. 424 failed dependency (webdav) the request failed due to failure of a previous request. 425 too early indicates that the server is unwilling to risk processing a request that might be replayed. 426 upgrade required the server refuses to perform the request using the current protocol but might be w...
Concurrency model and the event loop - JavaScript
modern javascript engines implement and heavily optimize the described semantics. visual representation stack function calls form a stack of frames. ...
...stance, where if a function runs in a thread, it may be stopped at any point by the runtime system to run some other code in another thread. a downside of this model is that if a message takes too long to complete, the web application is unable to process user interactions like click or scroll. the browser mitigates this with the "a script is taking too long to run" dialog. a good practice to follow is to make message processing short and if possible cut down one message into several messages. adding messages in web browsers, 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 ca...
...te().getseconds() - s >= 2) { console.log("good, looped for 2 seconds") break; } } zero delays zero delay doesn't actually mean the call back 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. (fun...
Iterators and generators - JavaScript
value in the associated array in sequence. while it is easy to imagine that all iterators could be expressed as arrays, this is not true. arrays must be allocated in their entirety, but iterators are consumed only as necessary. because of this, iterators can express sequences of unlimited size, such as the range of integers between 0 and infinity. here is an example which can do just that. it allows creation of a simple range iterator which defines a sequence of integers from start (inclusive) to end (exclusive) spaced step apart. its final return value is the size of the sequence it created, tracked by the variable iterationcount. function makerangeiterator(start = 0, end = infinity, step = 1) { let nextindex = start; let iterationcount = 0; const rangeiterator = { nex...
...at 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 iterator, called a generator. when a value is consumed by calling the generator's next method, the generator function executes u...
... expect iterables. for example: the for-of loops, yield*. for (let value of ['a', 'b', 'c']) { console.log(value); } // "a" // "b" // "c" [...'abc']; // ["a", "b", "c"] function* gen() { yield* ['a', 'b', 'c']; } gen().next(); // { value: "a", done: false } [a, b, c] = new set(['a', 'b', 'c']); a; // "a" advanced generators generators compute their yielded values on demand, which allows them to efficiently represent sequences that are expensive to compute (or even infinite sequences, as demonstrated above). the next() method also accepts a value, which can be used to modify the internal state of the generator. a value passed to next() will be received by yield . note: a value passed to the first invocation of next() is always ignored. here is the fibonacci generator using ...
Meta programming - JavaScript
« previousnext » starting with ecmascript 2015, javascript gains support for the proxy and reflect objects allowing you to intercept and define custom behavior for fundamental language operations (e.g. property lookup, assignment, enumeration, function invocation, etc). with the help of these two objects you are able to program at the meta level of javascript. proxies introduced in ecmascript 6, proxy objects allow you to intercept certain operations and to implement custom behaviors. for example, getting a property on an object: let handler = { get: function(target, name) { return name in target? target[name] : 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 ob...
...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) regarding object non-e...
...it is often used as storage backend for the proxy. invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target. invariants semantics that remain unchanged when implementing custom operations are called invariants. if you violate the invariants of a handler, a typeerror will be thrown. handlers and traps the following table summarizes the available traps available to proxy objects. see the reference pages for detailed explanations and examples. handler / trap interceptions invariants handler.getprototypeof() object.getprototypeof() reflect.getprototypeof() __proto__ object.prototype.isprototypeof() instanceof getprototypeof method must return an ...
Warning: 08/09 is not a legal ECMA-262 octal constant - JavaScript
is not a legal ecma-262 octal constant" occurs when 08 or 09 number literals are used. they can't be interpreted as an octal number. message warning: syntaxerror: 08 is not a legal ecma-262 octal constant. warning: syntaxerror: 09 is not a legal ecma-262 octal constant. error type warning. javascript execution won't be halted. ...
...o (0) followed by another decimal digit, but if all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. because this is not the case with 08 and 09, javascript warns about it. note that octal literals and octal escape sequences are deprecated and will present an additional deprecation warning. with ecmascript 6 and later, the syntax uses a leading zero followed by a lowercase or uppercase latin letter "o" (0o or 0o). see the page about lexical grammar for more information. ...
...6 and later, the syntax uses a leading zero followed by a lowercase or uppercase latin letter "o" (0o or 0o). see the page about lexical grammar for more information. ...
Default parameters - JavaScript
default function parameters allow named parameters to be initialized with default values if no value or undefined is passed. 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 function [name]([param1[ = defaultvalue1 ][, ..., paramn[ = defaultvaluen ]]]) { statements } description in javascript, function parameters default to undefined. however, it's often useful to set a different default value. this is where default parameters can help. ...
...ltvalue1 ][, ..., paramn[ = defaultvaluen ]]]) { statements } description in javascript, function parameters default to undefined. however, it's often useful to set a different default value. this is where default parameters can help. in the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined. in the following example, if no value is provided for b when multiply is called, b's value would be undefined when evaluating a * b and multiply would return nan. function multiply(a, b) { return a * b } multiply(5, 2) // 10 multiply(5) // nan ! to guard against this, something like the second line would be used, where b is set to 1 if multiply is called with only one argument: function multiply(a,...
...tion body. this means that functions and variables declared in the function body cannot be referred to from default value parameter initializers; attempting to do so throws a run-time referenceerror. it also means that variables declared inside the function body using var will mask parameters of the same name, instead of the usual behavior of duplicate var declarations having no effect. the following function will throw a referenceerror when invoked, because the default parameter value does not have access to the child scope of the function body: function f(a = go()) { // throws a `referenceerror` when `f` is invoked. function go() { return ':p' } } ...and this function will print undefined because variable var a is hoisted only to the top of the scope created for the function body (a...
Array.prototype.every() - JavaScript
are not visited. every acts like the "for all" quantifier in mathematics. in particular, for an empty array, it returns true. (it is vacuously true that all elements of the empty set satisfy any 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(ca...
... // and argument list containing kvalue, k, and o. if(t) testresult = callbackfn.call(t, kvalue, k, o); else testresult = callbackfn(kvalue,k,o) // iii. if toboolean(testresult) is false, return false. if (!testresult) { return false; } } k++; } return true; }; } examples testing size of all array elements the following example tests whether all elements in the array are bigger than 10. function isbigenough(element, index, array) { return element >= 10; } [12, 5, 8, 130, 44].every(isbigenough); // false [12, 54, 18, 130, 44].every(isbigenough); // true using arrow functions arrow functions provide a shorter syntax for the same test. [12, 5, 8, 130, 44].every(x => x >= 10); // false [12, 54, 18, 130...
..., array) { return element >= 10; } [12, 5, 8, 130, 44].every(isbigenough); // false [12, 54, 18, 130, 44].every(isbigenough); // true using arrow functions arrow functions provide a shorter syntax for the same test. [12, 5, 8, 130, 44].every(x => x >= 10); // false [12, 54, 18, 130, 44].every(x => x >= 10); // true​ affecting initial array (modifying, appending, and deleting) the following examples tests the behaviour of the every method when the array is modified. // --------------- // modifying items // --------------- let arr = [1, 2, 3, 4]; arr.every( (elem, index, arr) => { arr[index+1] -= 1 console.log(`[${arr}][${index}] -> ${elem}`) return elem < 2 }) // loop runs for 3 iterations, but would // have run 2 iterations without any modification // // 1st iteration: [...
Array.prototype.find() - JavaScript
et-unvisited element of the array is changed by callback, its value passed to the callback will be the value at the time find visits that element's index. elements that are deleted are still visited. 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 array.prototype.find with the following snippet: // https://tc39.github.io/ecma262/#sec-array.prototype.find if (!array.prototype.find) { object.defineproperty(array.prototype, 'find', { value: function(predicate) { // 1. let o be ? toobject(this value). if (this == null) { throw typeerror('"this" is null or not defined'); } var o = object(this); // 2. let len be ? tolength(? get(o, "le...
...(inventory.find(ischerries)); // { name: 'cherries', quantity: 5 } using arrow function and destructuring const inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5} ]; const result = inventory.find( ({ name }) => name === 'cherries' ); console.log(result) // { name: 'cherries', quantity: 5 } find a prime number in an array the following example finds an element in the array that is a prime number (or returns undefined if there is no prime number): function isprime(element, index, array) { let start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } console.log([4, 6, 8, 12].find(isprime)); // undefined, not found console.log([4, 5, 8, 12].fin...
...t in the array that is a prime number (or returns undefined if there is no prime number): function isprime(element, index, array) { let start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } console.log([4, 6, 8, 12].find(isprime)); // undefined, not found console.log([4, 5, 8, 12].find(isprime)); // 5 the following examples show that nonexistent and deleted elements are visited, and that the value passed to the callback is their value when visited: // declare array with no elements at indexes 2, 3, and 4 const array = [0,1,,,,5,6]; // shows all indexes, not just those with assigned values array.find(function(value, index) { console.log('visited index ', index, ' with value ', value); }); // shows al...
Array.prototype.flatMap() - 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. ...
...ng processed in the array. arrayoptional the array map was called upon. thisargoptional value to use as this when executing callback. return value a new array with each element being the result of the callback function and flattened to a depth of 1. description see array.prototype.map() for a detailed description of the callback function. the flatmap method is identical to a map followed by a call to flat of depth 1. alternative reduce() and concat() var arr = [1, 2, 3, 4]; arr.flatmap(x => [x, x * 2]); // is equivalent to arr.reduce((acc, x) => acc.concat([x, x * 2]), []); // [1, 2, 2, 4, 3, 6, 4, 8] note, however, that this is inefficient and should be avoided for large arrays: in each iteration, it creates a new temporary array that must be garbage-collected, and it co...
...a"]; arr1.map(x => x.split(" ")); // [["it's","sunny","in"],[""],["california"]] arr1.flatmap(x => x.split(" ")); // ["it's","sunny","in", "", "california"] notice, the output list length can be different from the input list length. for adding and removing items during a map() flatmap can be used as a way to add and remove items (modify the number of items) during a map. in other words, it allows you to map many items to many items (by handling each input item separately), rather than always one-to-one. in this sense, it works like the opposite of filter. simply return a 1-element array to keep the item, a multiple-element array to add items, or a 0-element array to remove the item. // let's say we want to remove all the negative numbers // and split the odd numbers into an even number ...
Array.isArray() - JavaScript
e) 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. ...
...ascript 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. ...
...ction(arg) { return object.prototype.tostring.call(arg) === '[object array]'; }; } examples using array.isarray // all following calls return true array.isarray([]); array.isarray([1]); array.isarray(new array()); array.isarray(new array('a', 'b', 'c', 'd')); array.isarray(new array(3)); // little known fact: array.prototype itself is an array: array.isarray(array.prototype); // all following calls return false array.isarray(); array.isarray({}); array.isarray(null); array.isarray(undefined); array.isarray(17); array.isarray('array'); array.isarray(true); array.isarray(false); array.isarray(new uint8array(32)); array.isarray({ __proto__: array.prototype }); instanceof vs isarray when checking for array instance, array.isarray is preferred over instanceof because it works through...
Array.prototype.lastIndexOf() - JavaScript
f the element in the array; -1 if not found. description lastindexof compares searchelement to elements of the array using strict equality (the same method used by the ===, or triple-equals, operator). 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. 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. // production steps of ecma-262, edition 5, 15.4.4.15 // reference: http://es5.github.io/#x15.4.4.15 if (!
...} return -1; }; } again, note that this implementation aims for absolute compatibility with lastindexof in firefox and the spidermonkey javascript engine, including in several cases which are arguably edge cases. if you intend to use this in real-world applications, you may be able to calculate from with less complicated code if you ignore those cases. ...
... ignore those cases. examples using lastindexof the following example uses lastindexof to locate values in an array. var numbers = [2, 5, 9, 2]; numbers.lastindexof(2); // 3 numbers.lastindexof(7); // -1 numbers.lastindexof(2, 3); // 3 numbers.lastindexof(2, 2); // 0 numbers.lastindexof(2, -2); // 0 numbers.lastindexof(2, -1); // 3 finding all the occurrences of an element the following example uses lastindexof to find all the indices of an element in a given array, using push to add them to another array as they are found. var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd']; var element = 'a'; var idx = array.lastindexof(element); while (idx != -1) { indices.push(idx); idx = (idx > 0 ? array.lastindexof(element, idx - 1) : -1); } console.log(indices); // [4, 2...
Array.prototype.pop() - JavaScript
mbling arrays. objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. if you call pop() on an empty array, it returns undefined. array.prototype.shift() has similar behavior to pop, but applied to the first element in an array. ...
... numerical properties may not behave in any meaningful manner. if you call pop() on an empty array, it returns undefined. array.prototype.shift() has similar behavior to pop, but applied to the first element in an array. examples removing the last element of an array the following code creates the myfish array containing four elements, then removes its last element. var myfish = ['angel', 'clown', 'mandarin', 'sturgeon']; var popped = myfish.pop(); console.log(myfish); // ['angel', 'clown', 'mandarin' ] console.log(popped); // 'sturgeon' using apply( ) or call ( ) on array-like objects the following code creates the myfish array-like object containing four elements and a length parameter, then removes its last element and decrements the length parameter. var myfish = {0:'angel', 1...
... 'mandarin', 'sturgeon']; var popped = myfish.pop(); console.log(myfish); // ['angel', 'clown', 'mandarin' ] console.log(popped); // 'sturgeon' using apply( ) or call ( ) on array-like objects the following code creates the myfish array-like object containing four elements and a length parameter, then removes its last element and decrements the length parameter. var myfish = {0:'angel', 1:'clown', 2:'mandarin', 3:'sturgeon', length: 4}; var popped = array.prototype.pop.call(myfish); //same syntax for using apply( ) console.log(myfish); // {0:'angel', 1:'clown', 2:'mandarin', length: 3} console.log(popped); // 'sturgeon' specifications specification ecmascript (ecma-262)the definition of 'array.prototype.pop' in that specification. ...
Array.prototype.slice() - JavaScript
the original array will not be modified. the source for this interactive demo is stored in a github repository. if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.slice([start[, end]]) parameters start optional zero-based index at which to start extraction. a negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence. ...
...e third element through the second-to-last element in the sequence. if end is omitted, slice extracts through the end of the sequence (arr.length). if end is greater than the length of the sequence, slice extracts through to the end of the sequence (arr.length). return value a new array containing the extracted elements. description slice does not alter the original array. it returns a shallow copy of elements from the original array. elements of the original array are copied into the returned array as follows: for object references (and not the actual object), slice copies object references into the new array. both the original and new array refer to the same object. if a referenced object changes, the changes are visible to both the new and original arrays. for strings, numbers a...
...an in one array do not affect the other array. if a new element is added to either array, the other array is not affected. examples return a portion of an existing array let fruits = ['banana', 'orange', 'lemon', 'apple', 'mango'] let citrus = fruits.slice(1, 3) // fruits contains ['banana', 'orange', 'lemon', 'apple', 'mango'] // citrus contains ['orange','lemon'] using slice> in the following example, slice creates a new array, newcar, from mycar. both include a reference to the object myhonda. when the color of myhonda is changed to purple, both arrays reflect the change. // using slice, create newcar from mycar. let myhonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } } let mycar = [myhonda, 2, 'cherry condition', 'purchased 1997'] let newcar = mycar.slice(0,...
Array.prototype.some() - JavaScript
visiting callback will be the value at the time that some() visits that element's index. elements that are deleted are not visited. caution: calling this method on an empty array returns false for 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...
... function isbiggerthan10(element, index, array) { return element > 10; } [2, 5, 8, 1, 4].some(isbiggerthan10); // false [12, 5, 8, 1, 4].some(isbiggerthan10); // true testing array elements using arrow functions arrow functions provide a shorter syntax for the same test. [2, 5, 8, 1, 4].some(x => x > 10); // false [12, 5...
... ...
Date.parse() - JavaScript
ipt 2015). therefore date objects produced using those strings may represent different moments in time depending on the version of ecmascript supported unless the system is set with a local time zone of utc. this means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted. ...
...lues depending on the format of the string that is being converted. examples using date.parse() the following calls all return 1546300800000. the first according to es5 will imply utc time, and the others are specifying utc timezone via the iso date specification (z and +00:00) date.parse("2019-01-01") date.parse("2019-01-01t00:00:00.000z") date.parse("2019-01-01t00:00:00.000+00:00") the following call, which does not specify a time zone will be set to 2019-01-01 at 00:00:00 in the local timezone of the system. date.parse("2019-01-01t00:00:00") non-standard date strings this section contains implementation-specific behavior that can be inconsistent across implementations. ...
...0:00") the following call, which does not specify a time zone will be set to 2019-01-01 at 00:00:00 in the local timezone of the system. date.parse("2019-01-01t00:00:00") non-standard date strings this section contains implementation-specific behavior that can be inconsistent across implementations. if ipodate is an existing date object, it can be set to august 9, 1995 (local time) as follows: ipodate.settime(date.parse('aug 9, 1995')); some other examples of parsing non-standard date strings: date.parse('aug 9, 1995'); returns 807937200000 in time zone gmt-0300, and other values in other time zones, since the string does not specify a time zone and is not iso format, therefore the time zone defaults to local. date.parse('wed, 09 aug 1995 00:00:00 gmt'); returns 807926400000...
Date.prototype.toLocaleString() - JavaScript
stanceof rangeerror; } return false; } using locales this example shows some of the variations in localized date and time formats. ...
..., gmt" // sometimes even the us needs 24-hour time console.log(date.tolocalestring('en-us', { hour12: false })); // → "12/19/2012, 19:00:00" avoid comparing formatted date values to static values most of the time, the formatting returned by tolocalestring() is consistent. however, this might change in the future, and isn't guaranteed for all languages; output variations are by design, and allowed by the specification. most notably, the ie and edge browsers insert bidirectional 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 tolocalestring() to a static value: "1/1/2019, 01:00:00" === new date("2019-01-01t01:00:00z").tolocalestring("en-us"); // true in fire...
... specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tolocalestring' in that specification. ...
Date - JavaScript
cseconds() sets the seconds for a specified date according to universal time. date.prototype.setyear() sets the year (usually 2–3 digits) for a specified date according to local time. use setfullyear() instead. date.prototype.todatestring() returns the "date" portion of the date as a human-readable string like 'thu apr 12 2018'. date.prototype.toisostring() converts a date to a string following the iso 8601 extended format. date.prototype.tojson() returns a string representing the date using toisostring(). intended for use by json.stringify(). date.prototype.togmtstring() returns a string representing the date based on the gmt (utc) time zone. use toutcstring() instead. date.prototype.tolocaledatestring() returns a string with a locality sensitive representation of the date por...
...he object.prototype.tostring() method. date.prototype.totimestring() returns the "time" portion of the date as a human-readable string. date.prototype.toutcstring() converts a date to a string using the utc timezone. date.prototype.valueof() returns the primitive value of a date object. overrides the object.prototype.valueof() method. examples several ways to create a date object the following examples show several ways to create javascript dates: note: parsing of date strings with the date constructor (and date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. let today = new date() let birthday = new date('december 17, 1995 03:24:00') let birthday = new date('1995-12-17t03:24:00') let birthday = new date(1995, 11, 17) ...
... and 99 the date.prototype.setfullyear() and date.prototype.getfullyear() methods should be used. let date = new date(98, 1) // sun feb 01 1998 00:00:00 gmt+0000 (gmt) // deprecated method; 98 maps to 1998 here as well date.setyear(98) // sun feb 01 1998 00:00:00 gmt+0000 (gmt) date.setfullyear(98) // sat feb 01 0098 00:00:00 gmt+0000 (bst) calculating elapsed time the following examples show how to determine the elapsed time between two javascript dates in milliseconds. due to the differing lengths of days (due to daylight saving changeover), months, and years, expressing elapsed time in units greater than hours, minutes, and seconds requires addressing a number of issues, and should be thoroughly researched before being attempted. // using date objects let start =...
Function.name - JavaScript
let object = { // anonymous somemethod: function() {} }; object.somemethod.name = 'othermethod'; console.log(object.somemethod.name); // somemethod to change it, use object.defineproperty(). shorthand method names var o = { foo(){} }; o.foo.name; // "foo"; bound function names function.bi...
... when using get and set accessor properties, "get" or "set" will appear in the function name. let o = { get foo(){}, set foo(x){} }; var descriptor = object.getownpropertydescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; function names in classes you can use obj.constructor.name to check the "class" of an object (but be sure to read the warnings below): function foo() {} // es2015 syntax: class foo {} var fooinstance = new foo(); console.log(fooinstance.constructor.name); // logs "foo" warning: the script interpreter will set the built-in function.name property only if a function does not have an own property called name (see section 9.2.11 of the ecmascript2015 language specification). however, es2015 specifies the static keyword such t...
... 14.5.14.21.b + 12.2.6.9). therefore we can't obtain the class name for virtually any class with a static method property name(): class foo { constructor() {} static name() {} } with a static name() method foo.name no longer holds the actual class name but a reference to the name() function object. above class definition in es2015 syntax will behave in chrome or firefox similar to the following snippet in es5 syntax: function foo() {} object.defineproperty(foo, 'name', { writable: true }); foo.name = function() {}; trying to obtain the class of fooinstance via fooinstance.constructor.name won't give us the class name at all but a reference to the static class method. example: let fooinstance = new foo(); console.log(fooinstance.constructor.name); // logs function name() you may...
Intl.DisplayNames() constructor - JavaScript
ry. 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 intl.displaynames([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. ...
... the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax new intl.displaynames([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. ...
...possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. style the formatting style to use, the default is "long". "narrow" "short" "long" type the type to use, the default is "language". ...
Intl.NumberFormat() constructor - JavaScript
ry. 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 intl.numberformat([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. the following unicode extension key is allowed: nu the numbering system to be used. possible values include: "adlm", "ahom", "arab", "arabext", "bali", "beng", "bhks", "brah", "cakm", "cham", "deva", "diak", "fullwide", "gong", "gonm", "gujr", "guru", "hanidec", "hmng", "hmnp", "java", "kali", "khmr", "knda", "lana", "lanatham", "laoo", "latn", "lepc", "limb", "mathbold", "mathdbl", "mathmono", "math...
... "lepc", "limb", "mathbold", "mathdbl", "mathmono", "mathsanb", "mathsans", "mlym", "modi", "mong", "mroo", "mtei", "mymr", "mymrshan", "mymrtlng", "newa", "nkoo", "olck", "orya", "osma", "rohg", "saur", "segment", "shrd", "sind", "sinh", "sora", "sund", "takr", "talu", "tamldec", "telu", "thai", "tibt", "tirh", "vaii", "wara", "wcho". options optional an object with some or all of the following properties: compactdisplay only used when notation is "compact". takes either "short" (default) or "long". currency the currency to use in currency formatting. possible values are the iso 4217 currency codes, such as "usd" for the us dollar, "eur" for the euro, or "cny" for the chinese rmb — see the current currency & funds code list. there is no default value; if the style is "cu...
...e unit property must be provided. unitdisplay 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. the following properties fall into two groups: minimumintegerdigits, minimumfractiondigits, and maximumfractiondigits in one group, minimumsignificantdigits and maximumsignificantdigits in the other. if at least one property from the second group is defined, then the first group is ignored. minimumintegerdigits the minimum number of integer digits to use. possible values are from 1 to 21; the default...
Object.getOwnPropertyDescriptors() - JavaScript
re 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 property (data descriptors only). writable true if and only if the value associated with the property may be changed (data descriptors only). get a function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). set a function which serves as a setter for the property, or undefined if ...
...ves as a setter for the property, or undefined if there is no setter (accessor descriptors only). configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. ...
...e property may be deleted from the corresponding object. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. examples creating a shallow clone whereas the object.assign() method will only copy enumerable and own properties from a source object to a target object, you are able to use this method and object.create() for a shallow copy between two unknown objects: object.create( object.getprototypeof(obj), object.getownpropertydescriptors(obj) ); creating a subclass a typical way of creating a subclass is to define the subclass, set its prototype to an instance of the superclass, and then define properties on that instance. this can get awkward especially for getters and setters. instead, you can use this code to s...
Object.prototype.hasOwnProperty() - JavaScript
n 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. ...
... 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. ...
...t vs. inherited properties the following example differentiates between direct properties and properties inherited through the prototype chain: o = new object(); o.prop = 'exists'; o.hasownproperty('prop'); // returns true o.hasownproperty('tostring'); // returns false o.hasownproperty('hasownproperty'); // returns false iterating over the properties of an object the following example shows how to iterate over the properties of an object without executing on inherited properties. note that the for...in loop is already only iterating enumerable items, so one should not assume based on the lack of non-enumerable properties shown in the loop that hasownproperty itself is confined strictly to enumerable items (as with object.getownpropertynames()). var buz = { fog: '...
Object.prototype.__proto__ - JavaScript
the effects on the performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in obj.__proto__ = ... statements, but may extend to any code that has access to any object whose [[prototype]] has been altered. if you care about performance you should avoid setting the [[prototype]] of an object. instead, create a new object with the desired [[prototype]] using object.create(). ...
...pec, but modern browsers implemented it anyway. only recently was the __proto__ property standardized by the ecmascript 2015 specification for compatibility with web browsers, so it will be supported into the future. it is deprecated in favor of object.getprototypeof/reflect.getprototypeof and object.setprototypeof/reflect.setprototypeof (though still, setting the [[prototype]] of an object is a slow operation that should be avoided if performance is a concern). the __proto__ property can also be used in an object literal definition to set the object [[prototype]] on creation, as an alternative to object.create(). see: object initializer / literal syntax. description the __proto__ getter function exposes the value of the internal [[prototype]] of an object. for objects created using an obj...
..., and so on — including new constructors added as javascript evolves), this value is always fun.prototype. for objects created using new fun, where fun is a function defined in a script, this value is the value of fun.prototype. (that is, if the constructor didn't return an other object explicitly, or the fun.prototype has been reassigned since the instance was created.) the __proto__ setter allows the [[prototype]] of an object to be mutated. the object must be extensible according to object.isextensible(): if it is not, a typeerror is thrown. the value provided must be an object or null. providing any other value will do nothing. to understand how prototypes are used for inheritance, see guide article inheritance and the prototype chain. the __proto__ property is a simple accessor prop...
handler.get() - JavaScript
ndler.get() method is a trap for getting a property value. 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 const p = new proxy(target, { get: function(target, property, receiver) { } }); parameters the following parameters are passed to the get() method. this is bound to the handler. target the target object. property the name or symbol of the property to get. receiver either the proxy or an object that inherits from the proxy. return value the get() method can return any value. description the handler.get() method is a trap for getting a property value. interceptions this trap can in...
... receiver either the proxy or an object that inherits from the proxy. return value the get() method can return any value. description the handler.get() method is a trap for getting a property value. interceptions this trap can intercept these operations: property access: proxy[foo]and proxy.bar inherited property access: object.create(proxy)[foo] reflect.get() invariants if the following invariants are violated, the proxy will throw a typeerror: the value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. the value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property ...
... must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. the value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has undefined as its [[get]] attribute. examples trap for getting a property value the following code traps getting a property value. const p = new proxy({}, { get: function(target, property, receiver) { console.log('called: ' + property); return 10; } }); console.log(p.a); // "called: a" // 10 the following code violates an invariant. const obj = {}; object.defineproperty(obj, 'a', { configurable: false, enumerable: false, value: 10, writable: f...
handler.has() - JavaScript
the handler.has() method is a trap for the in operator. 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 const p = new proxy(target, { has: function(target, prop) { } }); parameters the following parameters are passed to has() method. this is bound to the handler. target the target object. prop the name or symbol of the property to check for existence. return value the has() method must return a boolean value. description the handler.has() method is a trap for the in operator. interceptions this trap can intercept these operations: property query: foo in proxy inherited property query...
... symbol of the property to check for existence. return value the has() method must return a boolean value. description the handler.has() method is a trap for the in operator. ...
...() invariants if the following invariants are violated, the proxy will throw a typeerror: a property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. a property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. examples trapping the in operator the following code traps the in operator. const p = new proxy({}, { has: function(target, prop) { console.log('called: ' + prop); return true; } }); console.log('a' in p); // "called: a" // true the following code violates an invariant. const obj = { a: 10 }; object.preventextensions(obj); const p = new proxy(obj, { has: function(target, prop) { return false; ...
handler.isExtensible() - JavaScript
he handler.isextensible() method is a trap for object.isextensible(). 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 const p = new proxy(target, { isextensible: function(target) { } }); parameters the following parameter is passed to the isextensible() method. this is bound to the handler. target the target object. return value the isextensible() method must return a boolean value. description the handler.isextensible() method is a trap for object.isextensible(). interceptions this trap can intercept these operations: object.isextensible() reflect.isextensible() invariants if the fo...
...ng parameter is passed to the isextensible() method. this is bound to the handler. target the target object. return value the isextensible() method must return a boolean value. description the handler.isextensible() method is a trap for object.isextensible(). interceptions this trap can intercept these operations: object.isextensible() reflect.isextensible() invariants if the following invariants are violated, the proxy will throw a typeerror: object.isextensible(proxy) must return the same value as object.isextensible(target). examples trapping of isextensible the following code traps object.isextensible(). const p = new proxy({}, { isextensible: function(target) { console.log('called'); return true; } }); console.log(object.isextensible(p)); // "called...
...error: object.isextensible(proxy) must return the same value as object.isextensible(target). examples trapping of isextensible the following code traps object.isextensible(). const p = new proxy({}, { isextensible: function(target) { console.log('called'); return true; } }); console.log(object.isextensible(p)); // "called" // true the following code violates the invariant. const p = new proxy({}, { isextensible: function(target) { return false; } }); object.isextensible(p); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[isextensible]]' in that specification. ...
handler.ownKeys() - JavaScript
the handler.ownkeys() method is a trap for reflect.ownkeys(). 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 const p = new proxy(target, { ownkeys: function(target) { } }); parameters the following parameter is passed to the ownkeys() method. this is bound to the handler. target the target object. return value the ownkeys() method must return an enumerable object. description the handler.ownkeys() method is a trap for reflect.ownkeys(). interceptions this trap can intercept these operations: object.getownpropertynames() object.getownpropertysymbols() object.keys() reflect.ownkeys() ...
...ys() method. this is bound to the handler. target the target object. return value the ownkeys() method must return an enumerable object. description the handler.ownkeys() method is a trap for reflect.ownkeys(). interceptions this trap can intercept these operations: object.getownpropertynames() object.getownpropertysymbols() object.keys() reflect.ownkeys() invariants if the following invariants are violated, the proxy will throw a typeerror: the result of ownkeys() must be an array. the type of each array element is either a string or a symbol. the result list must contain the keys of all non-configurable own properties of the target object. if the target object is not extensible, then the result list must contain all the keys of the own properties of the target obje...
... of ownkeys() must be an array. the type of each array element is either a string or a symbol. the result list must contain the keys of all non-configurable own properties of the target object. if the target object is not extensible, then the result list must contain all the keys of the own properties of the target object and no other values. examples trapping of getownpropertynames the following code traps object.getownpropertynames(). const p = new proxy({}, { ownkeys: function(target) { console.log('called'); return ['a', 'b', 'c']; } }); console.log(object.getownpropertynames(p)); // "called" // [ 'a', 'b', 'c' ] the following code violates an invariant. const obj = {}; object.defineproperty(obj, 'a', { configurable: fal...
handler.preventExtensions() - JavaScript
entextensions() method is a trap for object.preventextensions(). 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 const p = new proxy(target, { preventextensions: function(target) { } }); parameters the following parameter is passed to the preventextensions() method. this is bound to the handler. target the target object. return value the preventextensions() method must return a boolean value. description the handler.preventextensions() method is a trap for object.preventextensions(). interceptions this trap can intercept these operations: object.preventextensions() reflect.preventextens...
...preventextensions() method. this is bound to the handler. target the target object. return value the preventextensions() method must return a boolean value. description the handler.preventextensions() method is a trap for object.preventextensions(). interceptions this trap can intercept these operations: object.preventextensions() reflect.preventextensions() invariants if the following invariants are violated, the proxy will throw a typeerror: object.preventextensions(proxy) only returns true if object.isextensible(proxy) is false. examples trapping of preventextensions the following code traps object.preventextensions(). const p = new proxy({}, { preventextensions: function(target) { console.log('called'); object.preventextensions(target); return true;...
...t.isextensible(proxy) is false. examples trapping of preventextensions the following code traps object.preventextensions(). const p = new proxy({}, { preventextensions: function(target) { console.log('called'); object.preventextensions(target); return true; } }); console.log(object.preventextensions(p)); // "called" // false the following code violates the invariant. const p = new proxy({}, { preventextensions: function(target) { return true; } }); object.preventextensions(p); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[preventextensions]]' in that specification. ...
handler.set() - JavaScript
et() method is a trap for setting a property value. 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 const p = new proxy(target, { set: function(target, property, value, receiver) { } }); parameters the following parameters are passed to the set() method. this is bound to the handler. target the target object. property the name or symbol of the property to set. value the new value of the property to set. receiver the object to which the assignment was originally directed. this is usually the proxy itself. but a set() handler can also be called indirectly, via the prototype chain or variou...
... method returns false, and the assignment happened in strict-mode code, a typeerror will be thrown. description the handler.set() method is a trap for setting property value. interceptions this trap can intercept these operations: property assignment: proxy[foo] = bar and proxy.foo = bar inherited property assignment: object.create(proxy)[foo] = bar reflect.set() invariants if the following invariants are violated, the proxy will throw a typeerror: cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that h...
...orresponding target object property is a non-writable, non-configurable data property. cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has undefined as its [[set]] attribute. in strict mode, a false return value from the set() handler will throw a typeerror exception. examples trap setting of a property value the following code traps setting a property value. const p = new proxy({}, { set: function(target, prop, value, receiver) { target[prop] = value; console.log('property set: ' + prop + ' = ' + value); return true; } }) console.log('a' in p); // false p.a = 10; // "property set: a = 10" console.log('a' in p); // true console.log(p.a); // 10 specifications s...
RangeError - JavaScript
constructor rangeerror() creates a new rangeerror object. ...
... constructor rangeerror() creates a new rangeerror object. ...
... constructor rangeerror() creates a new rangeerror object. ...
RegExp() constructor - JavaScript
flags is a string that contains the flags to add. alternatively, if an object is supplied for the pattern, the flags string will replace any of that object's flags (and lastindex will be reset to 0) (as of es2015). if flags is not specified and a regular expressions object is supplied, that object's flags (and lastindex value) will be copied over. flags may contain any combination of the following characters: g (global match) find all matches rather than stopping after the first match. i (ignore case) if u flag is also enabled, use unicode case folding. m (multiline) treat beginning and end characters (^ and $) as working over multiple lines. in other words, match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole in...
...match) find all matches rather than stopping after the first match. i (ignore case) if u flag is also enabled, use unicode case folding. m (multiline) treat beginning and end characters (^ and $) as working over multiple lines. in other words, match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string. s ("dotall") allows . to match newlines. u (unicode) treat pattern as a sequence of unicode code points. (see also binary strings). y (sticky) matches only from the index indicated by the lastindex property of this regular expression in the target string. does not attempt to match from any later indexes. examples literal notation and constructor there are two ways to create a regexp object: a litera...
... string. does not attempt to match from any later indexes. examples literal notation and constructor there are two ways to create a regexp object: a literal notation and a constructor. the literal notation's parameters are enclosed between slashes and do not use quotation marks. the constructor function's parameters are not enclosed between slashes but do use quotation marks. the following three expressions create the same regular expression: /ab+c/i new regexp(/ab+c/, 'i') // literal notation new regexp('ab+c', 'i') // constructor the literal notation results in compilation of the regular expression when the expression is evaluated. use literal notation when the regular expression will remain constant. for example, if you use literal notation to construct a regular expressio...
RegExp.prototype.test() - JavaScript
which to match the regular expression. returns true if there is a match between the regular expression and the string str. otherwise, false. description use test() whenever you want to know whether a pattern is found in a string. test() returns a boolean, unlike the string.prototype.search() method (which returns the index of a match, or -1 if not found). to get more information (but with slower execution), use the exec() method. (this is similar to the string.prototype.match() method.) as with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match. examples using test() simple example that tests if "hello" is contained at the very beginning of a string, returning a boolean result. const ...
... as with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match. examples using test() simple example that tests if "hello" is contained at the very beginning of a string, returning a boolean result. ...
...() also advances the lastindex property.) further calls to test(str) will resume searching str starting from lastindex. the lastindex property will continue to increase each time test() returns true. note: as long as test() returns true, lastindex will not reset—even when testing a different string! when test() returns false, the calling regex's lastindex property will reset to 0. ...
String.prototype.replaceAll() - JavaScript
e called with a global regexp". substr a string that is to be replaced by newsubstr. it is treated as a literal string and is not interpreted as a regular expression. newsubstr (replacement) the string that replaces the substring specified by the specified regexp or substr parameter. a number of special replacement patterns are supported; see the "specifying a string as a parameter" section below. function (replacement) a function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr. the arguments supplied to this function are described in the "specifying a function as a parameter" section below. return value a new string, with all matches of a pattern replaced by a replacement. description this method does not change the calling...
...regexp or substr. the arguments supplied to this function are described in the "specifying a function as a parameter" section below. return value a new string, with all matches of a pattern replaced by a replacement. description this method does not change the calling string object. it simply returns a new string. specifying a string as a parameter the replacement string can include the following special replacement patterns: pattern inserts $$ inserts a "$". $& inserts the matched substring. $` inserts the portion of the string that precedes the matched substring. $' inserts the portion of the string that follows the matched substring. $n where n is a positive integer less than 100, inserts the nth parenthesi...
... be invoked after the match has been performed. the function's result (return value) will be used as the replacement string. (note: the above-mentioned special replacement patterns do not apply in this case.) note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. the arguments to the function are as follows: possible name supplied value match 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 ...
WebAssembly.Memory() constructor - JavaScript
ew memory object whose buffer property is a resizable arraybuffer or sharedarraybuffer that holds the raw bytes of memory accessed by a webassembly instance. a memory created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly. syntax new webassembly.memory(memorydescriptor); parameters memorydescriptor an object that can contain the following members: initial the initial size of the webassembly memory, in units of webassembly pages. maximum optional the maximum size the webassembly memory is allowed to grow to, in units of webassembly pages. when present, the maximum parameter acts as a hint to the engine to reserve memory up front. however, the engine may ignore or clamp this reservation request. unshared webassembly mem...
.... note: a webassembly page has a constant size of 65,536 bytes, i.e., 64kib. exceptions if memorydescriptor is not of type object, a typeerror is thrown. if maximum is specified and is smaller than initial, a rangeerror is thrown. examples creating a new memory instance there are two ways to get a webassembly.memory object. the first way is to construct it from javascript. ...
...it then stores some values in that memory, then exports a function and uses it to sum some values. ...
parseFloat() - JavaScript
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 converted to a number (it’s not any of the above characters), parsefloat returns nan. parsefloat can also parse and return infinity. parsefloat converts bigint syntax to numbers, losing p...
...ppens because the trailing n character is discarded. consider number(value) for stricter parsing, which converts to nan for arguments with invalid characters anywhere. parsefloat will parse non-string objects if they have a tostring or valueof method. the returned value is the same as if parsefloat had been called on the result of those methods. ...
...e same as if parsefloat had been called on the result of those methods. examples parsefloat returning a number the following examples all return 3.14: parsefloat(3.14); parsefloat('3.14'); parsefloat(' 3.14 '); parsefloat('314e-2'); parsefloat('0.0314e+2'); parsefloat('3.14some non-digit characters'); parsefloat({ tostring: function() { return "3.14" } }); parsefloat returning nan the following example returns nan: parsefloat('ff2'); parsefloat and bigint the following examples both return 900719925474099300, losing precision as the integer is too large to be represented as a float: parsefloat(900719925474099267n); parsefloat('900719925474099267n'); specifications specification ecmascript (ecma-262)the definition of 'parsefloat' in that specification. ...
Spread syntax (...) - 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. ...
...t lists, ... can be used anywhere in the array literal, and may be used more than once. copy an array const arr = [1, 2, 3]; const arr2 = [...arr]; // like arr.slice() arr2.push(4); // arr2 becomes [1, 2, 3, 4] // arr remains unaffected note: spread syntax effectively goes one level deep while copying an array. therefore, it may be unsuitable for copying multidimensional arrays, as the following example shows. (the same is true with object.assign() and spread syntax.) const a = [[1], [2], [3]]; const b = [...a]; b.shift().shift(); // 1 // oh no! now array 'a' is affected as well: a // [[], [2], [3]] a better way to concatenate arrays array.prototype.concat() is often used to concatenate an array to the end of an existing array. without spread syntax, this is done as: const...
...2 = [3, 4, 5]; arr1 = [...arr2, ...arr1]; // arr1 is now [3, 4, 5, 0, 1, 2] note: unlike unshift(), this creates a new arr1, and does not modify the original arr1 array in-place. spread in object literals the rest/spread properties for ecmascript proposal (es2018) added spread properties to object literals. it copies own enumerable properties from a provided object onto a new object. shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than object.assign(). const obj1 = { foo: 'bar', x: 42 }; const obj2 = { foo: 'baz', y: 13 }; const clonedobj = { ...obj1 }; // object { foo: "bar", x: 42 } const mergedobj = { ...obj1, ...obj2 }; // object { foo: "baz", x: 42, y: 13 } note that object.assign() triggers setters, whereas spread syntax do...
void operator - JavaScript
the void operator evaluates the given expression and then returns undefined. 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 void expression description this operator allows evaluating expressions that produce a value into places where an expression that evaluates to undefined is desired. the void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). in these cases, the global variable undefined can be used. it should be noted that the precedence of the void operator should be taken into account and that parentheses can help cla...
...t evaluates to undefined is desired. the void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). in these cases, the global variable undefined can be used. it should be noted that the precedence of the void operator should be taken into account and that parentheses can help clarify the resolution of the expression following the void operator: void 2 == '2'; // (void 2) == '2', returns false void (2 == '2'); // void (2 == '2'), returns undefined examples immediately invoked function expressions when using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration. void function iife() { console.log("executed!"); }()...
...ked function expressions when using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration. void function iife() { console.log("executed!"); }(); // output: "executed!" executing the above function without the void keyword will result in an uncaught syntaxerror. javascript uris when a browser follows a javascript: uri, it evaluates the code in the uri and then replaces the contents of the page with the returned value, unless the returned value is undefined. the void operator can be used to return undefined. for example: <a href="javascript:void(0);"> click here to do nothing </a> <a href="javascript:void(document.body.style.backgroundcolor='green');"> click here for green background </...
yield - JavaScript
syntax [rv] = yield [expression] expression optional defines the value to return from the generator function via the iterator protocol. if omitted, undefined is returned instead. rv optional retrieves the optional value passed to the generator's next() method to resume its execution. description the yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's caller. it can be thought of as a generator-based version of the return keyword. yield can only be called directly from the generator function that contains it. it cannot be called from nested functions or from callbacks. the yield keyword causes the call to the generator's next() method to return an iteratorresult object with two properties: ...
...alue property is the result of evaluating the yield expression, and done is false, indicating that the generator function has not fully completed. once paused on a yield expression, the generator's code execution remains paused until the generator's next() method is called. each time the generator's next() method is called, the generator resumes execution, and runs until it reaches one of the following: a yield, which causes the generator to once again pause and return the generator's new value. the next time next() is called, execution resumes with the statement immediately after the yield. throw is used to throw an exception from the generator. this halts execution of the generator entirely, and execution resumes in the caller (as is normally the case when an exception is thrown). the...
...d by the generator's current yield operation. between the generator's code path, its yield operators, and the ability to specify a new starting value by passing it to generator.prototype.next(), generators offer enormous power and control. unfortunately, next() is asymmetric, but that can’t be helped: it always sends a value to the currently suspended yield, but returns the operand of the following yield. examples using yield the following code is the declaration of an example generator function. function* countapplesales () { let salelist = [3, 7, 5] for (let i = 0; i < salelist.length; i++) { yield salelist[i] } } once a generator function is defined, it can be used by constructing an iterator as shown. let applestore = countapplesales() // generator { } console.log(a...
empty - JavaScript
hub 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 ; description the empty statement is a semicolon (;) indicating that no statement will be executed, even if javascript syntax requires one. ...
...ent is a semicolon (;) indicating that no statement will be executed, even if javascript syntax requires one. the opposite behavior, where you want multiple statements, but javascript only allows a single one, is possible using a block statement, which combines several statements into a single one. examples empty loop body the empty statement is sometimes used with loop statements. ...
...ith loop statements. see the following example with an empty loop body: let arr = [1, 2, 3]; // assign all array values to 0 for (let i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ; console.log(arr); // [0, 0, 0] unintentional usage it is a good idea to comment intentional use of the empty statement, as it is not really obvious to distinguish from a normal semicolon. in the following example, the usage is probably not intentional: if (condition); // caution, this "if" does nothing! killtheuniverse() // so this always gets executed!!! in the next example, an if...else statement without curly braces ({}) is used. if three is true, nothing will happen, four does not matter, and also the launchrocket() function in the else case will not be executed. if (one) d...
for...of - JavaScript
iterable) { console.log(value); } // 1 // 2 // 3 iterating over the arguments object you can iterate over the arguments object to examine all of the parameters passed into a javascript function: (function() { for (const argument of arguments) { console.log(argument); } })(1, 2, 3); // 1 // 2 // 3 iterating over a dom collection iterating over dom collections like nodelist: the following example adds a read class to paragraphs that are direct descendants of an article: // note: this will only work in platforms that have // implemented nodelist.prototype[symbol.iterator] const articleparagraphs = document.queryselectorall('article > p'); for (const paragraph of articleparagraphs) { paragraph.classlist.add('read'); } closing iterators in for...of loops, abrupt iteration t...
...t be re-used, even if the for...of loop is terminated early, for example via the break keyword. 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) { console.log(o); // never called. } iterating over other iterable objects you can also iterate over an object that explicitly implements the iterable protocol: const iterable = { [symbol.iterator]() { return { i: 0, next() { if (this.i < 3) { return { value: this.i++, done: false }; } return { ...
...lue); } // 0 // 1 // 2 difference between for...of and for...in both for...in and for...of statements iterate over something. the main difference between them is in what they iterate over. the for...in statement iterates over the enumerable properties of an object, in an arbitrary order. the for...of statement iterates over values that the iterable object defines to be iterated over. the following example shows the difference between a for...of loop and a for...in loop when used with an array. object.prototype.objcustom = function() {}; array.prototype.arrcustom = function() {}; const iterable = [3, 5, 7]; iterable.foo = 'hello'; for (const i in iterable) { console.log(i); // logs 0, 1, 2, "foo", "arrcustom", "objcustom" } for (const i in iterable) { if (iterable.hasownproperty(...
import.meta - JavaScript
import.meta object. console.log(import.meta); // { url: "file:///home/user/my-module.js" } it returns an object with a url property indicating the base url of the module. this will either be the url from which the script was obtained, for external scripts, or the document base url of the containing document, for inline scripts. ...
...or #). ...
...or #). ...
let - JavaScript
send us a pull request. syntax let var1 [= value1] [, var2 [= value2]] [, ..., varn [= valuen]; parameters var1, var2, …, varn the names of the variable or variables to declare. each must be a legal javascript identifier. value1, value2, …, valuen optional for each variable declared, you may optionally specify its initial value to any legal javascript expression. description let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope. the other difference between var and let is that the latter is initialized to a value only when a parser evaluates it (see below). just like const the let does not cr...
..., 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 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); // o...
...riable'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) { var a = 11; // the scope is global let b = 22; // the scope is inside the if-block console.log(a); // 11 console.log(b); // 22 } console.log(a); // 11 console.log(b); // 2 however, this combination of var and let declaration below is a syntaxerror due to var being hoisted to the top of the block. this results in an implicit re-declaration of the variable. let x = 1; { var x = 2; // syntaxerror for re-declaration } specifications specification ecmascript (ecma-262)the definition of 'let and const declarations' in that specification. ...
with - JavaScript
the with statement extends the scope chain for a statement. syntax with (expression) statement expression adds the given expression to the scope chain used when evaluating the statement. the parentheses around the expression are required. statement any statement. to execute multiple statements, use a block statement ({ ... }) to group those statements. ...
...with' will relieve the interpreter of parsing repeated object references. note, however, that in many cases this benefit can be achieved by using a temporary variable to store a reference to the desired object. contra: the with statement forces the specified object to be searched first for all name lookups. therefore all identifiers that aren't members of the specified object will be found more slowly in a 'with' block. where performance is important, 'with' should only be used to encompass code blocks that access members of the specified object. ambiguity contra contra: the with statement makes it hard for a human reader or javascript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object. so given this example: function f(x, o) { ...
... will be available on every array). so, in a javascript environment that supports ecmascript 2015, the values reference inside the with statement could resolve to [1,2,3].values. however, in this particular example, array.prototype has been defined with values in its symbol.unscopables object. if it were not, one can see how this would be a difficult issue to debug. examples using with the following with statement specifies that the math object is the default object. the statements following the with statement refer to the pi property and the cos and sin methods, without specifying an object. javascript assumes the math object for these references. var a, x, y; var r = 10; with (math) { a = pi * r * r; x = r * cos(pi); y = r * sin(pi / 2); } specifications specification...
JavaScript
gether a course that includes all the essential information you need to work towards your goal. get started tutorials learn how to program in javascript with guides and tutorials. for complete beginners head over to our learning area javascript topic if you want to learn javascript but have no previous experience of javascript or programming. the complete modules available there are as follows: javascript first steps answers some fundamental questions such as "what is javascript?", "what does it look like?", and "what can it do?", along with discussing key javascript features such as variables, strings, numbers, and arrays. javascript building blocks continues our coverage of javascript's key fundamental features, turning our attention to commonly-encountered types of code block...
...n, for-of, try-catch, let, var, const, if-else, switch, and more javascript statements and keywords work. functions learn how to work with javascript's functions to develop your applications. tools & resources helpful tools for writing and debugging your javascript code. firefox developer tools web console, javascript profiler, debugger, and more. javascript shells a javascript shell allows you to quickly test snippets of javascript code. learn javascript an excellent resource for aspiring web developers — learn javascript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. the first 40 lessons are free, and the complete course is available for a small one-time payment. togetherjs collaboration made easy. by adding together...
... for aspiring web developers — learn javascript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. the first 40 lessons are free, and the complete course is available for a small one-time payment. togetherjs collaboration made easy. by adding togetherjs to your site, your users can help each other out on a website in real-time! stack overflow stack overflow questions tagged with "javascript". javascript versions and release notes browse javascript's feature history and implementation status. jsfiddle edit javascript, css, html and get live results. use external resources and collaborate with your team online. plunker plunker is an online community for creating, collaborating on and sharing your web development ideas. edit your ...
<math> - MathML
Web › MathML › Element › math
class, id, style provided for use with stylesheets. dir overall directionality of formulas. possible values are either ltr (left to right) or rtl (right to left). ...
... values are either ltr (left to right) or rtl (right to left). 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. display this enumerated attribute specifies how the enclosed mathml markup should be rendered. it can have one of the following values: block, which means that this element will be displayed outside the current span of text, as a block that can be positioned anywhere without changing the meaning of the text; inline, which means that this element will be displayed inside the current span of text, and cannot be moved out of it without changing the meaning of that text. if not present, its default value is inlin...
... changing the meaning of the text; inline, which means that this element will be displayed inside the current span of text, and cannot be moved out of it without changing the meaning of that text. if not present, its default value is inline. mode deprecated in favor of the display attribute. possible values are: display (which has the same effect as display="block") and inline. overflow specifies how an expression behaves if it is too long to fit in the allowed width. possible values are: linebreak (default), scroll, elide, truncate, scale. examples html5 notation <!doctype html> <html> <head> <title>mathml in html5</title> </head> <body> <math> <mrow> <mrow> <msup> <mi>a</mi> <mn>2</mn> </msup> <mo>+</mo...
<mmultiscripts> - MathML
in a descriptive way tensors are multidimensional matrices (mathematical imprecise but exemplified). the degree of a tensor depends on the dimensionality of a representative array. for example, a number is a 0-dimensional array, or a 0th-order tensor. a 1-dimensional array (e.g. vectors) is a 1st-order tensor and so 2nd-order tensors are needed to represent square matrices. to learn more about the mathematical background of tensors refer to the entry on wikipedia. ...
...cripts for both, postscripts and prescripts, attached to a base expression: <mmultiscripts> base (subscript superscript)* [ <mprescripts/> (presubscript presuperscript)* ] </mmultiscripts> after the base expression you can specify a postsubscript and a postsuperscript. prescripts are optional and are separated by the empty tag <mprescripts/> (only one <mprescripts /> element is allowed, otherwise you will get an duplicatemprescripts error in the error console and "invalid-markup" in your rendering). in addition you are able to use <none/> as a placeholder 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 ...
... 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 rendering: rendering in your browser: x d c b a ...
<mn> - MathML
Web › MathML › Element › mn
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). 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. ...
...small, normal and big. these will be removed in the future. mathvariant this attribute specifies the logical class of the number which varies in typography. that is, although the names suggest the typographic style for the class, semantically, items with the same class are treated "the same" within an expression, which might or might not involve displaying them with the named typography. ...
...g. these will be removed in the future. mathvariant this attribute specifies the logical class of the number which varies in typography. that is, although the names suggest the typographic style for the class, semantically, items with the same class are treated "the same" within an expression, which might or might not involve displaying them with the named typography. ...
<semantics> - MathML
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> child element of <semantics>. beware that <annotation-xml> e...
...red, 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> child element of <semantics>. ...
... encoding the encoding of the semantic information in the annotation (e.g. ...
Handling media support issues in web content - Web media technologies
from the video itself but contains imagery and/or text which gives the reader a useful idea of the video's contents. in the case of an action movie, for example, the poster frame might be an iconic exemplar image from one of the film's best-known scenes. a similar concept can be applied to still images; if an image you wish to present is very large and may take time to download (especially for slower devices or connections), you can offer a lower-resolution or alternate version that will be displayed until the full-quality version is available to be displayed. we'll look at both of these scenarios and how to implement them. poster frames for video progressive images images—whether embedded using <img> or <picture>—don't support a concept similar to poster frames. however, there are ...
...this requires creating your images using progressive formats, such as progressive jpeg or interlaced png. once your image has been converted to progressive form, you can simply use it as usual. ...
...is requires creating your images using progressive formats, such as progressive jpeg or interlaced png. once your image has been converted to progressive form, you can simply use it as usual. <img src="/images/stafff-photo-huge-progressive.jpg" alt="staff photo, taken in january of 1972"> when using a progressive image, the data is stored in such a way that the browser is able to render a low-quality representation of the image as soon as possible, then update the image as it loads—or after it's finished loading—to present it in full quality. 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...
OpenSearch description format
hform> element. this article focuses on creating opensearch-compatible search plugins that support these additional firefox features. opensearch description files can be advertised as described in autodiscovery of search plugins, and can be installed programmatically as described in adding search engines from web pages. opensearch description file the xml file that describes a search engine follows the basic template below. sections in [square brackets] should be customized for the specific plugin you're writing. <opensearchdescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/"> <shortname>[snk]</shortname> <description>[search engine full name and summary]</description> <inputencoding>[utf-8]</inputenc...
...e it. autodiscovery of search plugins web sites with search plugins can advertise them so firefox users can easily install the plugins. to support autodiscovery, add a <link> element for each plugin to the <head> of your web page: <link rel="search" type="application/opensearchdescription+xml" title="searchtitle" href="pluginurl"> replace the bolded items as explained below: searchtitle the name of the search to perform, such as "search mdc" or "yahoo! search". this must match your plugin file's <shortname>. pluginurl the url to the xml search plugin, so the browser can download it. if your site offers multiple search plugins, you can support autodiscovery for them all. for example: <link rel="search" type="application/opensearchdescription+xml" title...
...cription.xml" /> note: at this time, addons.mozilla.org (amo) doesn't support automatic updating of opensearch plugins. if you want to put your search plugin on amo, remove the auto-updating feature before submitting it. troubleshooting tips if there is a mistake in your search plugin xml, you could run into errors when adding a discovered plugin. if the error message isn't be helpful, the following tips could help you find the problem. your server should serve opensearch plugins using content-type: application/opensearchdescription+xml. be sure that your search plugin xml is well formed. you can check by loading the file directly into firefox. ampersands (&) in the template url must be escaped as &amp;, and tags must be closed with a trailing slash or matching end tag. the xmlns att...
Recommended Web Performance Timings: How long is too long? - Web Performance
load goal the 'under a second' is often touted as optimal for load, but what does that mean? a second should be considered a rule in the maximum amount of time to indicate to a user that the request for new content was made and will load, such as the browser displaying the page title and the background color of the page displaying. the first asset retrieved from a request is usually an html document, which then makes calls for additional assets. ...
...ason, script execution should be limited in scope, divided into chunks of code that can be executed in 50ms or less. this makes the thread available for user interactions. animation goal for scrolling and other animations to look smooth and feel responsive, the content repaints should occur at 60 frames per second (60fps), which is once every 16.7ms. the 16.7 milliseconds includes scripting, reflow, and repaint. realize a document takes about 6ms to render a frame, leaving about 10ms for the rest. anything less than 60fps, especially an un-even or changing frame rate, will appear janky. responsiveness goal when the user interacts with content, it is important to provide feedback and acknowledge the user's response or interaction and to do so within 100ms, preferably within 50ms. 50ms seco...
...iveness goal when the user interacts with content, it is important to provide feedback and acknowledge the user's response or interaction and to do so within 100ms, preferably within 50ms. 50ms seconds feels immediate. the acknowledgment of user interaction should often feel immediate, such as a hover or button press, but that doesn't mean the completed response should be instantaneous. while a slower than 100ms reaction may create a disconnect between the user interaction and the response, a 100 to 200ms transition for a response may help the user notice the response their interaction initiated, such as a menu opening. if a response takes longer than 100ms to complete, provide some form of feedback to inform the user the interaction has occurred. ...
Navigation and resource timings - Web Performance
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. 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 rep...
...imings 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, the navigation process goes from navigationstart, unloadeventstart, unloadeventend, redirectstart, redirectend, fetchstart, domainlookupstart, domainlookupend, connectstart , connectend, secureconnectionstart, requeststart, responsestart, responseend, domloading, dominteractive, domcontentloadedeventstart, domcontentloadedeventend, domcomplete, loadeventstart, and loadeventend. with the metri...
...arked as completely loaded. let navigationtimings = performance.getentriesbytype('navigation'); the performance.getentriesbytype('navigation')a returns an array of performanceentry objects for the navigation type. a lot can be garnered from these timing. in the above image, we see via the name property that the file being timed is this document for the rest of this explanation, we use the following variable: let timing = performance.getentriesbytype('navigation')[0]; protocol we can check the protocol used by querying: let protocol = timing.nexthopprotocol it returns the network protocol used to fetch the resource: in this case h2 for http/2. compression to get the compression savings percentage, we divide the transfersize by the decodedbodysize, and subtract that from 100%. we se...
Performance budgets - Web Performance
ry 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 with smaller alternatives is often picked to solve a common problem). how do i define 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...
... you should focus on user experience, which will dictate not only the bounce or conversion rate but how likely is that user to return. how do i implement a performance budget? during development, there are a few tools to run checks against new or modified assets: a module bundler (e.g. webpack), has performance features that will notify you when assets exceed specified limits. bundlesize, allows you to define and run file size checks in your ci pipeline. file size checks are the first line of defense against regressions but translating size back into time metrics can be difficult since development environments could be missing 3rd party scripts, and optimizations commonly provided by a cdn. the first step is to define a development baseline for each branch to compare to and the preci...
...rl. 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 introduce a feature that increases overall load time but attempts to increase user engagement. (i.e. how long a user stays on a page or site). a performance budget helps you protect optimal behavior for your current users while enabling you to tap into new markets and deliver custom experiences. ...
Understanding latency - Web Performance
is made by the user to the time it takes for the response to get back to that user. on a first request, for the first 14kb bytes, latency is longer because it includes a dns lookup, a tcp handshake, the secure tls negotiation. subsequent requests will have less latency because the connection to the server is already set. latency describes the amount of delay on a network or internet connection. low latency implies that there are no or almost no delays. high latency implies that there are many delays. one of the main aims of improving performance is to reduce latency. the latency associated with a single asset, especially a basic html page, may seem trivial. but websites generally involve multiple requests: the html includes requests for multiple css, scripts, and media files. the greater ...
... aims of improving performance is to reduce latency. the latency associated with a single asset, especially a basic html page, may seem trivial. but websites generally involve multiple requests: the html includes requests 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 t...
...atency 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 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. different browser developer tools have different preset options, the characteristics emulated include download speed, upload speed, and minimum latency, or the minimum amount of type it takes to send a...
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
js file, and can be executed after the registration is successful. it's the only piece of service worker code that sits inside the app.js file; everything else that is service worker-specific is written in the sw.js file itself. lifecycle of a service worker when registration is complete, the sw.js file is automatically downloaded, then installed, and finally activated. installation the api allows us to add event listeners for key events we are interested in — the first one is the install event: self.addeventlistener('install', (e) => { console.log('[service worker] install'); }); in the install listener, we can initialize the cache and add files to it for offline use. our js13kpwa app does exactly that. first, a variable for storing the cache name is created, and the app shell f...
... also an activate event, which is used in the same way as install. this event is usually used to delete any files that are no longer necessary and clean up after the app in general. we don't need to do that in our app, so we'll skip it. responding to fetches we also have a fetch event at our disposal, which fires every time an http request is fired off from our app. this is very useful, as it allows us to intercept requests and respond to them with custom responses. here is a simple usage example: self.addeventlistener('fetch', (e) => { console.log('[service worker] fetched resource '+e.request.url); }); the response can be anything we want: the requested file, its cached copy, or a piece of javascript code that will do something specific — the possibilities are endless. in our exa...
...nction that tries to find the resource in the cache and return the response if it's there. if not, we use another fetch request to fetch it from the network, then store the response in the cache so it will be available there next time it is requested. the fetchevent.respondwith method takes over control — this is the part that functions as a proxy server between the app and the network. this allows us to respond to every single request with any response we want: prepared by the service worker, taken from cache, modified if needed. that's it! our app is caching its resources on install and serving them with fetch from the cache, so it works even if the user is offline. it also caches new content whenever it is added. updates there is still one point to cover: how do you upgrade a service...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
but instead of relying only on user actions, we can do more, using push messages and notifications to automatically re-engage and deliver new content whenever it is available. two apis, one goal the push api and notifications api are two separate apis, but they work well together when you want to provide engaging functionality in your app. ...
...the making pwas work offline with service workers article. inside the service worker, a push service subscription mechanism is created. registration.pushmanager.getsubscription() .then( /* ... */ ); once the user is subscribed, they can receive push notifications from the server. from the server-side, the whole process has to be encrypted with public and private keys for security reasons — allowing everyone to send push messages unsecured using your app would be a terrible idea. see the web push data encryption test page for detailed information about securing the 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.add...
...rticle. we will only provide a high-level overview here. the web-push module is used to set the vapid keys, and optionally generate them if they are not available yet. const webpush = require('web-push'); if (!process.env.vapid_public_key || !process.env.vapid_private_key) { console.log("you must set the vapid_public_key and vapid_private_key "+ "environment variables. you can use the following ones:"); console.log(webpush.generatevapidkeys()); return; } webpush.setvapiddetails( 'https://serviceworke.rs/', process.env.vapid_public_key, process.env.vapid_private_key ); next, a module defines and exports all the routes an app needs to handle: getting the vapid public key, registering, and then sending notifications. you can see the variables from the index.js file being us...
Graphic design for responsive sites - Progressive web apps (PWAs)
ertain assets for the site's mobile layout, or even provide smaller assets to suit the smaller screen better. this is because in general mobile devices will have less processing power and bandwidth available, so you want to reduce the processing and downloads. in addition, mobile devices have smaller screen sizes, so it makes sense to reduce visual clutter on a mobile layout. css media queries allow us to serve different css rules dependant on viewport dimensions, and you should consider using mobile first media queries where possible. this means that the default layout before any media queries are encountered in the css is the small screen/mobile layout, not the wide screen/desktop layout. so when the page is loaded on a mobile device, the mobile will only download the mobile assets, and no...
...hen rendered on high res devices, are in danger of appearing tiny because the same number of pixels is being shown in a much smaller screen space. most hi res devices apply a default zoom factor to the whole web page so that the content is a bit more legible, but the downside of this is that the images in question start to look pixellated and ugly because they have been zoomed in. high res and low res image copies one option here is to create a hi res and a low res set of images, then use resolution media queries to serve the hi res images only to hi res devices. programmatic images you should also try to use programmatic/vector graphics as much as possible, as they theoretically scale infinitely so will still look crisp at high resolutions. you could use css3 properties for generating ...
...le can be a bit fiddly, but there are a number of good icon font services available such as font awesome. interactive images if your images need to feature some level of interactivity, such as links, other clickable areas, or animation, there are a number of options available. css as well as adding programmatic graphical effects to links (and anywhere else you might want them), css3 also allows you to write declarative animations and transitions. these may not be supported in older browsers like ie6-8, but they generally degrade gracefully, are fairly easy to write, and become much more flexible and powerful when combined with javascript and other technologies. javascript javascript has functions that enable developers to create animations, and any other type of interactivity you wan...
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
cing document. using embedded svg to apply an svg effect using css styles, you first need to create the css style that references the svg to apply. <style>p { mask: url(#my-mask); }</style> in the above example, all paragraphs are masked by an svg <mask> with the id my-mask. ...
...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>...
...you can achieve the same eff...
SVG Core Attributes - SVG: Scalable Vector Graphics
Web › SVG › Attribute › Core
or the language that editable elements should be written in. the tag contains one single entry value in the format defined in the tags for identifying languages (bcp47) ietf document. svg 2 introduce the new lang attributes. if both lang and xml:lang attribute are used, xml:lang has priority over lang. ...
...instead, use xml:lang="und". ...
...instead, use xml:lang="und". svg 2 introduce the new lang attributes. ...
clip-rule - SVG: Scalable Vector Graphics
« svg attribute reference home the clip-rule attribute only applies to graphics elements that are contained within a <clippath> element. the clip-rule attribute basically works as the fill-rule attribute, except that it applies to <clippath> definitions. ...
...te, except that it applies to <clippath> definitions. the following fragment of code will cause an evenodd clipping rule to be applied to the clipping path because clip-rule is specified on the <path> element that defines the clipping shape: <g> <clippath id="myclip"> <path d="..." clip-rule="evenodd" /> </clippath> <rect clip-path="url(#myclip)" ... /> </g> whereas the following fragment of code will not cause an evenodd clipping rule to be applied because the clip-rule is specified on the referencing element, not on the object defining the clipping shape: <g> <clippath id="myclip"> <path d="..." /> </clippath> <rect clip-path="url(#myclip)" clip-rule="evenodd" ... /> </g> as a presentation attribute, it also can be used as a property directly i...
... graphical elements » 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 exploreropera...
font-size-adjust - SVG: Scalable Vector Graphics
« svg attribute reference home the font-size-adjust attribute allows authors to specify an aspect value for an element that will preserve the x-height of the first choice font in a substitute font. note: as a presentation attribute, font-size-adjust can be used as a css property. see the css font-size-adjust property for more information. as a presentation attribute, it can be applied to any element but it has effect only on the following eight elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg width="600" height="80" viewbox="0 0 500 80" xmlns="http://www.w3.org/2000/svg"> <text y="20" font-family="times, serif" font-size="10px"> this text uses the times font (10px), which is hard to read in small sizes. </text>...
...{ height: 100%; } <svg width="600" height="80" viewbox="0 0 500 80" xmlns="http://www.w3.org/2000/svg"> <text y="20" font-family="times, serif" font-size="10px"> this text uses the times font (10px), which is hard to read in small sizes. </text> <text y="40" font-family="verdana, sans-serif" font-size="10px"> this text uses the verdana font (10px), which has relatively large lowercase letters. </text> <text y="60" font-family="times, serif" font-size="10px" 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 propert...
...mes, serif" font-size="10px" 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 heigh...
mask - SVG: Scalable Vector Graphics
Web › SVG › Attribute › mask
as a presentation attribu...
... as a presentation attribute, it can be applied to any element but it has noticeable effects mos...
... cx="50" cy="50" r="45" fill="red" mask="url(#mymask)"/> </svg> since svg2, the mask attribute is defined as a css property and is a shorthand for many other properties: mask-image, mask-mode, mask-repeat, mask-position, mask-clip, mask-origin, mask-size, and mask-composite. ...
paint-order - SVG: Scalable Vector Graphics
the paint-order attribute specifies the order that the fill, stroke, and markers of a given shape or text element are painted. note: as a presentation attribute, paint-order 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 ten elements: <circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, <rect>, <text>, <textpath>, and <tspan> usage notes value normal | [ fill || stroke || markers ] default value normal animatable yes normal this value indicates that the fill will be painted first, then the stroke, and finally the markers. [ fill || stroke || markers ] the order of these three keywords indicates the order in which the painting happens, from left to r...
... candidate recommendation initial definition ...
... candidate recommendation initial definition ...
<circle> - SVG: Scalable Vector Graphics
Web › SVG › Element › circle
0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <circle cx="50" cy="50" r="50"/> </svg> attributes cx the x-axis coordinate of the center of the circle. value type: <length>|<percentage> ; default value: 0; animatable: yes cy the y-axis coordinate of the center of the circle. value type: <length>|<percentage> ; default value: 0; animatable: yes r the radius of the circle. a value lower or equal to zero disables rendering of the circle. value type: <length> ; default value: 0; animatable: yes pathlength the total length for the circle's circumference, in user units. value type: <number> ; default value: none; animatable: yes note: starting with svg2, cx, cy, and r are geometry properties, meaning those attributes can also be used as css properties for that element. gl...
...fset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
... candidate recommendation scalable vector graphics (svg) 1.1 (second edition)the definition of '<circle>' in that specification. recommendation initial de...
<symbol> - SVG: Scalable Vector Graphics
Web › SVG › Element › symbol
fset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
...only instances of a <symbol> eleme...
...> element (i.e., a reference to a <symbol> by a <use> element) are rendered. that means that some browsers could refuse to directly display a <symbol> element even if the css display property tells otherwise. specifications specification status comment scalable vector graphics (svg) 2the definition of '<symbol>' in that specification. candidate recommendation allowed geometry properties to be specified on a symbol scalable vector graphics (svg) 1.1 (second edition)the definition of '<symbol>' in that specification. recommendation initial definition ...
<tspan> - SVG: Scalable Vector Graphics
Web › SVG › Element › tspan
html,body,svg { height:100% } <svg viewbox="0 0 240 40" xmlns="http://www.w3.org/2000/svg"> <style> text { font: italic 12px serif; } tspan { font: bold 10px sans-serif; fill: red; } </style> <text x="10" y="30" class="small"> you are <tspan>not</tspan> a banana! </text> </svg> attributes x the x coordinate of the starting point of the text baseline. ...
...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-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
... candidate recommendation scalable vector graphics (svg) 1.1 (second edition)the definition of '<tspan>' in that s...
<use> - SVG: Scalable Vector Graphics
Web › SVG › Element › use
policy on use elements and may refuse to load a cross-origin url in the href attribute. there is currently no defined way to set a cross-origin policy for use elements. since svg 2, the xlink:href attribute is deprecated in favor of href. see xlink:href page for more information. however, xlink:href can still be required in practice for cross-browser compatibility (see the compatibility table below). attributes href the url to an element/fragment that needs to be duplicated. value type: <url> ; default value: none; animatable: yes xlink:href an <iri> reference to an element/fragment that needs to be duplicated. value type: <iri> ; default value: none; animatable: yes x the x coordinate of the use element. value type: <coordinate> ; default value: 0; animatable: yes y the y c...
...fset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
... candidate recommendation scalable vector graphics (svg) 1.1 (second edition)the definition of '<use>' in that specification. recommendation initial definitio...
Basic Transformations - SVG: Scalable Vector Graphics
to start distorting our beautiful images. but first, let's formally introduce the <g> element. with this helper, you can assign properties to a complete set of elements. actually, that's its only purpose. an example: <svg width="30" height="10"> <g fill="red"> <rect x="0" y="0" width="10" height="10" /> <rect x="20" y="0" width="10" height="10" /> </g> </svg> all following transformations are summed up in an element's transform attribute. transformations can be chained simply by concatenating them, separated by whitespace. translation it may be necessary to move an element around, even though you can position it with the according attributes. for this purpose, the translate() transformation stands ready. <svg width="40" height="50" style="background-color:#bf...
...dsys}} + f \end{matrix} \right. see a concrete example on the svg transform documentation. detailed information about this property can be found in the svg recommendation. effects on coordinate systems when using transformations you establish a new coordinate system inside the element the transformations apply to. that means, the units you specify for the element and its children might not follow the 1:1 pixel mapping, but are also distorted, skewed, translated and scaled according to the transformation. <svg width="100" height="100"> <g transform="scale(2)"> <rect width="50" height="50" /> </g> </svg> the resulting rectangular in the above example will be 100x100px. the more intriguing effects arise, when you rely on attributes like userspaceonuse and the such. embe...
...d, skewed, translated and scaled according to the transformation. <svg width="100" height="100"> <g transform="scale(2)"> <rect width="50" height="50" /> </g> </svg> the resulting rectangular in the above example will be 100x100px. the more intriguing effects arise, when you rely on attributes like userspaceonuse and the such. embedding svg in svg in contrast to html, svg allows you to embed other svg elements seamlessly. this way you can also simply create new coordinate systems by utilizing the viewbox, width and height of the inner svg element. <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100" height="100"> <svg width="100" height="100" viewbox="0 0 50 50"> <rect width="50" height="50" /> </svg> </svg> the example above has basically the sa...
Mixed content - Web security
pted content accessible to sniffers and man-in-the-middle attackers. that leaves the pages unsafe. types of mixed content there are two categories for mixed content: mixed passive/display content and mixed active content. the difference lies in the threat level of the worst case scenario if content is rewritten as part of a man-in-the-middle attack. in the case of passive content, the threat is lower (the page may contain misleading content, or the user's cookies may be stolen). in the case of active content, the threat can lead to phishing, sensitive data disclosure, redirection to malicious sites, etc. mixed passive/display content mixed passive/display content is content served over http that is included in an https webpage, but that cannot alter other portions of the webpage. for exam...
...eck or missing padlock that will check your website recursively and find links to insecure content. starting in firefox 23, mixed active content is blocked by default (and mixed display content can be blocked by setting a preference). ...
...rors, all blocked mixed content requests are logged to the security pane of the web console, as seen below: to fix this type of error, all requests to http content should be removed and replaced with content served over https. some common examples of mixed content include javascript files, stylesheets, images, videos, and other media. note: since firefox 55, the loading of mixed content is allowed on http://127.0.0.1/ (see bug 903966). chrome allows mixed content on http://127.0.0.1/ and http://localhost/. safari does not allow any mixed content. ...
Caching compiled WebAssembly modules - WebAssembly
rialization support is being removed from browsers; see bug 1469395 and this spec issue. caching is useful for improving the performance of an app — we can store compiled webassembly modules on the client so they don't have to be downloaded and compiled every time. this article explains the best practices around this. caching via indexeddb indexeddb is a transactional database system that allows you to store and retrieve structured data on the client-side. it is ideal for persisting assets locally for the saved state of an application, including text, blobs, and any other type of cloneable object. this includes compiled wasm modules (webassembly.module javascript objects). setting up a caching library because indexeddb is a somewhat old-fashioned api, we wanted to provide a library f...
...es previously cached modules from the database, saving you from having to download them again. note: the entire site's wasm cache (not just the given url) is versioned by the specified dbversion passed into the function. if the wasm module code is updated, or its url changes, you will need to update dbversion. any subsequent call to instantiatecachedurl() will then clear out the entire cache, allowing you to avoid using out-of-date modules. the function starts off by defining some necessary constants: function instantiatecachedurl(dbversion, url, importobject) { const dbname = 'wasm-cache'; const storename = 'wasm-cache'; setting up the database the first helper function contained inside instantiatecachedurl() — opendatabase() — creates an object store for storing wasm modules,...
...database to store them into). errmsg => { console.log(errmsg); return webassembly.instantiatestreaming(fetch(url)).then(results => { return results.instance }); }); } caching a wasm module with the above library function defined, getting a wasm module instance and using its exported features (while handling caching in the background) is as simple as calling it with the following parameters: a cache version, which — as we explained above — you need to update when any wasm module is updated or moved to a different url. the url of the wasm module you want to instantiate. an import object, if required. const wasmcacheversion = 1; instantiatecachedurl(wasmcacheversion, 'test.wasm').then(instance => console.log("instance says the answer is: " + instance.export...
Communicating With Other Scripts - Archive of obsolete content
bedded in the page or linked to it using the src attribute, there are a couple of ways a content script can communicate with it: using the dom postmessage() api using custom dom events using the dom postmessage api note that before firefox 31 code in content scripts can't use window to access postmessage() and addeventlistener() and instead must use document.defaultview. see the section below on using postmessage() before firefox 31. you can communicate between the content script and page scripts using window.postmessage(). messaging from content script to page script suppose we have a page called "listen.html" hosted at "my-domain.org", and we want to send messages from the add-on to a script embedded in that page. in the main add-on code, we have a page-mod that attaches the co...
... finally, "listen.html" uses window.addeventlistener() to listen for messages from the content script: <!doctype html> <html> <head></head> <body> <script> window.addeventlistener('message', function(event) { window.alert(event.data); // message from content script }, false); </script> </body> </html> messaging from page script ...
Cross-domain Content Scripts - Archive of obsolete content
on's package.json under the "cross-domain-content" key, which itself lives under the "permissions" key: "permissions": { "cross-domain-content": ["http://example.org/", "http://example.com/"] } the domains listed must include the scheme and fully qualified domain name, and these must exactly match the domains serving the content - so in the example above, the content script will not be allowed to access content served from https://example.com/. wildcards are not allowed. this feature is currently only available for content scripts, not for page scripts included in html files shipped with your add-on. cross-domain iframes the following "main.js" creates a page-worker which loads a local html file called "page.html", attaches a content script called "page.js" to the page, waits fo...
...var todaysfeaturedarticle = iframe.contentwindow.document.getelementbyid("mp-tfa"); self.postmessage(todaysfeaturedarticle.textcontent); for this to work, we need to add the "cross-domain-content" key to "package.json": "permissions": { "cross-domain-content": ["http://en.m.wikipedia.org/"] } the add-on should successfully retrieve the iframe's content. cross-domain xmlhttprequest the following add-on creates a panel whose content is the summary weather forecast for shetland. if you want to try it out, you'll need to register and get an api key. the "main.js": creates a panel whose content is supplied by "panel.html" and adds a content script "panel-script.js" to it sends the panel a "show" message when it is shown adds a button which shows the panel when it is clicked // mai...
private-browsing - Archive of obsolete content
ing status is a property of an individual browser window. the user enters private browsing by opening a new private browser window. when they do this, any existing non-private windows are kept open, so the user will typically have both private and non-private windows open at the same time. ...
...bjects will not be shown if the active window is a private browser window the selection module will not include any selections made in private browser windows add-ons that have opted in will see private windows, so they will need to use the private-browsing module to check whether objects are private, so as to avoid storing data derived from such objects. additionally, add-ons that use low-level modules such as window/utils may see private browser windows with certain functions, even if they have not explicitly opted into private browsing. respecting private browsing the private-browsing module exports a single function isprivate() that takes an object, which may be a browserwindow, tab, or worker, as an argument. it returns true only if the object is: a private window, or a ...
self - Archive of obsolete content
ocal storage and other resources that are associated with a particular add-on. name this property contains the add-on's short name. it comes from the name property in the main package's package.json file. version this property contains the add-on's version string. it comes from the version property set in the package.json file in the main package. loadreason this property contains of the following strings describing the reason your add-on was loaded: install enable startup upgrade downgrade isprivatebrowsingsupported this property indicates whether or not the add-on supports private browsing. it comes from the private-browsing key in the add-on's package.json file. data the data object is used to access data that was bundled with the add-on. this data lives in the add-on's data/ d...
...he reason your add-on was loaded: install enable startup upgrade downgrade isprivatebrowsingsupported this property indicates whether or not the add-on supports private browsing. it comes from the private-browsing key in the add-on's package.json file. data the data object is used to access data that was bundled with the add-on. this data lives in the add-on's data/ directory, immediately below the package.json file. all files in this directory will be copied into the xpi and made available through the data object. the package specification article explains the package.json file. methods data.load(name) the data.load() method returns the contents of an embedded data file, as a string. it is most useful for data that will be modified or parsed in some way, such as json, xml, plain te...
simple-prefs - Archive of obsolete content
eference is defined by a group of attributes. there are: mandatory attributes that all preferences must have optional attributes attributes that are specific to the preference's data type mandatory common attributes these are attributes that all preferences must have. attribute description type the type of preference, as defined in the "preference types" section below. name an identifier for the preference. this is used to access the preference from your add-on: console.log(require("sdk/simple-prefs").prefs.mysettingname); this means that it must be a valid javascript identifier. title this is used as a label for the preference in the add-ons manager user interface. optional common attributes these are attribu...
...console.log(require("sdk/simple-prefs").prefs.mysettingname); this means that it must be a valid javascript identifier. title this is used as a label for the preference in the add-ons manager user interface. optional common attributes these are attributes that all preferences may have: attribute description description this appears below the preference title in the add-ons manager ui. value a default value for the preference. depending on the preference type, this may be an integer, string, or boolean value. hidden a boolean value which, if present and set to true, means that the preference won't appear in the add-ons manager interface, so users of your add-on won't be able to see or alter it. { ...
simple-storage - Archive of obsolete content
.1337; ss.storage.myobject = { a: "foo", b: { c: true }, d: null }; ss.storage.mystring = "o frabjous day!"; you can store array, boolean, number, object, null, and string values. if you'd like to store other types of values, you'll first have to convert them to strings or another one of these types. be careful to set properties on the storage object and not the module itself, as demonstrated below: // this is not good! var ss = require("sdk/simple-storage"); ss.foo = "i will not be saved! :("; simple storage and "jpm run" the simple storage module stores its data in your profile. because jpm run by default uses a fresh profile each time it runs, simple storage won't work with add-ons executed using jpm run - that is, stored data will not persist from one run to the next. the easiest so...
...ur debugging session by quitting firefox normally, not by cancelling the shell command. if you don't close firefox normally, then simple storage will not be notified that the session is finished, and will not write your data to the backing store. accessing storage from the console in the add-on debugger, you can access your add-on's simple-storage programmatically from the console using the following: loader.modules['resource://gre/modules/commonjs/sdk/simple-storage.js'].exports.storage clarification from mozilla needed: writing the above line in add-on debugger console results in "referenceerror: loader is not defined". constructing arrays be careful to construct array objects conditionally in your code, or you may zero them each time the construction code runs. for example, this a...
url - Archive of obsolete content
r.mozilla.org/add-ons?example=true&visible=yes#top"); console.log(url.path); // /add-ons?example=true&visible=yes#top hostname the domain of the url, as a string. mirrors window.location.hostname. for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=true&visible=yes#top"); console.log(url.hostname); // developer.mozilla.org pathname an initial '/' followed by the path of the url, as a string. compare with path. mirrors window.location.pathname. for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=true&visible=yes#top"); console.log(url.pathname); // /add-ons hash a '#' followed by the fragment identifier of the url, as a string. mirrors window.location.hash. for example: var url = require("sdk/url").ur...
...origin for this url, as a string. mirrors window.location.origin. protocol the protocol of the url, including the final ':', as a string. compare with scheme. mirrors window.location.protocol. for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=true&visible=yes#top"); console.log(url.protocol); // https: search if any parameters are present, a '?' followed by the parameters of the url, as a string. mirrors window.location.search. for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=true&visible=yes#top"); console.log(url.search); // ?example=true&visible=yes dataurl methods tostring() returns a string representation of the data url. if base64 is true, the data property is encoded using base-64 encodin...
windows - Archive of obsolete content
in particular, depending on what you do with these objects, your code might not work with multiprocess firefox. globals functions open(options) open a new window. var windows = require("sdk/windows").browserwindows; // open a new window. windows.open("http://www...
... var windows = require("sdk/windows").browserwindows; // add a listener to the 'open' event windows.on('open', function(window) { myopenwindows.push(window); }); // add a listener to the 'close' event windows.on('close', function(window) { console.log("a window was closed."); }); // add a listener to the 'activate' event windows.on(...
content/mod - Archive of obsolete content
experimental provides functions to modify a page content. globals 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 sp...
...nt 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 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); p...
core/heritage - Archive of obsolete content
, blue: function blue() { return parseint(this.color.substr(4, 2), 16); } }); var cmyk = class({ black: function black() { var color = math.max(math.max(this.red(), this.green()), this.blue()); return (1 - color / 255).tofixed(4); }, magenta: function magenta() { var k = this.black(); return (((1 - this.green() / 255).tofixed(4) - k) / (1 - k)).tofixed(4); }, yellow: function yellow() { var k = this.black(); return (((1 - this.blue() / 255).tofixed(4) - k) / (1 - k)).tofixed(4); }, cyan: function cyan() { var k = this.black(); return (((1 - this.red() / 255).tofixed(4) - k) / (1 - k)).tofixed(4); } }); such composable pieces can be combined into a single class definition by passing special implements option to a class function: // com...
...as mentioned before you could pass constructors that were not created using class function as long as they have proper prototype setup. also you can mix...
frame/utils - Archive of obsolete content
= create(window.document); optionally create can be passed set of options to configure created frame even further. execution of scripts may easily be enabled: let { open } = require('sdk/window/utils'); let { create } = require('sdk/frame/utils'); let window = open('data:text/html,top'); let frame = create(window.document, { uri: 'data:text/html,<script>console.log("running");</script>', allowjavascript: true }); } globals functions create(document, options) creates a xul browser element in a privileged document. parameters document : nsidomdocument options : object optional options: name type type string string that defines access type of the document loaded into it. defaults to "content". for more details and other possible values se...
... type string string that defines access type of the document loaded into it. defaults to "content". for more details and other possible values see documentation on mdn uri string uri of the document to be loaded into the new frame. defaults to about:blank. remote boolean if true separate process will be used for this frame, and all the following options are ignored. allowauth boolean whether to allow auth dialogs. defaults to false. allowjavascript boolean whether to allow javascript execution. defaults to false. allowplugins boolean whether to allow plugin execution. defaults to false. returns frame : the new browser element. ...
stylesheet/utils - Archive of obsolete content
ns for working with stylesheets. globals functions loadsheet(window, uri, type) synchronously loads a style sheet from uri and adds it to the list of additional style sheets of the document. the sheets added takes effect immediately, and only on the document of the window given. parameters window : nsidomwindow uri : string, nsiuri} type : string the type of the sheet. ...
...if not provided, the default value is "author". istypevalid(type) verifies that the type given is a valid stylesheet's type. the values considered valid are: "agent", "user" and "author". parameters type : string the type of the sheet. returns boolean : true if the type given is valid, otherwise false. ...
test/assert - Archive of obsolete content
each test will be passed an assert object when you run the tests using jpm test. you can use this object to make assertions about your program's state. for example: var a = 1; exports["test value of a"] = function(assert) { assert.ok(a == 1, "test that a is 1"); } require("sdk/test").run(exports); globals constructors assert(logger) create a new assert object. ...
...ds ok(guard, message) tests whether an expression evaluates to true. assert.ok(a == 1, "test that a is equal to one"); this is equivalent to: assert.equal(a == 1, true, "test that a is equal to one"); parameters guard : expression the expression to evaluate. message : string optional message to log, providing extra information about the test. equal(actual, expected, message) tests shallow, coercive equality with ==: assert.equal(1, 1, "test that one is one"); parameters actual : object the actual result. expected : object the expected result. message : string optional message to log, providing extra information about the test. notequal(actual, expected, message) tests that two objects are not equal, using !=: assert.notequal(1, 2, "test that one is not two"); parameter...
util/match-pattern - Archive of obsolete content
wildcards. example pattern example matching urls example non-matching urls "http://example.com/" http://example.com/ http://example.com http://example.com/foo https://example.com/ http://foo.example.com/ wildcards a single asterisk matches any url with an http, https, or ftp scheme. for other schemes like file, resource, or data, use a scheme followed by an asterisk, as below. example pattern example matching urls example non-matching urls "*" http://example.com/ https://example.com/ ftp://example.com/ http://bar.com/foo.js http://foo.com/ file://example.js resource://me/my-addon/data/file.html data:text/html,hi there a domain name prefixed with an asterisk and dot matches any url...
... an asterisk and dot matches any url of that domain or a subdomain, using any of http, https, ftp. example pattern example matching urls example non-matching urls "*.example.com" http://example.com/ http://foo.example.com/ https://example.com/ http://example.com/foo ftp://foo.example.com/ ldap://example.com http://example.foo.com/ a url followed by an asterisk matches that url and any url prefixed with the pattern. example pattern example matching urls example non-matching urls "https://foo.com/*" https://foo.com/ https://foo.com/bar http://foo.com/ https://foo.com https://bar.foo.com/ a scheme followed by an asterisk matches all urls with that scheme. to match local files, use file://*...
Adding a Button to the Toolbar - Archive of obsolete content
to follow this tutorial you'll need to have learned the basics of jpm. to add a button to the toolbar, use the action button or toggle button modules. create a new directory, navigate to it, and execute jpm init, accepting all the defaults. ...
...button or toggle button modules. create a new directory, navigate to it, and execute jpm init, accepting all the defaults. ...
Displaying annotations - Archive of obsolete content
's unload event and on unload sends a detach message to the main module, so the add-on can clean it up. ...
... 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 do with more beautiful styling, it certainly needs a way to delete annotations, it should deal with overquota more reliably, and the matcher could be made to match more reliably. but we hope this gives you an idea of the things that are ...
Creating Reusable Modules - Archive of obsolete content
with the sdk you don't have to keep all your add-on in a single "index.js" file. you can split your code into separate modules with clearly defined interfaces between them. you then import and use these modules from other parts of your add-on using the require() statement, in exactly that same way that you import core sdk modules like page-mod or panel. it can often make sense to structure a larger or more complex add-on as a collection of modules. this makes the design of the add-on easier to understand and provides some encapsulation as each module will export only what it chooses to, so you can change the internals of the module without breaking its users. ...
... }, onclick: function() { console.log(md5file(promptforfile())); } }); this works , but index.js is now getting longer and its logic is harder to understand. let's factor the file picker and hashing code into separate modules. creating separate modules filepicker.js first create a new file in "lib" called "filepicker.js". copy the file picker code into this new file, and add the following line at the end: exports.promptforfile = promptforfile; this defines the public interface of the new module. so "filepicker.js" should look like this: var {cc, ci} = require("chrome"); function promptforfile() { var window = require("sdk/window/utils").getmostrecentbrowserwindow(); const nsifilepicker = ci.nsifilepicker; var fp = cc["@mozilla.org/filepicker;1"] .createi...
List Open Tabs - Archive of obsolete content
you can download the icon here: . run the add-on, load a couple of tabs and click the button. ...
...you can download the icon here: . run the add-on, load a couple of tabs and click the button. ...
Modifying the Page Hosted by a Tab - Archive of obsolete content
to modify the page hosted by a particular tab, load one or more content scripts into it using attach() method of tab object. the job of these scripts is to interact with web content. here's a simple example: var button = require("sdk/ui/button/action").actionbutton({ id: "style-tab", label: "style tab", icon: "./icon-16.png", onclick: function() { require("sdk/tabs").activetab.attach({ contentscript: 'document.body.style.border = "5px solid red";' }); } }); to run this example, save an icon file named "icon-16.png" in add-on's "data" directory. you could download this icon: . this add-on creates a button with mozilla favicon as an icon. ...
...ttach({ contentscriptfile: self.data.url("my-script.js") }); } }); you can load more than one script, and the scripts can interact directly with each other. so you can load jquery, and then your content script can use that. loading several content script files the data assigned to contentscriptfile can be a vector. scripts will be loaded in the same order as the vector. in the following example, we are loading two scripts, first.js & second.js. both scripts will be executed in the same context, so everything publicly defined in first.js will be accessible from second.js. // index.js var self = require("sdk/self"); var tabs = require("sdk/tabs"); require("sdk/ui/button/action").actionbutton({ id: "load-several", label: "load several scripts", icon: "./icon-16.png", ...
Bootstrapped extensions - Archive of obsolete content
evant application ui elements by their id by calling document.getelementbyid(), then manipulate them to inject your ui. for example, you can get access to the menu bar in firefox with document.getelementbyid("main-menubar"). be sure that at shutdown time, you remove any user interface you've added. creating a bootstrapped extension to mark an extension as bootstrappable, you need to add the following element to its install manifest: <em:bootstrap>true</em:bootstrap> then you need to add a bootstrap.js file that contains the required functions; this should be alongside the install.rdf file in the extension's package. backward compatibility because older versions of firefox don't know about the bootstrap property or bootstrap.js file, it's not overly difficult to create an xpi that will ...
...e 7 the add-on is being upgraded. addon_downgrade 8 the add-on is being downgraded. bootstrap data each of the entry points is passed a simple data structure containing some useful information about the add-on being bootstrapped. more information about the add-on can be obtained by calling addonmanager.getaddonbyid(). the data is a simple javascript object with the following properties: property type description id string the id of the add-on being bootstrapped. version string the version of the add-on being bootstrapped. installpath nsifile the installation location of the add-on being bootstrapped. this may be a directory or an xpi file depending on whether the add-on is installed unpacked or not. ...
Forms related code snippets - Archive of obsolete content
it is supported in firefox & chrome (v8) and partially supporte...
...ned by ecmascript 6, but with different semantics. similar to variables declared with the let statement, constants declared with const will be block-scoped. we used it only for didactic purpose. if you want a full browser compatibility of this library, please replace all the const statements with the var statements. ...
QuerySelector - Archive of obsolete content
e returned object is a nodelist. ...
...d: // return array.prototype.slice.call(el.queryselectorall(selector)); } alert($('#myid').id); (note that while using the firefox web console, the above functions are available automatically.) both xul and even xml can be easily made supportable (an alternative approach to the following would be to add chromewindow.prototype or window.prototype, accessing this.document.queryselector, or following the jquery style of chaining by returning 'this' within each prototype method of $()): htmldocument.prototype.$ = function (selector) { // only for html return this.queryselector(selector); }; example: <h1>test!</h1> <script> htmldocument.prototype.$ = function (selector) { return this.queryselector(selector); }; alert(document.$('h1')); // [object htmlheadingelement] </script> xuld...
Sidebar - Archive of obsolete content
e from the main browser document (the sidebar is actually implemented as a xul browser element). this means you can't directly access the sidebar content from a script referenced from a browser.xul overlay. to access your sidebar's window or document objects, you need to use the contentwindow or contentdocument properties of document.getelementbyid("sidebar") respectively. ...
....href == "chrome://browser/content/web-panels.xul") { // act on the sidebar content only if it is the web panels } accessing the browser.xul window from a sidebar script see accessing the elements of the top-level document from a child window section of working with windows in chrome code. ...
Toolbar - Archive of obsolete content
describing the steps needed to add a toolbar button assuming you already have a working extension and know the basics of extension development: creating toolbar buttons adding button by default when you create and deploy your extension and include a toolbar button for it by overlaying the customize toolbarpalette, it is not available by default. the user has to drag it onto the toolbar. the following code will place your button on the toolbar by default. this should only be done on the first run of your add-on after installation so that if the user decides to remove your button, it doesn't show up again every time they start the application. notes insert your button by default only once, at first run, or when an extension update adds a new button. please only add your button by defaul...
...r decides to remove your button, it doesn't show up again every time they start the application. notes insert your button by default only once, at first run, or when an extension update adds a new button. please only add your button by default if it adds real value to the user and will be a frequent entry point to your extension. you must not insert your toolbar button between any of the following elements: the combined back/forward button, the location bar, the stop botton, or the reload button. these elements have special behaviors when placed next to eachother, and will break if separated by another element. /** * installs the toolbar button with the given id into the given * toolbar, if it is not already present in the document. * * @param {string} toolbarid the id of the tool...
Tree - Archive of obsolete content
); } to collapse all tree nodes just change the condition: var treeview = tree.treeboxobject.view; for (var i = 0; i < treeview.rowcount; i++) { if (treeview.iscontainer(i) && treeview.iscontaineropen(i)) treeview.toggleopenstate(i); } getting the text from the selected row assuming the given <tree>: <tree id="my-tree" seltype="single" onselect="ontreeselected()"> use the following javascript: function ontreeselected(){ var tree = document.getelementbyid("my-tree"); var cellindex = 0; var celltext = tree.view.getcelltext(tree.currentindex, tree.columns.getcolumnat(cellindex)); alert(celltext); } getting the tree item from the focused row assuming <tree id="my-tree">, you can use the following to get the tree item: var view = document.getelementbyid("my...
...r 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>. ...
View Source for XUL Applications - Archive of obsolete content
y one you should be using directly is the viewsource method. the rest of those methods should be considered private, and might become inaccessible in the future. void viewsource(aobject); methods viewsource opens a viewer to the source code for some document or uri. parameters the viewsource method takes an object as its first and only parameter. the object can include the following properties: url (required) a string url for the document to view the source of. browser (optional) the browser containing the document that we would like to view the source of. this is optional if outerwindowid is not passed. outerwindowid (optional) the outerwindowid of the content window containing the document that we want to view the source of. pass this if you want to attempt to l...
...indowid of the content window containing the document that we want to view the source of. pass this if you want to attempt to load the document source out of the network cache. linenumber (optional) the line number to focus on once the source has loaded. deprecated api this api is likely to go away in the future, and should no longer be used. the viewsource method will also accept the following arguments in place of the object: aurl a string url for the document to view the source of. apagedescriptor (optional) a "descriptor" that allows the source to be retrieved from the network cache. this is usually gotten from the nsiwebpagedescriptor interface via currentdescriptor. adocument (optional) the content document that we're attempting to load the source from. alinenumber (op...
getAttributeNS - Archive of obsolete content
while namespaced attributes are less common than namespaced elements, some standards such as xlink depend on them. note that all gecko-based browsers (including firefox) support dom:element.getattributens. this function is not necessary for gecko-based browsers. ...
... to get an xmlns for the 'xml' prefix return thisitem.getattribute('xml:'+nsatt); // prefix must be 'xml' per the specs } var attrs2, result; var attrs = thisitem.attributes; var prefixatt = new regexp('^(.*):'+nsatt.replace(/\./g, '\\.')+'$'); // e.g., xlink:href // find any prefixes with the local-name being searched (escape period since only character (besides colon) allowed in an xml name which needs escaping) for (var j = 0; j < attrs.length; j++) { // thisitem's atts // e.g., abc:href, xlink:href while (((result = prefixatt.exec(attrs[j].nodename)) !== null) && thisitem.nodename !== '#document' && thisitem.nodename !== '#document-fragment') { var xmlnsprefix = new regexp('^xmlns:'+result[1]+'$'); // e.g., xmnls:xl, xm...
Code snippets - Archive of obsolete content
a in typed arrays using c-like string functions. rosetta by default, the only possible standardized scripting language for html is ecmascript. hence, if you are going to use 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, whic...
... ...
Communication between HTML and your extension - Archive of obsolete content
what i wanted to do was have an extension "look" for something on an html page and if it found that something perform some operation on the found thing and then update the status bar with the results of the operation. ...
... var event = document.createevent("events"); event.initevent("my-custom-event", true, true); document.body.dispatchevent(event); in the code of the extension that catches the loading of a new page i added this code: var doc = aevent.originaltarget; // doc is document that triggered "onload" event // do something with the loaded page. // doc.location is a location object (see below for a link). // you can use it to make your code executed on certain pages only. if (doc && doc.addeventlistener) doc.addeventlistener("my-custom-event", myextension.customreceived, false); since the event is dispatched after the element in the html is updated by the statuschanged function, the element that extension is looking for is there to find. ...
Custom about: URLs - Archive of obsolete content
bout generating uuid's: uuid. it is imported to queryinterface the components.manager otherwise this will not work. this example can be easily modified, just modify the global const at in the // globals section. in bug 1254752 things changed for firefox 48 and up. services.io.newchannel was deprecated, and the signature of the newchannel method changed. this change is reflected in the code below. this code will work for all versions of firefox 4 and up. const {classes: cc, interfaces: ci, manager: cm, results: cr, utils: cu, constructor: cc} = components; cm.queryinterface(ci.nsicomponentregistrar); components.utils.import("resource://gre/modules/services.jsm"); // globals const aboutpage_description = 'this is my custom about page'; const aboutpage_id = 'aa132730-2278-11e5-867f-0800...
... return components.id(`{${aboutpage_id}}`); } static get classdescription() { return aboutpage_description; } static get contractid() { return `@mozilla.org/network/protocol/about;1?what=${aboutpage_word}`; } static get queryinterface() { return xpcomutils.generateqi([ci.nsiaboutmodule]); } constructor() { object.freeze(this); } geturiflags(auri) { return ci.nsiaboutmodule.allow_script; } newchannel(auri, asecurity_or_aloadinfo) { let channel; if (services.vc.compare(services.appinfo.version, '47.*') > 0) { const uri = services.io.newuri(aboutpage_uri, null, null); // greater than or equal to firefox48 so asecurity_or_aloadinfo is aloadinfo channel = services.io.newchannelfromuriwithloadinfo(uri, asecurity_or_aloadinfo); } else { ...
Default Preferences - Archive of obsolete content
remember that preferences are held in two separate trees. one with user supplied prefs, another with default prefs. user supplied prefs are set using the gui and also by modifying a profile's prefs.js file (which uses the user_pref() function). default preferences are set similarly but inside an extension and use the pref() function. ...
...fest, default preferences must be in very particular spot: | extension root +--|content +--|skin +--|defaults +--|preferences to add preferences simply drop a .js file into that directory and mozilla will read it and set the appropriate preferences. the actual file, despite having .js extension, is not a javascript file. you may not set variables inside of it, nor may do any kind of program flow control (ifs, loops etc.) nor even calculated values (i.e. 3600 * 24 * 5). doing so will cause mozilla to stop processing your preferences file without any notification, warning, error, or exception. think of it more as an .ini file. comments are perfectly acceptable. inside your file you set preferences using the pref() function: pref("name", "value") example: pref('extensions.defaultprefs.exam...
Downloading JSON and JavaScript in extensions - Archive of obsolete content
on practice found in many extensions is using xmlhttprequest (or some other mechanism) to download javascript or json (they are different) from a remote website. once the content has been downloaded, the extension authors proceed to use eval() to decode the string content into javascript objects. this practice is dangerous and will not, in fact, pass an amo review. so the extension will not be allowed to move out of the amo sandbox. the practice is dangerous because the decoded javascript has full chrome privileges and could perform some nasty actions. how could the javascript an extension downloads perform nasty actions? fairly easy if the webserver where the javascript is hosted were to be hijacked or compromised. it happens to the best of us. amo takes the threat very seriously. the goo...
...he javascript is hosted were to be hijacked or compromised. it happens to the best of us. amo takes the threat very seriously. the good news is there are several ways to workaround the problem. downloading json if the extension is downloading json, then the developer should be using one of the json decoding methods discussed here and not using eval() at all. 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 usua...
Installing Extensions and Themes From Web Pages - Archive of obsolete content
there are a variety of ways you can install extensions and themes from web pages, including direct linking to the xpi files and using the installtrigger object. extension and web authors are encouraged to use the method described below to install xpis, as it provides the best experience to users. web script example <script type="application/javascript"> <!-- function install (aevent) { for (var a = aevent.target; a.href === undefined;) a = a.parentnode; var params = { "foo": { url: aevent.target.href, iconurl: aevent.target.getattribute("iconurl"), hash: aevent.target.getattribute("hash"), tostring: function () { return this.url; } } }; installtrigger.install(params); return false; } //--> </script> <a href="http://www.exam...
...you could also use the old style parameter block ({ "foo": aevent.target.href }) if you wanted - and didn't have an icon to use for the confirmation dialog. installtrigger.install is then called to install the item with the parameter block. return false; this last part is the most important - the install function must return false so...
Migrating raw components to add-ons - Archive of obsolete content
historically, firefox has allowed third party contributions to be added to the application's components/ directory, but beginning with firefox 3.6, this is no longer permitted. components added in this way are invisible to users and cannot be managed through the firefox add-ons manager. what's worse, though, is that these components don't have a mechanism for specifying the versions of firefox with which they are compatible, leading to poor integration and instability as users upgrade their firefox installations. the firefox extension mechanism allows you to do everything that you could do through direct component drops, but also gives you and your users extra flexibility and more sophisticated versioning support. as we roll this new behavior out, this document will be updated with additiona...
..., we have documented a set of best practices. javascript c-types some add-on authors create 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. ...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
()) { browser = browsers.getnext().queryinterface(components.interfaces.nsidomwindowinternal); browser.browsertrytoclosewindow(); } this method returns an overview of the specified window type in the form of an iterator pattern object called nsisimpleenumerator. ...
... in order to work with local files, first you need to create a nsilocalfile object representing the local file, as shown in listing 6. ...
Adding menus and submenus - Archive of obsolete content
menu items, one of them being a menu with 3 child items. you can also have menus that are filled dynamically. instead of setting the menupopup directly in the xul, you can use the onpopupshowing event to fill the children when the popup is about to be displayed. dom functions like createelement and appendchild can be used to accomplish this. if you have nothing to show on a menu, you should follow the standard used in firefox: show a single disabled item with an "(empty)" label. if filling your menu takes a noticeable amount of time, you should not make firefox (and your users) wait for it to fill up before displaying anything. it's best to show an item with a throbber image (see chrome://global/skin/icons/loading_16.png) so the user knows there's something going on, and asynchronously fi...
...ulschoolhello-hello-menu" label="&xulschoolhello.hello.label;" accesskey="&xulschoolhello.hellomenu.accesskey;" insertafter="javascriptconsole,devtoolsseparator"> <menupopup> <!-- your menuitem goes here. --> </menupopup> </menu> </menupopup> now let's look at some specialized types of menu items. menu types checkbox menu items you can make a menuitem "checkable" to allow the user to enable/disable options using the menu. we use two attributes for this: type and checked. the type attribute must be set to "checkbox". you can set the checked attribute to "true" to check it by default. the item's checked state changes when the user clicks on it. an example of one such item is the view > status bar item in the main firefox menu. radio menu items if you need to have...
Useful Mozilla Community Sites - Archive of obsolete content
« previous the mozilla community is very rich and active. it's a very powerful tool you have when developing on top of the mozilla platform, and you should take advantage of it in order to create a truly successful add-on . 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. ...
...illa applications. this is the best way to get your extension to users from all around the world. adding your extension to amo 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...
Performance best practices in extensions - Archive of obsolete content
arized to the extent that doing so increases clarity, and loading of large or expensive chunks of code fragments can be significantly deferred. defer everything that you can most extensions have a load event listener in the main overlay that runs their startup functions. do as little as possible here. the browser window is blocked while your add-on's load handler runs, so the more it does, the slower firefox will appear to the user. if there is anything that can be done even a fraction of a second later, you can use an nsitimer or the window.settimeout() method to schedule that work for later. even a short delay can have a big impact. general performance tips avoid creating memory leaks memory leaks require the garbage collector and the cycle collector to work harder, which can signifi...
...s 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. for example, bug 719601 featured a "system principal" javascript compartment containing 100s of mbs of memory, which is much larger than usual. avoid writing slow css read the "writing efficient css" guide. remember that any selector in your rule which might match many different nodes is a source of inefficiency during either selector matching or dynamic update processing. this is especially bad for the latter if the selector can dynamically start or stop matching. avoid unqualified ":hover" like the plague. avoid dom mutation event listeners dom mu...
Supporting search suggestions in search plugins - Archive of obsolete content
notation (json) given a search term. when the browser wants to fetch possible matches for a search term, it then sends an http get request to the url specified by the <url> element. your server should then decide upon the suggestions to offer using whatever means it sees fit, and return a json array of results: query string the first element in the array is the original query string. this allows firefox to verify that the suggestions match the current search term. completion list an array of suggested search terms. the array should be enclosed in square brackets. for example: ["term 1", "term 2", "term 3", "term 4"] descriptions this optional element is an array of descriptions for each of the suggestions in thecompletion list . these can be any additional information the sear...
... search plugin's xml description. query urls are not supported in firefox, and are ignored. this enhancement request - the handling of a selected suggestion, namely calling of a full specified url as proposed in the opensearch standard - is tracked in bug 386591. for example, if the search term is "fir", and you don't need to return descriptions or alternate query urls, you might return the following json: ["fir", ["firefox", "first choice", "mozilla firefox"]] note that in this example, only the query string and completion array are specified, leaving out the optional elements. your completion list can include as many suggestions as you like, although it should be kept manageable, given that the display will be updating live while the user is typing their search string. in addition, t...
Updating addons broken by private browsing changes - Archive of obsolete content
after reading this document, contact josh matthews with further questions or clarifications, or file a bug if your extension has stopped working due to a change described here and you are having trouble updating it. ...
...movegroupedprefs, removeprefsbyname, getprefs, and getprefsbyname all take a required nsiloadcontext argument to indicate the privacy status of the pref in question. use privatebrowsingutils.getprivacycontextfromwindow(win) to obtain it from the relevant window. nsidownloadmanager/nsidownload: integer download ids (and specifically the id property of nsidownload) are deprecated, and don't allow access to private downloads. all downloads now use guids, and contain a new guid property. nsidownload now has retry, cancel, remove, pause, and resume methods which should be used instead of deprecated similarly-named nsidownloadmanager methods. nsidownload's getdownload method is deprecated; use the asynchronous getdownloadbyguid method instead. nsidownloadmanager now has activeprivatedownlo...
Using Dependent Libraries In Extension Components - Archive of obsolete content
d libraries (for example, libraries provided by a third party). the firefox extension system does not provide automatic support for loading these dependent libraries, but it is possible to load these libraries explicitly using a component stub. the basic strategy of the stub is to dynamically load the dependent libraries, then load the component library and continue registration. sample code is below, and can be built by placing the two files in extensions/stub and configuring with --enable-extensions=stub extension file structure using the stub slightly changes how components are packaged in the extension directory structure. note that the "real" component is no longer in the components/ directory, it is in the libraries/ directory. extension-directory/install.rdf extension-directory/librari...
...(lib, ns_get_module_symbol); if (!getmoduleproc) return ns_error_failure; return getmoduleproc(acompmgr, alocation, aresult); } extensions/stub/bdsstubloader.cpp (for mac os x) the code as written above won't work for mac os x. dependant libraries on the mac must be loaded with a special system function nsaddimage() 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...
Using the Stylesheet Service - Archive of obsolete content
replace it with the url of the css file you want to load. ...
...heetservice.idl. the stylesheets registered with this api apply to all documents; firefox 18 extended nsidomwindowutils with loadadditionalstylesheet() and removeadditionalstylesheet() to manage stylesheets for a specific document (bug 737003). the examples in this document are all written in javascript using xpcom. using the api the string "chrome://myext/content/myext.css" in the examples below is just an example. replace it with the url of the css file you want to load. you can replace user_sheet with agent_sheet or author_sheet, depending where in the css cascade you want the sheet to be placed. see the css specification for more details. note that ua stylesheets are allowed to do certain unsafe things that user stylesheets are not allowed to do. in particular, they can apply style...
Adding preferences to an extension - Archive of obsolete content
(output.length) { // remove any whitespace from the end of the string output = output.replace(/\w*$/, ""); // build the tooltip string var fieldarray = output.split(","); samplepanel.label = symbol + ": " + fieldarray[1]; samplepanel.tooltiptext = "chg: " + fieldarray[4] + " | " + "open: " + fieldarray[5] + " | " + "low: " + fieldarray[6] + " | " + "high: " + fieldarray[7] + " | " + "vol: " + fieldarray[8]; } } var httprequest = new xmlhttprequest(); httprequest.open("get", fullurl, true); httprequest.onload = inforeceived; httprequest.send(null); } } note that we use stockwatcher.tickersymbol here instead of this.tickersymbol to get the stock symb...
...arpanel id="stockwatcher2" label="loading..." context="stockmenu" onclick="stockwatcher.refreshinformation()" /> </statusbar> now when the user clicks on the status bar panel, the stock information refreshes, but when they right-click on it, a context menu pops up. defining the menu is also easy. ...
Creating a status bar extension - Archive of obsolete content
t, read the install manifests section. the chrome manifest the chrome manifest is a file that tells the target application where to look for the chrome package for your extension. the chrome is the set of user interface elements outside the content area of the application's window, such as toolbars, status bars, menu bars, and the like. the chrome manifest file, chrome.manifest, for the sample follows. content status-bar-sample-1 chrome/content/ # firefox overlay chrome://browser/content/browser.xul chrome://status-bar-sample-1/content/status-bar-sample-1.xul the first line registers the location on disk of the contents of the extension whose id is "status-bar-sample-1". this path is relative to the extension's root folder in this case, but can be absolute if you want it to be. the secon...
...there.is.only.xul"> <!-- firefox --> <statusbar id="status-bar"> <statusbarpanel id="status-bar-sample-1" label="hello world" tooltiptext="sample status bar item" /> </statusbar> </overlay> the first order of business in the status-bar-sample-1.xul file is to establish that this is in fact a xul file, and to set up a unique id for the overlay. this is accomplished by the following line of xml: <overlay id="status-bar-sample-1-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> once that's accomplished, we can describe our user interface. in this case, we're simply inserting a new panel into the status bar at the bottom of firefox browser windows. we do this by embedding inside the statusbar named "status-bar" -- which is the firefox browse...
MozOrientation - Archive of obsolete content
warning: this experimental api was removed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3), when support for the standard deviceorientationevent was implemented. you should use that api instead. an event that is repeatedly fired on the window as accelerator data is provided to the browser. note: this below describes how these values worked for the now obsolete mozorientation. the x axis represents the amount of right-to-left tilt. this value is 0 if the device is level along the x axis, and approaches 1 as the device is tilted toward the left, and -1 as the device is tilted toward the right. the y axis represents the amount of front-to-back tilt. the value is 0 if the device is level along the y axis, and approaches 1 as you tilt the devic...
... notes this event is only dispatched if an accelerometer is available on the current device. specification not part of any specification. ...
Environment variables affecting crash reporting - Archive of obsolete content
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. ...
...hes 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. you must use this to enable crash reporting on linux debug builds. additionally, on mac os x, you can set an application default setting to allow apple's crash reporter tool to run alongside the breakpad crash reporter. run this on the command line: defaults write org.mozilla.firefox oscrashreporter 1 note that you will get two crash dialogs with this setting, one from the os and one from mozilla. ...
Installing plugins to Gecko embedding browsers on Windows - Archive of obsolete content
es these keys to the registry, and so does the mozilla installer (for versions after mozilla 0.9.1). other major commercial browsers based on gecko have committed to providing these keys as well. some gecko-based browsers provide additional information via the registry, and where appropriate, these registry keys are also mentioned, with the necessary version caveats. much of this registry data follows as a consequence of the discussions in bug 109402. to find the plugins directory applicable to netscape 6.1, 6.2.x, netscape 7.0 (and up), mozilla 1.0, and compuserve 7.0 this section details the suggested 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 moz...
...rs exist as well; all gecko-based browsers are encouraged to write these keys, so that plugin vendors can write plugin installers that install correctly to all gecko-based browsers. to find the path to the browser executable (exe) applicable to netscape 6.1, 6.2.x, netscape 7.0 (and up), mozilla 1.0, and compuserve 7.0 finding the browser executable is useful if you wish to launch the browser following installation of the plugin dll. 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_curr...
No Proxy For configuration - Archive of obsolete content
d bugs. audience mozilla users, mozilla developers, mozilla testers. overview as browsers rapidly grew in popularity in the mid-90's, many network administrators added proxy servers. initially, proxy servers were used for access control and performance. many networks had limited access to the public network via proxy servers. because the public network was small in scope and connections were slow, a caching proxy could often improve the overall performance. this feature was originally designed as a "blacklist" of sites or domains that was within the intranet, and should not be accessed via the proxy server. due to various limitations, this feature should be used for only the most simple blacklist scenarios. in almost all cases, pac gives better control and flexibility. user interface "...
... into "no proxy for" ...for example use... ...
Same-origin policy for file: URIs - Archive of obsolete content
specifically, a file can read another file only if the parent directory of the originating file is an ancestor directory of the target file. directories cannot be loaded this way, however. ...
...if bar.html is either in the same directory as index.html or in a directory contained within the same directory as index.html. this policy affects anything that does same-origin checks, including xmlhttprequest, xslt, and xbl. for cross-window dom access, each file is treated as a separate origin, with one exception: if a file is loaded from another file that would otherwise be able to load it following this same-origin policy, they are considered to have the same origin. this load can occur through a subframe, link, location set, call to window.open(), or the like. for example, if the file /home/user/foo.html is a frameset and one of the frames is /home/user/subdir/bar.html, the frame and frameset are considered to share the same origin. on the other hand, if the file /home/user/subdir/foo...
Visualizing an audio spectrum - Archive of obsolete content
nsform (fft) spectrum data for the playing audio. the function handling the loadedmetadata event stores the metadata of the audio element in global variables; the function for the mozaudioavailable event does an fft of the samples and displays them in a canvas. note: you can use the audionode called analysernode to perform real-time fft analysis on an audio stream, rather than the code shown below. <!doctype html> <html> <head> <title>javascript spectrum example</title> </head> <body> <audio id="audio-element" src="song.ogg" controls="true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2...
... fft.spectrum[i] * 4000; // draw rectangle bars for each frequency bin ctx.fillrect(i * 4, canvas.height, 3, -magnitude); } } var audio = document.getelementbyid('audio-element'); audio.addeventlistener('mozaudioavailable', audioavailable, false); audio.addeventlistener('loadedmetadata', loadedmetadata, false); // fft from dsp.js, see below var fft = function(buffersize, samplerate) { this.buffersize = buffersize; this.samplerate = samplerate; this.spectrum = new float32array(buffersize/2); this.real = new float32array(buffersize); this.imag = new float32array(buffersize); this.reversetable = new uint32array(buffersize); this.sintable = new flo...
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
the control itself is implemented in a dll called pluginhostctrl.dll which is standalone from the rest of the mozilla project. 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. assuming you have cvs somewhere in your path, type this from a command prompt: c:\> set cvsroot=:pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot c:\> set home=\temp c:\> cvs login (logging in to anonymous@cvs-mirror.mozilla.org) cvs password: anonymous c:\> cvs -z3 co mozilla/embe...
...com/some_movie.mov"/> <!-- custom arguments --> <param name="loop" value="true"/> </object> the classid attribute tells ie to create an instance of the plug-in hosting 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 contro...
Autodial for Windows NT - Archive of obsolete content
annot be reached. however, this service will won't function if you have a lan card installed, unless that particular address has been accessed in the past via a dialup connection. origin of the bug before the implementation of the autodial helper feature, mozilla would trigger the autodial feature on nt-based operating systems, but only if certain conditions are met. these conditions are as follows: the autodial service is running control panel | network connections | advanced | dialup preferences | enable autodial by location is set for some location a dialup connection has been configured there is no lan connected or the dialup connection has been used to access the internet address in question. most systems are not set up correctly for this to happen, and most users have no idea h...
...re altogether by setting the pref network.autodial-helper.enabled to false. since the feature was implemented close to the release of netscape 7, the pref was added so that we could include the feature in the 7.0 release with the feature turned off and enable it in specific cases. the feature was turned on in mozilla 1.1 to get more exposure. mozilla 1.1 also includes a fix to bug 157733, 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 ...
Enabling quicklaunch for all users - Archive of obsolete content
enabling quicklaunch for all users unlike all other settings, quicklaunch is stored in the windows registry. to enable it, just load the following registry script into the user's windows registry: quicklaunch.reg. ...
... enabling quicklaunch for all users unlike all other settings, quicklaunch is stored in the windows registry. to enable it, just load the following registry script into the user's windows registry: quicklaunch.reg. ...
How Mozilla finds its configuration files - Archive of obsolete content
ow mozilla finds its configuration files mozilla looks into the binary %userprofile%\application data\mozilla\registry.dat file for its "registry", which contains, amongst other information, a pointer to the directory where the profile is stored (located at common/profiles/profilename/directory. ...
...usage: ./readmozprofile.pl < registry.dat >registry.xml a program to convert the xml file back into the binary registry.dat file. ...
How Thunderbird and Firefox find their configuration files - Archive of obsolete content
rbird\profiles.ini file for its "registry", which contains, amongst other information, a pointer to the directory where the profile is stored (usually located in %appdata%\thunderbird\profiles\profilename). likewise, firefox uses a similar file, located in %appdata%\mozilla\firefox\profiles.ini. the value contained in this key is a litteral value, no variables (such as %userprofile%/mozprofile) allowed. we chose to point this to the user's home directory (h:\thunderbird). the configuration itself is stored in the specified directory, in a file named prefs.js. this is a readable file of javascript commands. all other files in that directory are dynamically created by mozilla on first start. unlike mozilla's binary registry.dat file, thunderbird's and firefox' profiles.ini file is a readable te...
...lastprofile=1 [profile0] name=default isrelative=1 path=profiles/default.uda if you want to point this to a location of your choice (for example h:\thunderbird), you need to perform to changes: set isrelative to be 0 update the path to point to the desired place. note: for absolute paths thunderbird uses dos'ish backslashes (\) rather than unixish slashes (/). you'd obtain a file such as the following: [general] startwithlastprofile=1 [profile0] name=default isrelative=0 path=h:\thunderbird a discussion about this file can be found here ...
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
ion-yourfiletype" or be officially registered with iana (unlikely) or be a standard type (e.g. if you want to play mpeg files). file extension reflects the data type handled by the plugin, esp. when loaded from local disk on windows. build create a new project in visual studio for a win32 gui library (dll) (in .net 2003: win32 template, then switch to dll in application settings in the following dialog, export symbols too?)(in visual studio 2008, it is visualc++|win32|win32 project, then check dll in the wizard). if a wizard gives you a checkbox to create an empty project, then check it. otherwise you'll delete files later. again note that the resulting dll filename must start with "np", so either call your project like this or rename the file later delete the .cpp and .h and readm...
... to "resource files"). samples can be obtained from: https://developer.mozilla.org/en/plugins/samples_and_test_cases get the npapi sdk. add the npapi sdk include path (example : c:\npapi-sdk\headers) to project properties|(all configurations)|c++|general|additional include directories. note: if your project is still empty, the c++ tree might not be visible. so, add some files first. add the following preprocessor definitions to project properties|(all configurations)|c++|preprocessor|preprocessor definitions: win32;_windows;xp_win32;xp_win;_x86_;npsimple_exports disable precompiled headers using project properties|(all configurations)|c++|precompiled headers|create/use precompiled header. they may be already disabled. define the function exports by adding the .def filename (e.g. nprt.def...
Drag and Drop Example - Archive of obsolete content
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 the board is at the top-left corner of the window. the label attribute is set to the data from the drag also so that the button has a default label. this example is f...
...g also so that the button has a default label. this example is fairly simple. one possible change is to use a custom flavour for the data instead of text. the problem with using text is that if the text from an external drag just happens to be set to button, a button will be created on the board. a custom type means that the board will only accept drags from the palette. ...
Fast Graphics Performance With HTML - Archive of obsolete content
make content that has scrolling content underneath it opaque e.g. use <div><div style="background:white; position:fixed">simple</div>lots of text...</div> instead of <div><div style="position:fixed">simple</div>lots of text...</div> make the content of scrollable sub frames opaque e.g. ...
...v><div style="background:white; position:fixed">simple</div>lots of text...</div> instead of <div><div style="position:fixed">simple</div>lots of text...</div> make the content of scrollable sub frames opaque e.g. ...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
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 calls to load a new...
...ea alt="necko" coords="721,113,821,157" href="#necko"> <area alt="nsuriloader" coords="23,335,215,455" href="#nsuriloader"> <area coords="227,515,485,575" href="#nsiuricontentlistener"> <area alt="nsdocshell" coords="47,83,203,153" href="#nsdocshell"></map> this block diagram is out of date as of january 2012 with regard to some minor control flow shuffling in nsuriloader. 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 calls to load a new uri. these can come in via nsiwebnavigation (a script...
Help Viewer - Archive of obsolete content
help viewer: allows information to be shown to the user inside mozilla. introduction computers and software are incredibly complex. naturally, then, everyone needs a little help now and then, and getting that help to the user is critical to making applications useful. consequently, the mozilla platform provides a cross-platform help viewer along with a framework for providing built-in help documentation. mozilla's help viewer makes providing documentation an easy job, and this document will describe how you can use it. ...
...consequently, the mozilla platform provides a cross-platform help viewer along with a framework for providing built-in help documentation. ...
popChallengeResponse - Archive of obsolete content
er. use <keygen> or the future web crypto api instead. resultstring = crypto.popchallengeresponse("challengestring"); argument description "challengestring" a base-64 encoded cmmf popodeckeychallcontent message. the current implementation does not conform to that defined in the cmmf draft, and we intend to change this implementation to that defined in the cmc rfc.. see below for the current implementation. the resultstring will either be a base-64 encoded popodeckeyrespcontent message, or one of the following error strings: error string description "error:invalidparameter:xxx" the parameter xxx was an invalid value. "error:internalerror" the software encountered some internal error, such as out of memory challenge-respo...
...e used). witness octet string, -- the result of applying the one-way function (owf) to a -- randomly-generated integer, a. [note that a different -- integer must be used for each challenge.] sender generalname, -- the name of the sender. key octet string, -- the public key used to encrypt the challenge. this will allow -- the client to find the appropriate key to do the decryption. challenge octet string -- the encryption (under the public key for which the cert. -- request is being made) of rand, where rand is specified as -- rand ::= sequence { -- int integer, -- - the randomly-generated integer a (above) -- senderhash octet string ...
Settings - Archive of obsolete content
jetpack will automatically generate a user interface based on the specification. the settings persist across browser sessions and are stored using the jetpack [simple storage api][]. settings are private to each jetpack and are not accessible by other jetpacks. because it is still under development, the api currently lives in the future and must be imported before it is used: specifying settings in a manifest to specify its settings, a jetpack defines a variable named manifest in its global namespace before it imports the settings api. the value of this variable must be an object that contains a property named settings. ...
... "secret" } ] }, { name: "music", type: "boolean", label: "music", default: true }, { name: "volume", type: "range", label: "volume", min: 0, max: 10, default: 5 } ] }; // import after defining manifest! jetpack.future.import("storage.settings"); this definition will result in a user interface with an input field for each setting defined above. ...
Settings - Archive of obsolete content
jetpack will automatically generate a user interface based on the specification. the settings persist across browser sessions and are stored using the jetpack simple storage api. ...
... "secret" } ] }, { name: "music", type: "boolean", label: "music", default: true }, { name: "volume", type: "range", label: "volume", min: 0, max: 10, default: 5 } ] }; // import after defining manifest! ...
Selection - Archive of obsolete content
tions made by the user. features can get, set, and listen for selection events in html or plain text. the namespace for this api is jetpack.selection. this api currently lives in the future and must be imported for use: jetpack.future.import("selection"); getting and setting the selection the current version of jetpack.selection includes these formats: .text and .html getting the selection the following is an example of getting the selection from the user. jetpack.import.future("selection");var textofsel = jetpack.selection.text;var htmlofsel = jetpack.selection.html; setting the selection the following is an example of getting the selection from the user. jetpack.import.future("selection");jetpack.selection.text = 'hello';jetpack.selection.html = '<b>hello</b>'; methods onselection(func func...
...f getting the selection from the user. jetpack.import.future("selection");var textofsel = jetpack.selection.text;var htmlofsel = jetpack.selection.html; setting the selection the following is an example of getting the selection from the user. jetpack.import.future("selection");jetpack.selection.text = 'hello';jetpack.selection.html = '<b>hello</b>'; methods onselection(func function)this method allows you to execute an event function when a selection is made. funca function to be called when the selection is made. this function receives no arguments. use jetpack.selection.*. function adding a selection event jetpack.selection.onselection( fn ); removal of a selection event jetpack.selection.onselection.unbind( fn ); verbose example the following example will bold the html that you select. ...
Microsummary XML grammar reference - Archive of obsolete content
hes the url of the page and none of the <exclude> expressions match the url of the page. the order in which child elements appear within the <pages> element is not significant. white space between the child element tags and the regular expressions they contain is also not significant; it is not considered part of the regular expression, and it does not affect evaluation of the expressions. ...
...to true. the interval attribute defines an absolute interval in minutes. its value must be a number greater than or equal to 1. fractional values (e.g. 5.5 minutes) are permitted, although they probably aren't useful. the <update> element may contain any number of <condition> child elements. firefox determines which interval to apply to a microsummary generated by a generator according to the following rules: firefox processes each <condition> child element in document order. for each one, firefox evaluates the element's xpath boolean expression against the page being summarized. if the expression evaluates to true, firefox applies that element's interval and stops processing child elements. thus, the first matching <condition> determines the update interval. if there are no <condition>...
Microsummary topics - Archive of obsolete content
osummary generator to programmatically install a microsummary generator -- for example, in an extension that helps users create custom generators for their favorite sites -- obtain a reference to the nsimicrosummaryservice interface implemented by the nsimicrosummaryservice component, then call its installgenerator() method, passing it an xml document containing the generator. ...
...ry requests when firefox downloads content in order to update a microsummary, it honors cache-related http response headers. thus, if you would like to control how frequently firefox initiates microsummary-related requests to your web server, you can do so by including an http expires or cache-control header in your response to a microsummary-related request. for example, you might include the following header in your response to prevent firefox from making another microsummary-related request for one hour: cache-control: max-age=3600 note: because of a technical limitation (bug 346820), firefox uses the same cache for both microsummary-related requests and user-initiated requests, so the cache headers you return apply to both. thus if your cache headers tell firefox not to refresh a page on...
Plug-n-Hack Phase1 - Archive of obsolete content
security tool manifest to support pnh-1 security tools provide a manifest over http(s) which defines the capabilities that the browser can make use of. it is up to the tool authors to decide how the url of the manifest is published. the tool configures itself by serving an html document (we’ll call this the configuration document) to the browser. this can cause the browser to inspect the manifest and register the tool by firing a customevent with the type configuresectool and a properties object which specifies the url of the tool manifest. ...
...s to another manifest which describes the commands the browser can invoke. serving manifests from outside of your tool you may want to serve manifests from a separate webserver (e.g. for testing); plug-n-hack requires tool and service manifests to be served from the same origin as the api endpoints but, for testing purposes, ringleader (the firefox addon implementation of the browser component) allows you to set a preference to relax or disable origin checks. the preference is ringleader.check.origin this can be set to 'off' to disble origin checks completely, or 'noport' to disable only port checks. security tool commands manifest an example commands manifest (for owasp zap) is: https://code.google.com/p/zap-extensions/source/browse/branches/beta/src/org/zaproxy/zap/extension/plugnhack/resou...
Bundles - Archive of obsolete content
older maybe be located in a directory that requires elevated privileges, the web application should not write data to it. the application profile directory can be used instead for this purpose. note: the webapp must have an id in order to be installed. when prism is launched with a "-webapp [bundle]" command line, the bundle must first be unpacked before the web application is launched. this can slow the overall launch time and the unpacking is redundant if the bundle has been launched previously. this is why the preferred method of launching is to use the "-webapp [webapp-id]" command line, which looks for the previously installed (unpacked) web application in the prism webapps/{webapp-id} folder. the web application is then launched without the unpacking overhead. a bundle can also be insta...
...any other files in the .webapp file will be ignored. after the .webapp file is executed the first time, these files will be unzipped and "cached" to a local directory structure. / webapp.ini webapp.js webapp.css winnt/ webapp.css darwin/ webapp.css linux/ webapp.css [icon].ico [icon].png [icon].icns ...
Extensions - Archive of obsolete content
the prism application id and the differences in the user interface (ui). extensions typically overlay the host application's ui to add toolbar buttons, menus and other features. one of prism's features is an extreme lack of ui elements, which means that trying to use the same overlays in firefox and prism is really not possible. the basics in order 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...
...s. this usually means extracting and editing the install.rdf file to add prism as a target application. you may also need to modify the extension's overlay to be able to work with the prism ui. many archive tools, like 7zip, can edit and update a file in the archive without needing to manually extract it and add it back into the xpi. installing prism supports a basic add-on user interface which allows a user to manage extensions. using this dialog, a user just launches a webapp and opens the add-ons dialog. then install the extension by either dragging and dropping the extension onto the dialog, or by clicking the “install…” button, navigating to the extension and selecting it for installation. extensions can be removed using the same dialog. ...
Styling - Archive of obsolete content
prism allows for some client-side web application styling. the web application bundle is allowed to hold a css file named webapp.css (called the webapp style). this file will be loaded into the web application content stylesheet and can override the web application's native styles. simply add the webapp.css to the bundle and it will be injected into the web application, regardless of the platform or os. it is also possible to create platform-specific styles. in this scenario, the css file is specific to an os. this allows prism webapps to take on an os-specific look. to use platform-specific styles, create a folder in the bundle archive for each supported os and place a webapp.css file in the folder. ...
...d into the web application, regardless of the platform or os. it is also possible to create platform-specific styles. in this scenario, the css file is specific to an os. this allows prism webapps to take on an os-specific look. to use platform-specific styles, create a folder in the bundle archive for each supported os and place a webapp.css file in the folder. the folder names must match the following: windows - winnt mac os x - darwin linux - linux the folder names are pulled from mozilla and are the same as those used in other mozilla projects, such as extension and xul applications. note: you can also include a root level webapp.css which will be used if a platform-specific version is not found. ...
Priority Content - Archive of obsolete content
list for the piece. if there is devedge content you think should be migrated that isn't currently on this list, feel free to add it. note: use example at sample:original document information to credit original authors. devedge devedge mirror note: if you're digging around the mirror and see anything there that you think should be migrated to devmo that isn't on this list, feel free to add it below. a raw list of everything that has not 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: de...
...tscape gecko compatibility handbook original: netscape gecko compatibility handbook wiki location: gecko compatibility handbook migrators: mathieu deaudelin there are inline examples on this page that cannot be migrated. they are dependant on some code that cannot be integrated in the page. dependant on: updating dhtml web pages for next generation browsers on devedge the tune-up wizard (see below, in the wishlist section) mostly completed: popup window controls devedge article migrators: mathieu deaudelin there are inline examples on this page that cannot be migrated. they are dependant on some style instructions that can only be placed in the header of the page. started: scripting plugins: macromedia flash original: scripting plugins: macromedia flash wiki location: scripting ...
Hacking wiki - Archive of obsolete content
or.mozilla.org:/www cvs login cvs co mozilla-org/css (when prompted to enter a password, type <tt>anonymous</tt>) setting up copy the contents of the <tt>trunk</tt> folder and the <tt>css</tt> folder (note: the folder itself) into the <tt>www</tt> directory on your server. the contents of the <tt>trunk</tt> directory you just checked out is a slightly modified mediawiki install, so you can follow the mediawiki install instructions. the <tt>css</tt> folder contains files that are supposed to be in the <tt>/css</tt> directory of the site.) to get a working install, you need to configure mediawiki. it's done by navigating to <tt>/config/index.php</tt> in your web browser. polvi claims that you'll have it, but in case you don't, you can copy one from the mediawiki tarball. once you're done wi...
...umbs.php"); include("extensions/titleoverride.php"); include("extensions/abbr.php"); include("extensions/object.php"); include("extensions/kbd.php"); ?> tbd installing/configuring rss and doxygen extensions - anything special needs to be done? the title-override / breadcrumbs extensions need an additional table created. to configure it, run <tt>update-devmo.php</tt> from the command line. the following worked for me (from the <tt>www</tt> directory): /path/to/php -f ./maintenance/update-devmo.php done you should have a working install of the mdc wiki now. if you have problems with setting up the mdc wiki (and not the web server or php or mediawiki), feel free to ask in #devmo. random tips you can set the file to log by putting something like this in your localsettings.php: $wgdebuglo...
New Skin Notes - Archive of obsolete content
ightly lighter shade) the background color of the link, this will help to make items "appear as links" to many users, possibly add a text-decoration: underline as well. --callek is it possible to remove the blank space on category pages, like category:dom?by the way, it looks like this skin has the same problem as previous - the edit box, category list on category pages, and others are always below the end of the sidebar. the major problem it caused in cavendish skin - that they were out of the screen - is solved by making the sidebar smaller, which is not the right thing to do, imo (see my comment 1).--nickolay 02:11, 25 aug 2005 (pdt) yeah this is actually a problem with mw, rather than the skin -- they use a <br style="clear:both" /> in some pretty annoying places. i'll try to get those...
...the right and is slightly too large... --mmondor 12:52, 26 aug 2005 (pdt) will revisit sidebar width later. --dria i see that it was activated as default for non-logged in people already, it appears that there is no intention whatsoever to fix this at current time, since it's been placed in this section. just so that (perhaps) this might revive the topic, a side bar shouldn't exceed 16% to allow proper viewing at 800 pixels width ideally in my opinion, i find strange that i'm the only person not too fond of large side bars (or side bars at all, for that matter :) considering that in most articles we scroll down to read the text, and that the side bar scrolls as well, the links aren't there anymore, but the width remains wasted anyway. in the case of a story book, small text columns do se...
Remote XUL - Archive of obsolete content
how to use xul delivered from a webserver, not as part of chrome. note: support for remote xul has long been a potential security concern; support for it was disabled in gecko 2.0. this also means you can't load xul using file:// urls unless you set the preference dom.allow_xul_xbl_for_file to true. however, there is a whitelist that lets you specify sites that can still use remote xul. ...
...ern; support for it was disabled in gecko 2.0. this also means you can't load xul using file:// urls unless you set the preference dom.allow_xul_xbl_for_file to true. however, there is a whitelist that lets you specify sites that can still use remote xul. the remote xul manager extension lets you manage this whitelist, which is maintained using nsipermissionmanager, by creating entries of type "allowxulxbl", like this: components.classes["@mozilla.org/permissionmanager;1"] .getservice(components.interfaces.nsipermissionmanager) .add(uri, 'allowxulxbl', components.interfaces.nsipermissionmanager.allow_action); see using remote xul. oreillynet article, part 1 oreillynet article, part 2 restrictions see remote xul bugs for needless restrictions, fea...
Remotely debugging Firefox for Metro - Archive of obsolete content
ls in firefox on the desktop. prerequisites you will need: windows 8 (metro-style) firefox running in the touch-friendly "metro" mode on a windows 8 computer. firefox running in classic "desktop" mode on windows, mac os x, or linux, either on a separate computer or in a separate profile on the same computer. ...
... this can be a security risk, especially if you also set the force-local preference to false.) set up firefox for desktop on the desktop, remote debugging is enabled by a setting in the toolbox. open the toolbox, click the "settings" button in the toolbar, and check "enable remote debugging" in the settings tab. if you're using a version of...
Safely loading URIs - Archive of obsolete content
crash the operating system in some cases. some other schemes are used internally by mozilla modules to communicate with each other. finally, some uris (e.g. chrome: give the loaded page expanded privileges. if a web page gets access to a window with such expanded privileges, it may be able to abuse it to gain access to those privileges itself. to solve this problem, gecko provides methods that allow the caller to check whether it's safe to load a particular uri. these methods are exposed on the nsiscriptsecuritymanager interface and are called checkloaduri, checkloaduriwithprincipal, and checkloaduristr. all three methods take three arguments: the first argument identifies the source of the uri, the second argument is the uri that one plans to load, and the third argument is a set of flags t...
...e source of the uri. so if you're implementing a context menu and you add a "view image" option, the source of the image uri would be the page the image is in, not the chrome document the context menu code is in. differences between the methods the three methods differ from each other in how the source of the uri is identified and in what is known about the uri to be loaded. in general, the following guidelines apply for gecko 1.8: if you plan pass a uri string to nsiwebnavigation.loaduri (which can happen indirectly, e.g. by passing the string to something that loads it in a <browser> or <iframe>), you must call checkloaduristr to be secure. there's no way to do this completely securely in gecko versions prior to 1.8.0.4. if you're doing anything else (passing a uri string to some oth...
Abc Assembler Tests - Archive of obsolete content
it is possible to write tests using the abc assembler. the assembler code can be found in /utils/abcasm. tests can be found in /test/acceptance/abcasm and end with the .abs extension. the tests are run using the same runtests.py script that is used for the actionscript tests. ...
...hts reserved. * * contributor(s): * adobe as3 team * * alternatively, the contents of this file may be used under the terms of * either the gnu general public license version 2 or later (the "gpl"), or * the gnu lesser general public license version 2.1 or later (the "lgpl"), * in which case the provisions of the gpl or the lgpl are applicable instead * of those above. if you wish to allow use of your version of this file only * under the terms of either the gpl or the lgpl, and not to allow others to * use your version of this file under the terms of the mpl, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the gpl or the lgpl. if you do not delete * the provisions above, a recipient may use your ver...
Tamarin Acceptance Test Template - Archive of obsolete content
hts reserved. * * contributor(s): * adobe as3 team * * alternatively, the contents of this file may be used under the terms of * either the gnu general public license version 2 or later (the "gpl"), or * the gnu lesser general public license version 2.1 or later (the "lgpl"), * in which case the provisions of the gpl or the lgpl are applicable instead * of those above. if you wish to allow use of your version of this file only * under the terms of either the gpl or the lgpl, and not to allow others to * use your version of this file under the terms of the mpl, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the gpl or the lgpl. if you do not delete * the provisions above, a recipient may use your ver...
... // provide ecma section title or a description var bugnumber = ""; starttest(); // leave this alone /** * calls to addtestcase here. addtestcase is a function that is defined * in shell.as and takes three arguments: * - a string representation of what is being tested * - the expected result * - the actual result * * for example, a test might look like this: * * var helloworld = "hello world"; * * addtestcase( * "var helloworld = 'hello world'", // description of the test * "hello world", // expected result * helloworld ); // actual result * */ // add your tests here var helloworld = "hello world"; addtestcase( "var helloworld = 'hello world'", "hello world", helloworld ); test(); // leave this alone. th...
Cmdline tests - Archive of obsolete content
see test/cmdline/readme document for more information. ...
...see test/cmdline/readme document for more information. ...
Tamarin Acceptance Testing - Archive of obsolete content
in order to ensure that changes to the tamarin code base are high quality before submitting, all developers are required to complete the following steps. ...
... in order to ensure that changes to the tamarin code base are high quality before submitting, all developers are required to complete the following steps. ...
Using cross commit - Archive of obsolete content
getting the script "make -f client.mk pull_all" from a working copy of the trunk now pulls cross-commit, and that'll work on the 1.8 branch soon, too, so you might already have the script. if you don't, however, then from the parent directory of your source dir, do: cvs co mozilla/tools/cross-commit note that you will need to have $cvsroot and such set up correctly for this to work. ...
...ross-commit will end up waiting forever for you to type a cvs checkin message in an editor that it never shows you! (although it works without specifying -m on the command line if you are using x-enabled emacs on linux.) also note that if you don't specify any branches to commit on, cross-commit will commit to the trunk and the mozilla_1_8_branch by default. details cross-commit accepts the following options: all cvs options (those to the left of the specific cvs command) and cvs commit options (those to the right of a commit command), although the -r and -f cvs options need to be specified as --cvs-r and --cvs-f to avoid conflict with the similarly named (but different in meaning) cvs commit options. you can list the files/directories you want it to commit on the command line or leave ...
Using gdb on wimpy computers - Archive of obsolete content
of memory. how do i fix it? if your computer has less than 256 mb of memory, your computer will become unhappy as gdb loads mozilla's shared libraries. the solution to this is to delay loading shared libraries until they are actually needed. however, you need to make sure that the base libraries like libc and pthreads are loaded before you tell gdb to stop loading shared libraries. if you don't allow those libraries to be loaded then gdb will not be able to properly debug threads on linux. mozilla uses pthreads for its networking library so you need to be able to work in a threaded environment. the best way to do this is to set a breakpoint in main, let the program run until main and then turn off automatic library loading. from there you can allow the program to continue running. here's an e...
...this has been fixed in version 5 of gdb. there isn't a fix for older versions. ...
Venkman - Archive of obsolete content
debugger functionality implemented in c. bandhauer then went on to reflect that api into java, and create his cross platform front end, eventually producing netscape javascript debugger 1.0 and 1.1. in april of 2001, robert ginda began work on a javascript debugger for mozilla, called venkman. venkman builds on the js/jsd portion of john's 1998 work, exposing it as an xpcom component. this allows the user interface be written in javascript and xul, which allows venkman to be fully cross-platform. venkman is named after the character dr. peter venkman, played by bill murray in the movies ghostbusters and ghostbusters ii. getting venkman firefox and thunderbird the latest version of javascript debugger is available from firefox add-ons. ...
...choose advanced install. also available from firefox add-ons as an extension. nvu and kompozer javascript debugger extension version 0.9.84 is available from nvu's downloads page. we encourage you to use the latest available version 0.9.87.1 (or higher) with firefox instead. source code the source code for venkman may be found in mercurial at the following url: http://hg.mozilla.org/venkman/summary community view mozilla forums... mailing list newsgroup rss feed irc: #venkman on irc.mozilla.org report a bug in venkman if you find a problem with venkman, please follow directives mentioned at venkman faq section 5.4 and then you may report a bug on javascript debugger component. rela...
XBL 1.0 Reference - Archive of obsolete content
t...
... this example is targeted t...
XML in Mozilla - Archive of obsolete content
inly to localize mozilla to different languages (the ui strings are stored in external dtd files). another exception is an entity whose system identifier is a relative path, and the xml declaration states that the document is not standalone (default), in which case mozilla will try to look for the entity under <bin>/res/dtd directory. mozilla may also make an exception with xhtml documents, see below. mozilla will read internal (dtd) subsets, and in special circumstances external dtds as explained above and will use this information to recognize id type attributes, default attribute values, and general entities. other notes a lot of the document object model (dom, w3c recommendations and drafts) applies to xml. likewise, the cascading style sheets (css, w3c recommendations and drafts) style l...
...d above and will use this information to recognize id type attributes, default attribute values, and general entities. other notes a lot of the document object model (dom, w3c recommendations and drafts) applies to xml. likewise, the cascading style sheets (css, w3c recommendations and drafts) style language can be used to style xml documents. the code for most the core xml can be found in the following directories on the mozilla mercurial repository: content/xml/, parser/expat/ and parser/htmlparser/. the newsgroup to discuss xml in mozilla depends a bit on the nature of the question. for example, dom related questions should probably be discussed in the mozilla.dev.tech.dom newsgroup, while style issues should be discussed on mozilla.dev.tech.css and so on. the catch-all newsgroup for xml d...
Install Wizards (aka: Stub Installers) - Archive of obsolete content
ds used to install mozilla are lightweight stubs targeted to be around 200 kb disk footprint. users download the stub installers, choose which packages to install, choose the destination directory for the installation, and select from various other options. subsequently, when users click the "install" button the install wizard downloads and installs only the selected software packages. this saves low-bandwidth users considerable time since they do not need to download software packages they may not be interested in. (the stub installer accomplishes this by downloading the xpinstall engine along with the selected software packages. it then proceeds to extract the xpinstall engine and feed it the downloaded software packages to install.) the stub installer code includes: the logic to display...
...sses user selections the code that calls the xpinstall engine through xpistub the libxpnet code that is statically linked in the stub installers are written in code native to the platform using native widget toolkits including the windows api for windows, the mac toolbox for the mac, and gtk for the unix version. to learn more about the three platform-specific versions of the stub installer follow the links below: unix stub installer mac stub installer windows stub installer what do we mean by xpistub? the xpinstall engine is not called directly by the stub installer. the stub installer calls some glue code: xpistub which resides at: < http://lxr.mozilla.org/seamonkey/sou...pinstall/stub/> this "glue" code initialized xpcom and registers the xpinstall engine and requisite components...
Install script template - Archive of obsolete content
/** doron rosenberg -- doronatnospamallowedherenetscape.com arun k. ranganathan -- aruneratnospamallowedherenetscape.com petter ericson -- petteratnospamallowedherecycore.com this is an install.js file that does the following -- 1. installs to the current browser that is invoking the installation 2. additionally installs to a secondary location on the windows desktop, in this case c:\winnt\system32\myplugin\ 3. writes registry keys exposing the above secondary install location for other browsers to find. ...
... the current browser that is invoking the installation 2. additionally installs to a secondary location on the windows desktop, in this case c:\winnt\system32\myplugin\ 3. writes registry keys exposing the above secondary install location for other browsers to find. ...
getFolder - Archive of obsolete content
summary returns an object representing one of the standard directories. method of install object syntax filespecobject getfolder ( string foldername); filespecobject getfolder ( string foldername, string subdirectory); filespecobject getfolder ( object localdirspec, string subdirectory); parameters the getfolder method has the following parameters: foldername a string representing one of netscape's standard directories. there are two sets of possible values for this parameter. the first set contains platform-independent locations; the second set contains platform-specific locations. you are encouraged to use the platform-independent locations. see the list in the description section for the two sets of locations. subdirectory a strin...
... getcomponentfolder or getfolder. returns a filespecobject representing one of netscape's standard directories, or null in case of error or if subdirectory refers to a file that already exists. description the getfolder method obtains an object representing one of netscape's standard directories, for use with the addfile and getwinprofile methods. ...
getLastError - Archive of obsolete content
getlasterror returns the most recent nonzero error code. method of install object syntax int getlasterror (); parameters none. returns the most recent nonzero error code. for a list of possible values, see return codes. description use getlasterror method to obtain the most recent nonzero error code since initinstall or reseterror were called. ...
...return codes. description use getlasterror method to obtain the most recent nonzero error code since initinstall or reseterror were called. this method allows you to defer checking for error codes each time you call addfile or adddirectory until the last addfile or adddirectory call. the getlasterror method does not return errors from methods that return objects, such as getfolder. ...
buttons - Archive of obsolete content
this button will also be the default button. cancel: the cancel button which will cancel the operation. help: a help button for displaying help about the dialog. disclosure: a button to show more information. this might be a button or a disclosure triangle. ...
...this button will also be the default button. cancel: the cancel button which will cancel the operation. help: a help button for displaying help about the dialog. disclosure: a button to show more information. this might be a button or a disclosure triangle. ...
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. ...
... 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. 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. ...
crop - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › crop
an ellipsis will be used in place of the cropped text. if the box direction is reversed, the cropping is reversed. start the text will be cropped on its left side in left-to-right text locales, and the right side in right-to-left locales. end the text will be cropped on its right side in left-to-right text locales, and the right side in right-to-left locales. ...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. ...
dlgtype - Archive of obsolete content
cancel the cancel button which will cancel the operation. ...
... used only when the button is in a dialog box. you can use this feature to replace the standard dialog box buttons with custom buttons, yet the dialog event methods will still function. for example, if the dlgtype is set to accept, the button will replace the dialog box's accept button, which is usually labeled ok. using this attribute on a button that is not in a dialog box has no effect. the following values can be used as the dialog type: accept the ok button, which will accept the changes when pressed. cancel the cancel button which will cancel the operation. help a help button for displaying help about the dialog. disclosure a button to show more information. this might be a button or a disclosure triangle. extra1 an optional additional button. extra2 a second...
onchange - Archive of obsolete content
« xul reference home overview an onchange attribute is an event listener to the object for the event change. a change event is fired in different ways for different xul input elements as listed below: onchange type: script code textbox when enter key is pressed radio/check box when the state is changed select list when the selected item is changed what is accessible the script context at this point can only access the following things: global values/functions i.e. window, document, or any of the functions/objects/variables bound to the window object event object example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="hor...
... the window object event object example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="return myfunction(event);"/> </window> ...
popupalign - Archive of obsolete content
« xul reference homepopupaligntype: one of the values belowpopupalign is an optional attribute for specifying which side of the popup content should be attached to the popupanchor. noneno aligntopleftalign to the top left cornertoprightalign to the top right cornerbottomleftalign to the bottom left cornerbottomrightalign to the bottom right cornersyntax<element popupalign="none | topleft | topright | bottomleft | bottomright"/> example<element id="edit-context" popup="editor-popup" popupanchor="topleft" popupalign="bottomright"/> notesthe popupalign attribute can be used to specify which corner of the popup content is tied to the originating point. if omitted, the default is topleft. ...
...ightalign to the bottom right cornersyntax<element popupalign="none | topleft | topright | bottomleft | bottomright"/> example<element id="edit-context" popup="editor-popup" popupanchor="topleft" popupalign="bottomright"/> notesthe popupalign attribute can be used to specify which corner of the popup content is tied to the originating point. if omitted, the default is topleft. the example below shows how to create the traditional buttons with attached left mouse menus that exist in the 4.x communicator product. if omitted, no anchoring occurs. instead the popup content comes up directly underneath the mouse event coordinates. this point (either directly under the mouse or attached to one of the four corners) is called the originating point. by default the popup content appears with its ...
width - Archive of obsolete content
the size is adjusted by the flexibility or alignment of its parent. the css width property may also be used. in this example, the preferred width of the inner hbox will be displayed at 40 pixels. the displayed width is also 40 pixels as no flexibility or alignment applies. ...
...label value="40"/> </hbox> </hbox> however, in the following example, despite that the preferred width of the box is 30 pixels, the displayed size of the box will be larger to accommodate the larger label. <vbox width="30" align="start" style="background-color: red;"> <label value="vbox xul width 10px red"/> </vbox> note: when used on treecol objects, the width attribute can be used to allow a tree to be scrolled horizontally if the column widths add up to be wider than the containing object. ...
Getting File Information - Archive of obsolete content
lesize = file.filesize; it is also possible to modify the size of a file by setting the filesize (nsifile.attributes) attribute to a value. this may be useful to truncate a file, however, setting the file size will also increase the size of a file if the value is larger than the current size of the file. in this case, the new part of the file will be filled with empty data. for instance, the following line will set the length of a file to 5000 bytes. file.filesize = 5000; modified time the time that a file was last changed may be retrieved using the lastmodifiedtime (nsifile.attributes) attribute. this attribute holds a value measured in milliseconds since january 1, 1970. it is convenient to pass the returned time to the date constructor. var lastmod = new date(file.lastmodifiedtime);...
...date(file.lastmodifiedtime); in this example, a date object is created using the modification time of a file. you can change the modification time of a file by setting the lastmodifiedtime (nsifile.attributes) attribute, or you can just write to the file, in which case the value will be adjusted automatically. file permissions several methods may be used to check for file permissions. the following four methods return true or false: nsifile.isreadable() - returns true if the file can be read from. nsifile.iswritable() - returns true if the file can be written to. nsifile.isexecutable() - returns true if the file can be executed. nsifile.ishidden() - returns true if the file is hidden. in this example, an exeception will occur if the file cannot be written to. if (!file.iswritabl...
Uploading and Downloading Files - Archive of obsolete content
mentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. the io object and stream objects can be used to upload files to servers in various ways. the exact method depends on the type of upload that you wish to perform. http file upload some web sites allow one to upload a file. this is done by using an html <input> element using the file type from within a form. when the user selects a file, it can be uploaded to a server. this operation can also be performed via a script using the xmlhttprequest object. this is a common technique for uploading files as it is compatible with existing servers and formdata interface makes that task fairly simple. a ...
...request: function upload(posturl, fieldname, filepath) { var formdata = new formdata(); formdata.append(fieldname, new file(filepath)); var req = new xmlhttprequest(); req.open("post", posturl); req.onload = function(event) { alert(event.target.responsetext); }; req.send(formdata); } http put you can also upload a file using an http put operation. this is simpler but it doesn't allow sending additional data and web servers usually need special configuration to support put operations. function uploadput(posturl, filepath) { var req = new xmlhttprequest(); req.open("put", posturl); req.setrequestheader("content-type", "text/plain"); req.onload = function(event) { alert(event.target.responsetext); } req.send(new file(filepath)); } in this example, a new input stream...
IO - Archive of obsolete content
Archive › Mozilla › XUL › FileGuide › IO
ing textual data, list of file-related error codes. files and streams this section describes how to access and get information about files, read from files and create and write files. using files a xul application or extension may access files on disk, and either read or write to files. a file is accessed via a file object. to get a reference to a file object use nsiscriptableio.getfile(). the following example will retrieve a reference to a file located in the profile directory named sample.txt. var file = io.getfile("profile", "sample.txt"); the nsiscriptableio object is a global object always available within an application or extension. it provides a number of useful functions for dealing with files. retrieve a file object for information about getting a file object, see accessing files...
... reading from text and binary files, see reading from files. writing to a file for information about writing to text and binary files, see writing to files. copying and moving files files may be moved and copied on disk. for details, see copying a file and moving a file. deleting files to learn how to delete a file, see deleting a file. open and save dialogs you can show a dialog to the user to allow them to select a file to open or enter a filename for saving. for details about this, see open and save dialogs. file errors see file errors for a list of errors that might occur while using files. working with directories directories may be accessed in a similar manner using nsiscriptableio.getfile(). for instance, in the following example, a subdirectory is retrieved. if the name 'subdirname' ...
International characters in XUL JavaScript - Archive of obsolete content
ns that such script files can use any character from virtually 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 defa...
...u want the same code to work in both gecko 1.8 and earlier versions, you must limit yourself to ascii. however, you can use unicode escapes – the earlier example rewritten using them would be: var text = "ein sch\u00f6nes beispiel eines mehrsprachigen textes: \u65e5\u672c\u8a9e"; an alternative might be to use property files via nsistringbundle or the xul <stringbundle> element; this would allow for localization of the xul. this can not be done in xul files loaded from the web, only in privileged code, e.g. in extensions. ...
List of commands - Archive of obsolete content
the following lists commands which might be usable by <command> or command dispatchers/controllers. list of commands (grouped by type) nsdomwindowcontroller commands (generally legal when there is a selection): cmd_copy - copy a selection to the clipboard cmd_cut - cut a selection into the clipboard cmd_paste - paste a selection from the clipboard cmd_selectall cmd_selectnone cmd_copylink cmd_copyimagelocation cmd_copyimagecontents cmd_scrolltop cmd_scrollbottom cmd_scrollpageup cmd_scrollpagedown cmd_scrolllineup cmd_scrolllinedown cmd_scrollleft cmd_scrollright cmd_selectcharprevious cmd_selectcharnext cmd_wordprevious cmd_wordnext cmd_selectwordprevious cmd_selectwordnext cmd_beginline cmd_endline cmd_selectbeginline cmd_selectendline cmd_selectlinepr...
...evious cmd_charprevious cmd_charnext cmd_selectcharprevious cmd_selectcharnext cmd_beginline cmd_endline cmd_selectbeginline cmd_selectendline cmd_wordprevious cmd_wordnext cmd_selectwordprevious cmd_selectwordnext cmd_scrollpageup cmd_scrollpagedown cmd_scrolllineup cmd_scrolllinedown cmd_movepageup cmd_movepagedown cmd_selectpageup cmd_selectpagedown other commands the following list other commands (prefixed by cmd_ or browser:) which have not been categorized here yet (though they are in the alphabetical list below): http://lxr.mozilla.org/seamonkey/sou...baroverlay.xul http://lxr.mozilla.org/seamonkey/sou...t/navigator.js http://lxr.mozilla.org/seamonkey/sou...toroverlay.xul http://lxr.mozilla.org/seamonkey/sou...onaltoolbar.js http://lxr.mozilla.org/seamonke...
loadTabs - Archive of obsolete content
l reference home loadtabs( uris, loadinbackground, replace ) loadtabs( uris, params ) return type: no return value loads a set of uris, specified by the array uris, into tabs. ...
... loadtabs( uris, params ) return type: no return value loads a set of uris, specified by the array uris, into tabs. ...
Namespaces - Archive of obsolete content
his document, see namespaces crash course. xml namespaces provide a way to distinguish duplicate element and attribute names. duplicates element and attribute names can occur when an xml document contains elements and attributes from two or more different xml schemas (or dtds). to quote wikipedia: "in general, a namespace is an abstract container providing context for the items ... it holds and allows disambiguation of items having the same name." if you are familiar with c++ namespaces, java packages, perl packages, or python module importing, you are already familiar with the namespace concept. an xml namespace is identified by an unique name (called a uri, not a url, even though it can look like a url). an uri is any string, although most people choose a url-based uri because urls are an e...
...ugh the latter is just as correct when not using http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul as the default namespace) -- the xul namespace is defined as the default on the topmost element. in other words, a default namespace permits a kind of short-hand to be used for all descendants of an element. here's a question: what namespace contains the element foo in the xml document below? <foo/> the answer is that it's in no namespace, or alternately, it's in the namespace denoted by the empty string: <foo xmlns=""/> this second example is semantically equivalent to the first. now, a second question: what namespaces are the bar, baz, and quux attributes in? <foo bar="value"> <element xmlns="namespace!" baz="value"> <element quux="value"/> </element> </foo>...
Floating Panels - Archive of obsolete content
floating panels a floating panel is used for secondary popups such as tool palettes and property inspector panels. it will have a titlebar which the user may use to move the panel around on the screen. a floating panel can be created using the panel element with at least two additional attributes as in the following example: <panel id="tools-panel" noautohide="true" titlebar="normal"> <label control="name" value="name:"/> <textbox id="name"/> </panel> the noautohide attribute is used to indicate that the panel is not temporary. when set to true, the popup will not close when the user clicks outside of it, nor when the user presses the escape key. the titlebar attribute creates a panel with a titlebar. currently, only the value normal is supported, which creates a default titlebar. in th...
...he floating panel can be placed and moved independently of the main window, however it will always appear above the main window. on mac, floating panels are invisible when another application is made active, and become visible again when the xul application is made active. a floating panel may contain any type of element. a label for the titlebar may be set using the label attribute, as in the following example: <panel id="info-panel" noautohide="true" titlebar="normal" label="image properties"> closing a floating panel unlike other panels, a floating panel does not close when clicking outside of it. you can use the close attribute to have a close button on the titlebar. when the user presses it, the popup will be closed. <panel id="info-panel" noautohide="true" titlebar="normal" label="imag...
MenuButtons - Archive of obsolete content
should be placed as a direct child of the button. the 'menu' button the 'menu' type of button is used when pressing the button alone should just open the menu and not execute a command directly. this works similarly to the menu tag, and would be used to present a set of commands to execute. to create a button of this type, set the type attribute of the button to 'menu'. for instance, in the following example, pressing the 'view' button will open a menu which allows the user to select from a set of radio menuitems. presumably, when one is selected, the application view would be changed accordingly. when using the keyboard, pressing the down key will open the menu while the button is focused. <button type="menu" label="view"> <menupopup> <menuitem label="icons" type="radio" name="vi...
...io" name="view"/> <menuitem label="list" type="radio" name="view"/> <menuitem label="details" type="radio" name="view"/> </menupopup> </button> note that when the menu is closed, the button doesn't indicate which view is selected. if you do want this indication, you should use a menulist instead. the same technique can be used for toolbarbuttons as well as buttons. in the example below a toolbarbutton with an image has a menu associated with it. <toolbarbutton type="menu" image="cookies.png"> <menupopup> <menuitem label="block cookies" type="checkbox"/> <menuitem label="clear cookies"/> </menupopup> </toolbarbutton> the 'menu-button' button the 'menu-button' type of button is used when you want to attach a menu to a button but want to have a default action carri...
MenuModification - Archive of obsolete content
x, which means before the first item. indicies are counted starting at 0, so to insert an item before the fourth item pass 3 as the argument. the second and third arguments to insertitemat are the label and value for the new item, as with appenditem. both the appenditem and insertitemat methods return the new menuitem, so you can further modify it, for instance to add an access key, as in the following example: var item = menu.appenditem("insert", "insert"); item.accesskey = "i"; appending submenus there is no built-in method to append submenus to a menu. to do this, we instead need to use the inherited node modification methods available for all elements. first, we need to retrieve the menupopup for the menu, and then use the appendchild method to append a new item. <script> function a...
...ome other specific elements, and is simpler to use to append new menuitem elements to a menu. if we were to use the example above, we would also want to make sure to remove the items again in a popuphiding event listener. otherwise, a new submenu would be added every time the menu is opened, which is clearly not desirable. another possibility is to ensure that the menu is only added once. the following shows how the addsubmenu function above might be rewritten to handle this case. <script> function addsubmenu() { var popup = document.getelementbyid("file-popup"); if (popup.haschildnodes()) return; var newmenu = document.createelement("menu"); popup.appendchild(newmenu); newmenu.label = "new"; newmenu.appenditem("document", "doc"); newmenu.appenditem("image", "image"); } <...
MoveResize - Archive of obsolete content
be moved using the popup's moveto method. void moveto(in long left, in long top); the left argument is the horizontal screen position and the top argument is the vertical screen position. this method will change the left and top attributes to match the supplied arguments, so if these 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 f...
... 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. you can see this effect in a xul application by moving a window near the bottom of the screen and clicking a menu or button that has a menu. if a popup is still too large, it will be resized to fit on the screen. arrows will appear on the ends of the menu to allow a user to scroll through the items. a popup can be resized manually usi...
Tooltips - Archive of obsolete content
pear in the tooltip. <toolbarbutton label="back" tooltiptext="go back one page"/> in this example, a back button on a toolbar is given additional text to appear on a tooltip. this could also be useful if the toolbar is configured such that labels do not appear. if an element does not have a tooltiptext attribute, yet a parent element does, the parent tooltip will apply. for example, in the following, a toolbar has a tooltip set for it. <toolbar tooltiptext="file buttons"> <toolbarbutton label="open" tooltiptext="open a file"/> <toolbarbutton label="close"/> </toolbar> the 'open' button has a tooltiptext attribute so will have a tooltip of its own. however, the close button does not have a tooltip associated with it, yet the parent toolbar does. the result is that the toolbar's tool...
...buttons' isn't a good tooltip to use either. it conveys no additional information to the user, so it shouldn't be used as in this example. the tooltip element tooltips are displayed using a tooltip element, which is a type of popup, but is styled to look different. elements that use the tooltiptext attribute display the tooltip in a default tooltip element, which typically looks like a small yellow box large enough to fit the text inside it. this default tooltip is created automatically, so you don't normally need to use a tooltip element. however, it is possible to use another tooltip element that looks differently, or which supports other elements besides a single text label. the tooltip can be created using the tooltip element, the contents of which appear inside the tooltip. <tooltip...
Sorting and filtering a custom tree view - Archive of obsolete content
= new treeview(table); //set the appropriate attributes to show to indicator var cols = tree.getelementsbytagname("treecol"); for (var i = 0; i < cols.length; i++) { cols[i].removeattribute("sortdirection"); } document.getelementbyid(columnname).setattribute("sortdirection", order == 1 ? "ascending" : "descending"); } //prepares an object for easy comparison against another. ...
...ee.getelementsbytagname("treecol"); for (var i = 0; i < cols.length; i++) { cols[i].removeattribute("sortdirection"); } document.getelementbyid(columnname).setattribute("sortdirection", order == 1 ? "ascending" : "descending"); } //prepares an object for easy comparison against another. ...
Bindings - Archive of obsolete content
the tower looking east of the doges palace') thus, only one match exists, so only one set of content is generated. sometimes, it would be useful to have triples that match conditionally; that is, a triple that doesn't cause a result to be removed as a possible match. this is done with a binding element. this tag doesn't go in the query block but instead inside a rule element. ...
...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. ...
Filtering - Archive of obsolete content
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. in this example, the menulist is hard-coded to contain the items that we know are in the datasource. next, we'll look at also generating this list using a template. genera...
...icate="http://purl.org/dc/elements/1.1/title" object="?countrytitle"/> </query> the action body will need to generate a <menuitem> for each result. it will also need to include a <menupopup> around all of the items. since we only want to generate a single menupopup, it should go outside of the element with the uri attribute. only the contents at the element with the uri attribute and below are copied for each result. the elements above are not. <action> <menupopup> <menuitem uri="?country" label="?countrytitle" value="?country"/> </menupopup> </action> the result will be two generated menuitems, one for each country, inside a menupopup. the value attribute is assigned the ?country variable so that the applyfilter function can use this value easily for filtering. the compl...
Rule Compilation - Archive of obsolete content
reapply the template again. this means that you can change the rules using dom methods, rebuild the template, and get different results. once the template builder has compiled the rules, query processing and content generation can begin. the template builder generates content lazily, that is, it processes as little as needed, and only continues when necessary. for instance, consider the example below: <vbox datasources="http://www.xulplanet.com/ds/sample.rdf" ref="http://www.xulplanet.com/rdf/a" hidden="true"> <template> ... </template> </vbox> the <vbox> is hidden as indicated by the 'hidden' attribute. since any content that would be generated wouldn't be displayed anyway, the template builder doesn't do anything, putting off work until later. if you show the vbox by setti...
...invoked and the content will be generated. does this mean that templates cannot be used inside hidden areas of the ui? no, you can still do that. changing the hidden state of an element isn't the only way to cause content to be generated. calling a dom api which needs to get at the generated content will cause the template builder to generate output. for example, just calling the code like the following on the hidden vbox above will start off the template builder. var length = vbox.childnodes.length; this request to return the number of children of the vbox will make the template builder process the query and output content. once done, the correct length can be returned. all of this is transparent to the xul developer. when the template builder decides to start generation is determined autom...
Simple Query Syntax - Archive of obsolete content
ommon, so the simpler syntax is usually used in this situation since it avoids extra tags, although the simple syntax is not more or less efficient, at least when a single query is involved. a simple query is equivalent to a query with only the content tag and a member tag, as well as optionally a set of triples from the child node. at its simplest, the simple query syntax is equivalent to the following: <query> <content uri="?start"/> <member container="?start" child="?photo"/> </query> the template builder uses the simple query syntax whenever a template does not have a <query> element. if a <query> element is present, the full syntax is used instead. in the simple syntax, the builder will use the default query shown above, although the variable names are randomly generated. since the...
...ld be equivalent to ?photo variable in this example if the full syntax was used. you can see in the example that the value 'rdf:*' is used in two places, the uri attribute on the hbox and as the src attribute for the image. here is the photos example using the simple syntax. the filtering isn't shown in this example. it is still possible to do filtering using simple query and we'll look at this below. simple query conditions simple queries also use a simpler way of handling triple elements to filter out unwanted results. it allows you to filter for results that have certain predicates with specific values. for instance, you may filter results that have a certain category or country. you can only filter on predicates pointing out of the member resource. that is, you cannot filter on predica...
Template Builder Interface - Archive of obsolete content
different whitespace handling for html and xul, which is why the content to generate in the above example is all on one line. if you do plan on generating non-xul content with a template, just watch out for issues like this. note that this particular whitespace issue has been fixed in firefox 3 and later. note also that the datasources attribute has been placed on an html element. this is also allowed. however, one thing to watch out for is that non-xul elements do not have their content generated lazily so all of the content will be generated at once. be careful that your templates do not recurse to deep levels. the builder property is a property of the nsidomxulelement interface, so all xul elements will have this property, although, as mentioned earlier, is will be set to null for most el...
... for example: <vbox datasources="template-guide-photos5.rdf template-guide-streets.rdf"> sometimes, you will want to calculate the datasource to be used and attach it to the template later. you can do this using the composite datasource's adddatasource method. you can add as many datasources as you wish, and you can remove them using the removedatasource method. a common pattern is to use the following: var rdf = components.classes["@mozilla.org/rdf/rdf-service;1"]. getservice(components.interfaces.nsirdfservice); var ds = rdf.getdatasource("http://www.xulplanet.com/ndeakin/tests/xul/template-guide-streets.rdf"); var tree = document.getelementbyid("thetree"); tree.database.adddatasource(ds); tree.builder.rebuild(); this is the typical way to add a datasource to an element, in ...
XML Assignments - Archive of obsolete content
his using the built-in string-length method. however, you cannot use a expression that returns a number in the query, as the query must return dom nodes as results. in this case, we use an expression that returns the nodes as in earlier examples, and use some additional syntax of the query to get the length of the names. to do this, we use an additional element, the assign element. this element allows the use of additional xpath expressions to get more data from the xml data. here is an example: <vbox datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="person"> <assign var="?namelength" expr="string-length(@name)"/> <assign var="?siblings" expr="count(../*) - 1"/> </query> <action> <hbox uri="?" align="center"> <button label="?name...
..."string-length(@name)"/> <assign var="?siblings" expr="count(../*) - 1"/> </query> <action> <hbox uri="?" align="center"> <button label="?name"/> <label value="?gender"/> <label value="?namelength"/> <label value="?siblings"/> </hbox> </action> </template> </vbox> two assign elements are placed as children of the query element. it allows us to declare additional variables that may be used in the action body. the expr attribute specifies the xpath expression and the var attribute specifies the variable to assign to. note that while the query expression uses the root node (or reference node) as the xpath context, the expressions for the assign element are evaluated using each result node as the context. for each result, the ?namel...
Things I've tried to do with XUL - Archive of obsolete content
short answer: you can't easily, at least not yet. this means that creating any sort of visual display (not necessarily "ui"; my use case is for creating a calendar time display) that sizes sanely when the user resizes the window is unfortunately very difficult. (to add insult, xul layout code *explicitly* trims off '%' from width/height, thus treating it as pixels.) for reference, i'd like the following to give a vbox that resizes along with the window, with the green, red, and blue inside boxes always maintaining a 30%-20%-50% ratio to the height of the parent vbox. <vbox flex="1"> <box height="30%" flex="1" style="background: green;"/> <box height="20%" flex="1" style="background: red;"/> <box height="50%" flex="1" style="background: blue;"/> </vbox> workaround: no real good ones; the ...
...xes. enn: percentages won't have any effect in these examples though, since the actual height of the container isn't known, and 30% of an unknown number is still an unknown number. vlad: sure; the snippets assume that there's some enclosing structure that will provide the actual height. wrap the whole thing in a <vbox height="300"> or something. :) silver: if you set height="0" and include "overflow: hidden" on each box that is sharing the space, current gecko will quite happily split the space out according to flex, ignoring the contents of each box, as desired. from my reading of the code, just height="0" should work, but it doesn't seem to. this trick doesn't work in 1.4, but works in 1.7 and current versions. obtaining the rect of an element you can't obtain the actual visible rect of...
Complete - Archive of obsolete content
introduction you can use the custom toolbar button tutorial as a very simple introduction to extensions. however, because it is so simple it does not support some of the usual features of extensions. this page describes how to structure the extension in a more conventional way. ...
...erface in two languages (english and french). it supports firefox, thunderbird, sunbird and flock—these are referred to as "firefox etc." in the rest of this page. it also supports seamonkey. in seamonkey it supports two themes (classic and modern). it provides all five custom toolbar buttons on all the toolbars, and it provides corresponding menu choices in seamonkey's chatzilla window. the following sections describe this extension's overall structure, and how it implements languages and themes. overall structure this extension's internal name is allcustom. it uses this name as the default file name throughout. where you see a url in the code with no file name, the application uses this default file name and an extension appropriate for the type of file expected. the extension is supplied...
Additional Install Features - Archive of obsolete content
s 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:///", "main"); file.copy(grep, mainfolder); the first line will retrieve a reference to the /bin directory. the text 'file:///' is a special string which means the root of the filesystem.
...r 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 error message to the user. for example, you might put the following as the last section of your script: if (getlasterror() == success) { performinstall(); } else { cancelinstall(); } error codes that could be returned by getlasterror() are listed in the mozilla source file nsinstall.h. during installation, a log file is created that contains the operations that are performed. it will also show any errors that occured. the log file can be found in the file...
Box Model Details - Archive of obsolete content
lex="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 model may be difficult to understand without trying various various things out for yourself. the following is an outline of both types of boxes: horizontal boxes lay out their elements next to each other horizontally. flexible elements are flexed horizontally. packing controls their horizontal placement of child elements. alignment controls how the row of elements are aligned vertically. vertical boxes lay out their elements vertically in a column. flexible elements are flexed vertic...
...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 some space of no more than 30 pixels. the second box has an alignment of start. this causes the child elements to be aligned on the left edge. if this was not specified, the default would be stretch, which would make the ...
Creating an Installer - Archive of obsolete content
which can be used to install files and components. the jar file installers typically have the extension .xpi (pronounced zippy) to distinguish them from other archives. the installers will be usually used to install mozilla components such as new skins, plugins and packages. there are several steps involved in launching an installer and installing components. these are described step by step below. create a web page from which the user can download the software to be installed. this page will contain an install trigger which is a small piece of script which launches the install. the user is presented with a dialog which indicates the package being installed. it is possible for the install trigger to launch multiple installers. in this case, they will be presented in a list. the user ma...
...be the install script (install.js) and a jar file. this jar file contains all of the files used by your application. the components provided with mozilla are stored in this manner. because the xpi file is just a special zip file, you can create it and add files to it using a zip utility. our find files example for the find files dialog, we'll create a structure in the archive much like the following: install.js findfile content contents.rdf findfile.xul findfile.js skin contents.rdf findfile.css locale contents.rdf findfile.dtd a directory has been added for each part of the package, the content, the skin and the locale. the contents.rdf files have also been added because they will be needed to register the chrome files. next, we'll look further at t...
Grids - Archive of obsolete content
Archive › Mozilla › XUL › Tutorial › Grids
ml table tag. the grid does not display anything itself; it is used only to position elements in a tabular form with rows and columns. a grid contains elements that are aligned in rows just like tables. inside a grid, you declare two things, the columns that are used and the rows that are used. just like html tables, you put content such as labels and buttons inside the rows. however, the grid allows either row or column based organization so you may put content in either rows or in columns. it is most common to use rows, as with a table. however, you can still use columns to specify the size and appearance of the columns in a grid. alternatively, you can put content inside the columns, and use the rows to specify the appearance. we'll look at the case of organizing elements by row first. d...
... the rows in the above example. if the columns has been placed first, the rows would have grabbed the events and you would not be able to type into the fields. flexibility of grids one advantage that grids have over a set of nested boxes is that you can create cells that are flexible both horizontally and vertically. you can do this by putting a flex attribute on both a row and a column. ...
Introduction to XBL - Archive of obsolete content
bar function. for this, you need xbl. an xbl file contains a set of bindings. each binding describes the behavior of a xul widget. for example, a binding might be attached to a scroll bar. the behavior describes the properties and methods of the scroll bar in addition to describing the xul elements that make up a scroll bar. like xul, xbl is an xml language, so it has similar syntax rules. ...
...ide default handling. in addition new events can be defined. style: custom style properties that the xbl defined element has. binding example the box is generic enough that you can use it to create custom widgets (although you can use any element, even one you make up yourself). by assigning a class to a box tag, you can associate a binding to only those boxes that belong to that class. the following example demonstrates this. xul (example.xul): <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <?xml-stylesheet href="chrome://example/skin/example.css" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <box class="okcancelbuttons"/> </window> css (example.css): box.okcancelbuttons { -moz-binding: u...
Persistent Data - Archive of obsolete content
pain to do for every application. conveniently, xul provides such a mechanism to save the state of a window. the information is collected and stored in a rdf file (localstore.rdf) in the same directory as other user preferences. it holds state information about each window. this method has the advantage that it works with mozilla user profiles, so that each user can have different settings. xul allows you to save the state of any element. you will typically want to save toolbar states, window positions and whether certain panels are displayed or not, but you can save almost anything. persist attribute to allow the saving of state, you simply add a persist attribute to the element which holds a value you want to save. the persist attribute should be set to a space-separated list of attributes ...
... . . the two attributes of the window element, the width and the height will be saved. you could add additional attributes by adding a space and another attribute name to the persist attribute. ...
Progress Meters - Archive of obsolete content
s 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. if this is set to undetermined, the progress meter is i...
...the value has been set to 50% so that we can see the meter on the window. a margin has been set to 4 pixels so that it is separated from the edge of the window. as was stated earlier, we only want the progress bar to be displayed while the search was occurring. a script will show and hide it as necessary. to make this work you will first have to define the namespace html. do this by adding the below line to your opening window tag in the findfile.xul. xmlns:html="http://www.w3.org/1999/xhtml" the example so far. source view in the next section, we will learn how to add additional elements to the window using html. « previousnext » ...
Property Files - Archive of obsolete content
ddition, you may wish to display a message which is generated from a script, if, for example, you do not know the exact text to be displayed. for this purpose, property files can be used. a property file contains a set of strings. you will find property files alongside the dtd files with a .properties extension. properties in the file are declared with the syntax name=value. an example is shown below: notfoundalert=no files were found matching the criteria. deletealert=click ok to have all your files deleted. resultmessage=%2$s files found in the %1$s directory. here, the property file contains three properties. these would be read by a script and displayed to the user. a property file can also include comments. a line that begins with a hash sign ('#') is treated as a comment: # this is a c...
... gets a string with the given key name from the bundle. in addition, each occurrence of formatting code (e.g. %s) is replaced by each successive element in the supplied array. var dir = "/usr/local/document"; var count = 10; var strbundle = document.getelementbyid("strings"); var result = strbundle.getformattedstring("resultmessage", [ dir, count ]); alert(result); this example will display following message in an alert box. 10 files found in the /usr/local/document directory. you will notice the formatting codes %1$s and %2$s is used, and replaced different order in the array. formatting code %n$s is specify the position of corresponding parameter directly. although the word order is not the same in all the languages, by using getformattedstring() the specification of the order can be pu...
Stacks and Decks - Archive of obsolete content
contain other elements. we've already seen that buttons may contain other things besides the default. a scroll bar is just a special type of box that creates its own elements if you don't provide them. it also handles the moving of the scroll bar thumb. in the next few sections, we'll introduce some elements that are designed for holding other elements. they are all special types of boxes and allow all of the attributes of boxes on them. stacks the stack element is a simple box. it works like any other box but has 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 m...
...e 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 the stack element however is that you could emulate a number of css properties with it. for example, you could create an effect similar to the text-shadow property with the following: example 1 : source view <stack> <description value="shadowed" style="padding-left: 1px; padding-top: 1px; font-size: 15pt"/> <description value="shadowed" style="color: red; font-size: 15pt;"/> </stack> both description elements create text with a size of 15 points. the first, however is offset one pixel to the right and down by adding a padding to its left and top sides. this has t...
XUL Template Primer - Bindings - Archive of obsolete content
f#street" object="?street"/> </bindings> <action> <hbox uri="?friend"> <label value="?name"/> <label value="?street"/> </hbox> </action> </rule> </template> </vbox> </window> the xul template primer covers the <conditions> and <action> elements, so we won't discuss those here. we'll use a the following data model to illustrate how bindings work. see the rdf/xml file friends.rdf, below, a simple database with name and address information for some of my good friends. <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:nc="http://home.netscape.com/nc-rdf#"> <rdf:description about="urn:root"> <nc:friends> <rdf:seq> <rdf:li> ...
... when displayed in mozilla, something like this appears: note that even though poor lumpy has no nc:address property, he still appears in the content model! unlike the <conditions>, bindings do not affect whether or not a rule matches: they just "pull through" additional information if it is available. the <bindings> element the <bindings> element is optional in a xul template, b...
XUL Coding Style Guidelines - Archive of obsolete content
easy to read and maintain, localization friendly, and portable across user agents, we need to have a set of coding style guidelines to ensure our objectives are achievable. the author has collected a set of guidelines from various sources listed in the references section. while some of the guidelines are recommended practices, the others are mandatory. xml, xul, html, and xhtml guidelines the following are considered good coding style for xml/xul documents. disobeying them might not cause any parsing error for now, however, it might cause future maintenance headache: convert html files to xul files. use the xml declaration. use namespace. case sensitivity. use chrome urls. javascript code shall be moved out of xul. dtd declaration. predefined entities. other guidelines mentioned in xhtml 1...
...ity 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 xul language spec and xul window language. xul localizability issues xhtml 1.1 recommendation namespaces in xml extensible...
caption - Archive of obsolete content
tion label="my groupbox"/> </groupbox> <groupbox flex="1"> <caption> <checkbox label="a checked groupbox"/> </caption> </groupbox> 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. 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. start the text will be cropped on its left side in left-to-right text locales, and the right side in ri...
...nment. depending on the platform and theme being used, some elements will have set a maximum width so they will always appear cropped. if you wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width css property (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.
commandset - Archive of obsolete content
rs. for example, since the cut command is only valid when something is selected, a command updater might be used when the select event occurs. events type: comma-separated list a comma-separated list of event names that the command updater will update upon. if this attribute is not specified, or you set it to the value '*', all events are valid. valid events are listed below, or you can use your own events. you can send a custom event by calling the updatecommands method of the command dispatcher. focus: occurs when the focused element changes. select: occurs when the selected text changed. clipboard: occurs when the clipboard is changed. undo: occurs when the undo buffer is changed. oncommandupdate type: script...
... items. targets type: comma-separated list of element ids a comma-separated list of element ids that the command updater will update upon. if this attribute is not specified, 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. ...
content - Archive of obsolete content
iza para vincular una variable a un nodo de contenido cuando se emparejan. cuando use un árbol con los atributos flags ("banderas"), establezca dont-build-content, ("no almacenar contenido"), use treeitem en su lugar. para más información, se encuentra disponible el tutorial xul. ...
...ular una variable a un nodo de contenido cuando se emparejan. cuando use un árbol con los atributos flags ("banderas"), establezca dont-build-content, ("no almacenar contenido"), use treeitem en su lugar. para más información, se encuentra disponible el tutorial xul. ...
dialog - Archive of obsolete content
e: string the label to appear on the second extra button. buttonlabelhelp type: string the label to appear on the "help" button. buttonorient type: string the value of the orient attribute for the box containing the buttons. buttonpack type: string the value of the pack attribute for the box containing the buttons. buttons type: comma-separated list of the values below a comma-separated list of buttons to appear in the dialog box. the buttons will be placed in suitable locations for the user's platform and basic event handling will be performed automatically. the following values can be used in the list: accept: the ok button, which will accept the changes when pressed. this button will also be the default button. cancel: the cancel button which will can...
... buttons attribute. inactivetitlebarcolor type: color string specify background color of the window's titlebar when it is inactive (background). moreover this hides separator between titlebar and window contents. this affects only on mac os x. title type: string the text to appear in the title bar of the window. properties buttons type: comma-separated list of the values below a comma-separated list of buttons to appear on the dialog box. the buttons will be placed in suitable locations for the user's platform and basic event handling will be performed automatically. the following values can be used in the list: accept: the ok button, which will accept the changes when pressed. this button will also be the default button. cancel: the cancel button which will can...
grid - Archive of obsolete content
Archive › Mozilla › XUL › grid
<textbox id="user"/> </row> <row> <label value="group"/> <menulist> <menupopup> <menuitem label="accounts"/> <menuitem label="sales" selected="true"/> <menuitem label="support"/> </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, sortd...
...t, 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, 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 addeventlist...
image - Archive of obsolete content
Archive › Mozilla › XUL › image
when the image has finished loading. this applies whether the image is applied via the src attribute or the list-style-image style property. if you change the image, the event will fire again when the new image loads. this event will not bubble up the element tree. src type: uri the uri of the content to appear in the element. validate type: one of the values below this attribute indicates whether to load the image from the cache or not. this would be useful if the images are stored remotely or you plan on swapping the image frequently. the following values are accepted, or leave out the attribute entirely for default handling: always the image is always checked to see whether it should be reloaded. never the image will be loaded from the cache...
...handling: always the image is always checked to see whether it should be reloaded. never the image will be loaded from the cache if possible. properties accessibletype 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. ...
listcol - Archive of obsolete content
ox> <listhead> <listheader label="first"/> <listheader label="last"/> </listhead> <listcols> <listcol flex="1"/> <listcol/> </listcols> <listitem> <listcell label="buck"/> <listcell label="rogers"/> </listitem> <listitem> <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, sortd...
...t, 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, 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 addeventlist...
param - Archive of obsolete content
Archive › Mozilla › XUL › param
should be text as a child of the param element. for more information, see query_parameters. attributes index, name, type attributes index type: integer the index within the sql statement of the parameter. name type: string the name of a parameter within the sql statement. this name should appear within the query preceded by a colon. ...
...g the name of a parameter within the sql statement. this name should appear within the query preceded by a colon. ...
richlistitem - Archive of obsolete content
disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. searchl...
...his value is read-only. to change the selection, set either the selectedindex or selecteditem property of the containing element. 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 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 merely associate data with an element, you could 1) use another attribute like "value2" or "data-myatt" (as in the html5 draft), as xul does not require ...
scrollbar - Archive of obsolete content
the scroll bar may also be used independently when a numeric value or percentage needs to be selected by the user. the user can adjust the position of the scroll bar by clicking arrows on either end of the scroll bar or by dragging the scroll bar thumb around. ...
...nteger the maximum position of the scrollbar. the default value is 100. pageincrement type: integer the amount by which the value of the curpos or value attribute changes when the tray 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. ...
tabpanels - Archive of obsolete content
be hidden; hiding the tab suffices to make the panel inaccessible. more information is available in the xul tutorial. attributes selectedindex properties selectedindex, selectedpanel examples (example needed) attributes selectedindex type: integer gets and sets the index of the currently selected panel. the first item is at index 0. ...
...iding the tab suffices to make the panel inaccessible. more information is available in the xul tutorial. attributes selectedindex properties selectedindex, selectedpanel examples (example needed) attributes selectedindex type: integer gets and sets the index of the currently selected panel. the first item is at index 0. ...
toolbaritem - Archive of obsolete content
s" selected="true"/> <menuitem label="train"/> </menupopup> </menulist> </toolbaritem> <toolbaritem id="sample-toolbutton-unified"> <toolbarbutton id="myext-button1" class="toolbarbutton-1" label="label1" /> <toolbarbutton 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, sortd...
...t, 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, 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 addeventlist...
Building XULRunner - Archive of obsolete content
by default, xulrunner is built with 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. ...
...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. a basic minimal mozconfig which will build a release configuration of xulrunner is: mk_add_options moz_co_project=xulrunner mk_add_options moz_objdir=@topsrcdir@/obj-xulrunner ac_add_options --enable-application=xulrunner #uncomment the following line if you don't want to build javaxpcom: #ac_add_options --disable-javaxpcom cvs tags and xulrunner versions older xulrunner releases where tagged in cvs with (for instance xulrunner_1_8_0_5_release ) up to version 1.8.0.5 the cvs repository does not have specific tags for xulrunner anymore. instead a xulrunner build is a just special build made from the firefox/mozilla tree, using the s...
Using SOAP in XULRunner 1.9 - Archive of obsolete content
several alternatives were considered: soapclient 2.4 - this library contains a few javascript mistakes but nevertheless seems (fairly) widely used, mature and tested. it requires servers to support wsdl which took it out of the running. xulrunner 1.8.* - using an old xulrunner is certainly an option but brings up a host of speed, stability and memory issues. ...
....8.* - using an old xulrunner is certainly an option but brings up a host of speed, stability and memory issues. manual implementation - the author doesn't know enough about soap to implement a robust client in an afternoon. the best solution proved to be jqsoapclient. this library doesn't require a wsdl. though jquery is listed as a dependency, it can be worked around easily. ...
XUL Explorer - Archive of obsolete content
still available. option to automatically update the preview as the editor changes. indicator in the statusbar shows errors. double-click to display error console. option to specify the snippet used to load the editor on startup. option to include a user snippet file. the snippets are merged with the built-in snippets at startup. double-click or drag-and-drop to insert a snippet file > new allows user to pick any “template” snippet, as well as blank. simple xul checker can be used to ‘validate’ the xul snippet. it checks for legal element and attribute names, including allowed attributes for a given element. support attribute value checking where appropriate (boolean and enumerated values) - xul checker support “best practice” checks such as: using of commands and keys, st...
... installs latest version: install (windows): xulexplorer-1.0a1pre.en-us.win32.exe 6.6mb inst...
application/http-index-format specification - Archive of obsolete content
the application/http-index-format file format is an attempt to provide a generic, extensible file listing format that is principly machine readable. syntax every line in the file must conform to the following generic syntax: number: data where number is at least a three digit number (note that more digits are possible in the future) and data is separated from number by a colon and a space. 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 int...
...e. white space and 8 bit characters must be url encoded. content-length base 10 digits representing the size of the file in bytes. only digits are legal. last-modified rfc 1123 date format url encoded. content-type mime content type. whitespace and 8-bit characters must be url-encoded. the mime-type for a directory can be given as application/http-index-format. file-type one of the following keywords to represent a special status for a file: file directory symbolic-link sym-file (a symbolic link to a file) sym-directory (a symbolic link to a directory) permissions unix type file permission syntax. 3 slots either 'r', 'w', 'x', or '-' representing, in order, read, write, or execute permissions. a '-' indicates that the particular permission is not set. example "rw-" means ...
calICalendarViewController - Archive of obsolete content
calendar/base/public/calicalendarviewcontroller.idlscriptable please add a summary to this article. ...
... in calidatetime anewstarttime, in calidatetime anewendtime); the modifyoccurrence method is used to change the attributes of an already existing caliitem. the calidatetime parameters must either both be specified, or neither. if they are both specified, aoccurrence should be modified 'silently', that is, without a more detailed dialog appearing. otherwise, a dialog should be display allowing the user to modify the fields. implementations of calicalendarviewcontroller should be careful to provide clearly defined behavior to the user regarding the modification of recurring caliitems. deleteoccurrence void deleteoccurrence (in caliitemoccurrence aoccurrence); the deleteoccurrence method is called when by the calicalendarview when caliitem should be deleted. implementations of c...
2006-10-27 - Archive of obsolete content
he wanted to know what was wrong with fx 1.5.0.x (linux) tinderbox because it has been failing since october 22 at around 5:45 pm pdt. gavin responded to tony's posting saying that the log file shows a "no space left on device" error when trying to link the final executable. on the same day tony replied to gavin's posting stating the possible choices to solve the problem. these were the following choices stated: search the filesystem for unneeded files delete or archive them, add a hard disk, move all or part of the concerned filesystem there move that tinderbox to a different machine with more empty disk space on october 23rd: nick responded to gavin and tony's posting. nick stated that the build engineers knew that there was a problem with the tinderbox and that they would ...
...lso 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/thunderbird --enable-application=browser --disable-tests --disable-debug -disable-auto-deps --disable-freetype2 -enable-official-branding --enable-default-toolkit=gtk2 --enable-optimize=-xo5 --enable-static --disable-shared --enable-xft --enable-svg the build tools that he used to...
2006-11-17 - Archive of obsolete content
no could not run gtk test program, checking why... the test program failed to compile or link. see the file config.log for the exact error that occured. this usually means gtk was incorrectly installed or that you have moved gtk since it was installed. ...
...no could not run gtk test program, checking why... the test program failed to compile or link. see the file config.log for the exact error that occured. this usually means gtk was incorrectly installed or that you have moved gtk since it was installed. ...
2006-11-24 - Archive of obsolete content
ber 17th to november 24th 2006 trouble building xulrunner 1.8.4 on winxp using mingw32 november 20th: joe is trying to build xulrunner using the ming compiler on windowsxp. however he has been unsuccessful and a bunch of errors. to view the joe's error please check the posting. ...
..."component returned failure code: 0x80570016 (ns_error_xpc_gs_returned_failure) [nsijscid.getservice]" nsresult: "0x80570016 (ns_error_xpc_gs_returned_failure)" location: "js frame :: chrome://modzilla/content/js/pkg_zillacom.js :: <top_level> :: line 1202" data: no] he is running xulrunner v1.8.0.4. ...
2006-10-06 - Archive of obsolete content
re: sunbird and lightning 0.3rc1 available sunbird and lightning 0.3rc1 is announced. ...
...l of the planning blog. adam gutherie replied that cbeard's blog post from nov 2005 is as close to a roadmap as exists right now and agrees that needs to be done about this. re: plan to hold trunk closed for lack of talkback dbaron mentioned that maybe trunk should be closed because of lack of talkbacks received ( bug 354835 is suspected). pal-moz offers a solution to bug 354835. dbaron then follows up that bug 354835 is solved so there is no need to close the tree waiting for it. thunderbird 2 - beta/rc? johannes koch asks where is the thunderbird roadmap? ziga sancin replies with a link and regrets about it being a bit out of date. firefox 1.5.0.8 andrew schultz asks about the gecko 1.8.0.8 schedule. dbaron and chris ilias respond with relative dates but still no schedule. rc2 status...
2006-10-06 - Archive of obsolete content
summary: mozilla.dev.security - september 30, 2006 to october 6, 2006 return to mozilla-dev-tech-xul announcements none during this week. discussions protocol handlers boris zbarsky posed the question, should random webpages have access to the following protocols: feed, pcast, moz-bookmark, webcal, swebcal. as well as any protocols that you have implemented and are not in the list of protocols nsscriptsecuritymanager::checkloaduri feed: consensus is that it should be allowed and treated as an ordinary link. pcast: similar to feed: just differentiating between different types of feeds and should be allowed access. moz-bookmark: protocol is defunct, apparently ben goodger disabled it back in 12/2003, shortly after he added it. webcal: & swebcal: should also be a...
... of protocols nsscriptsecuritymanager::checkloaduri feed: consensus is that it should be allowed and treated as an ordinary link. pcast: similar to feed: just differentiating between different types of feeds and should be allowed access. moz-bookmark: protocol is defunct, apparently ben goodger disabled it back in 12/2003, shortly after he added it. webcal: & swebcal: should also be allowed as the security manager doesn't differentiate between access types. other this is for allowing protocol handlers to define a custom security model (see bug 120373). there is no consensus in the posts as to if this should be allowed. problem looping c_opensession problem in thunderbird christian bongiorno has run into a problem developing a pkcs11 module for a new card. thunderbird is cont...
2006-11-03 - Archive of obsolete content
summary: mozilla.dev.tech.layout - october 28 - november 3, 2006 announcements new reflow branch off of trunk l. david baron announced that he merged the reflow branch to a new branch (reflow_20061031_branch) off of the trunk. discussions html5 @ w3c discussion of the official announcement from w3c on the development of html5 and how mathml should be included in it. firefox table captions discussion on how ie displays captions depending on the size of the content while ff uses a default setting. captions in ff also exceed the table length and become hidden if it's surrounded by a bounding div element. a test case is pending. ...
...scussion of the official announcement from w3c on the development of html5 and how mathml should be included in it. firefox table captions discussion on how ie displays captions depending on the size of the content while ff uses a default setting. captions in ff also exceed the table length and become hidden if it's surrounded by a bounding div element. a test case is pending. perf question (reflow branch) a look into bug #352367 and the mention of possibly reducing the number of times nsframe::intrinsicwidthoffsets is called for each cell within a table. meetings none this week. ...
2006-11-17 - Archive of obsolete content
ut - november 11 - november 17, 2006 announcements none this week. discussions testing accesskey 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 bu...
... parsing html into a document object in fx3 discussion if gecko 1.9 will support parsing html into a document object. the possibility of turning the microsummaryresource object into a xpcom component, which accomplishes this task in a "hacky" manner, was also discussed. ...
NPN_GetAuthenticationInfo - Archive of obsolete content
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 freei...
...rameter. the length of the returned password 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 plugin which implement their own http networking stack (such as the java plugin) may want to use the standard http auth prompts and password managed of the browser. this function allows the plugin to ask the browser for http authentication information for a domain. unless the plugin has special networking needs, it is recommended to use the standard network apis, such as npn_geturlnotify/npn_posturlnotify. see also npn_setvalueforurl, npn_getvalueforurl ...
NPN_GetURL - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary asks the browser to create a stream for the specified url. syntax #include <npapi.h> nperror npn_geturl(npp instance, const char* url, const char* target); parameters the function has the following parameters: instance pointer to the current plug-in instance. url pointer to the url of the request. can be of any type, such as http, ftp, news, or mailto. target name of the target window or frame, or one of the following special target names. values: _blank or _new: load the link in a new blank unnamed 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 ...
... as the http server method get, which requests url objects. use npn_geturlnotify() instead of npn_geturl() in these cases: to request a stream and receive notification of the result. if the buffer contains header information (even a blank line). make sure that the target matches the url type sent to it. for example, a null target does not make sense for some url types (such as mailto). the following recommendations about target choice apply to other methods that handle urls as well. if the target parameter refers to the window or frame containing the current plug-in instance, the instance is destroyed and the plug-in may be unloaded. if target is null, the application creates a new stream and delivers the data to the plug-in instance, through calls to npp_newstream(), npp_writeready() and...
NPN_GetURLNotify - Archive of obsolete content
i reference « browser side plug-in api summary requests creation of a new stream with the contents of the specified url; gets notification of the result. syntax #include <npapi.h> nperror npn_geturlnotify(npp instance, const char* url, const char* target, void* notifydata); parameters the function has the following parameters: instance pointer to the current plug-in instance. url pointer to the url of the request. can be of any type, such as http, ftp, news, or mailto. target name of the target window or frame, or one of several special target names. for values, see npn_geturl(). notifydata plug-in-private value for associating the request with the subsequent npp_urlnotify() call, which passes ...
...ointer to the current plug-in instance. url pointer to the url of the request. can be of any type, such as http, ftp, news, or mailto. target name of the target window or frame, or one of several special target names. for values, see npn_geturl(). notifydata plug-in-private value for associating the request with the subsequent npp_urlnotify() call, which passes this value (see description below). 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 npn_geturlnotify() works just like npn_geturl(), with one exception: npn_geturlnotify() notifies the plug-in instance upon successful or unsuccessful completion of the request by calling the plug...
NPN_GetValue - Archive of obsolete content
variable information the call gets. ...
... variable information the call gets. ...
NPN_GetValueForURL - Archive of obsolete content
r example the cookies or preferred proxy. syntax #include <npapi.h> typedef enum { npnurlvcookie = 501, npnurlvproxy } npnurlvariable; nperror npn_getvalueforurl(npp instance, npnurlvariable variable, const char *url, char **value, uint32_t *len); parameters this function has the following parameters: instance pointer to the current plug-in instance. variable 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...
... 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 to allow plugins which implement their own http stacks to form requests to the web server in the same way the browser does. see also npn_setvalueforurl, npn_getauthenticationinfo ...
NPN_MemAlloc - Archive of obsolete content
returns if successful, the function returns a pointer to the allocated memory, in bytes. if insufficient memory is available, the plug-in returns null. ...
... description the plug-in calls npn_memalloc to allocate a specified amount of memory in the browser's memory space. if you allocate saved instance data with npp_destroy, be sure to use npn_memalloc to allocate memory. this ensures that the browser can free the saved data at a later time with the equivalent of npn_memfree. since the browser and plug-ins share the same memory space, npn_memalloc allows plug-ins to take advantage of any customized memory allocation scheme the application may have, and allows the application to manage its memory more flexibly and efficiently. mac os npn_memalloc is particularly important on mac os, since the mac os version of the browser frequently fills its memory partition with cached data that is only purged as necessary. since npn_memalloc automatically fr...
NPN_PostURL - Archive of obsolete content
url url of the request, specified by the plug-in. ...
... ftp (upload a file). plug-ins can use this function to post form data to cgi scripts using http or upload files to a remote server using ftp. you cannot use npn_posturl to specify headers (even a blank line) in a memory buffer. to do this, use npn_posturlnotify. for protocols in which the headers must be distinguished from the body, such as http, the buffer or file should contain the headers, followed by a blank line, then the body. if no custom headers are required, simply add a blank line ('\n') to the beginning of the file or buffer. npn_posturl is typically asynchronous: it returns immediately and only later handles the request. for this reason, you may find it useful to call npn_posturlnotify instead; this function notifies your plug-in upon successful or unsuccessful completion of the ...
NPN_PostURLNotify - Archive of obsolete content
ion of the result. syntax #include <npapi.h> nperror npn_posturlnotify(npp instance, const char* url, const char* target, uint32 len, const char* buf, npbool file, void* notifydata); parameters the function has the following parameters: instance current plug-in instance, specified by the plug-in. url url of the post request, specified by the plug-in. target target window, specified by the plug-in. for values, see npn_geturl. len length of the buffer buf. buf path to local temporary file or data buffer that contains the data to post. file...
...file or data buffer that contains the data to post. file whether to post a file. values: true: post the local file whose path is specified in buf, then delete the file. false: post the raw data in buf. notifydata plug-in-private value for associating the request with the subsequent npp_urlnotify call, which returns this value (see description below). 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 npn_posturlnotify functions identically to npn_posturl, with these exceptions: npn_posturlnotify supports specifying headers when posting a memory buffer. npn_posturlnotify calls npp_urlnotify...
NPN_SetValue - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary implemented by browsers. this call is used to inform the browser of variable information controlled by the plugin. syntax #include <npapi.h> nperror npn_setvalue(npp instance, nppvariable variable, void *value); parameters the function has the following parameters: instance pointer to the plugin instance setting the variable. variable values the function can set: nppvpluginwindowbool: sets windowed/windowless mode for plugin display; true=windowed, false=windowless nppvplugintransparentbool: sets transparent mode for display of a plugin; true=transparent, false=opaque nppvjavaclass nppvpluginwindowsize nppvplugintimerinterval nppvplu...
...etvalue any time with nppvpluginkeeplibraryinmemory as variable parameter and value set to true. by default, the dll will be unloaded from memory preceded by an np_shutdown call. remarks all four variable values are boolean. although the function prototype has type of value void *, the actual boolean should be placed there, not a pointer to a boolean. the browser code reads this parameter as follows (nppvpluginwindowbool as an example): nperror np_export _setvalue(npp npp, nppvariable variable, void *value) { ... bool bwindowless = (value == null); ... } so the proper way to call this function from a plug-in would be: bool bwindowed = false; npn_setvalue(npp, nppvpluginwindowbool, ( void *)bwindowed); see also npp_new, npn_getvalue, npp_setvalue, npp_getvalue ...
NPN_SetValueForURL - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary allows a plugin to change the stored information associated with a url, in particular its cookies. (while the api theoretically allows the preferred proxy for a given url to be changed, doing so does not have much meaning given how proxies are configured, and is not supported.) syntax #include <npapi.h> typedef enum { npnurlvcookie = 501, npnurlvproxy } npnurlvariable; nperror npn_setvalueforurl(npp instance, npnurlvariable variable, const char *url, const char *value, uint32_t len); parameters this function has the following parameters: instance pointer to the current plug-in instance. variable selects the ty...
...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 ...
NPP_NewStream - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary notifies a plug-in instance of a new data stream. syntax #include <npapi.h> nperror npp_newstream(npp instance, npmimetype type, npstream* stream, npbool seekable, uint16* stype); parameters the function has the following parameters: instance pointer to current plug-in instance. type pointer to mime type of the stream. stream pointer to new stream. seekable boolean indicating whether the stream is seekable: true: seekable. stream supports random access through calls to npn_requestread (for example, local files or http servers that support byte-range requests). false: not seekable. the browser ...
...ssively as it arrives from the network or file system. np_asfileonly: the browser saves stream data to a file in the local cache. when the stream is complete, the browser calls npp_streamasfile to deliver the path of the file to the plug-in. if the stream comes from a local file, the npp_write and npp_writeready functions are not called. npp_streamasfile is simply called immediately. this mode allows the plug-in full random access to the data using platform-specific file operations. np_asfile: file download. differs from np_asfileonly in that data is delivered to the plug-in, through a series of calls to npp_writeready and npp_write, as it is saved to the file (as in mode np_normal). when the stream is complete, the browser calls npp_streamasfile to deliver the path of the file to the plug-...
NPP_SetWindow - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary tells the plug-in when a window is created, moved, sized, or destroyed. syntax #include <npapi.h> nperror npp_setwindow(npp instance, npwindow *window); parameters the function has the following parameters: instance pointer to the current plug-in instance. must be embedded or full-screen. window pointer to the window into which the instance draws. the window structure contains a window handle and values for top left corner, width, height, and clipping rectangle (see note on unix below). 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 browser calls npp_set...
...subsequent calls to npp_setwindow indicate changes in size or position; these calls pass the same npwindow object each time, but with different values. if the window handle is set to null, the window is destroyed. ...
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...
...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 ...
NPStream - Archive of obsolete content
e browser and consumed by the plug-in, or produced by the plug-in and consumed by the browser. syntax typedef struct _npstream { void* pdata; /* plug-in private data */ void* ndata; /* netscape private data */ const char* url; uint32 end; uint32 lastmodified; void* notifydata; const char *headers; } npstream; fields the data structure has the following fields: plug-in-private value that the plug-in can use to store a pointer to private data associated with the instance; not modified by the browser. ndata browser-private value that can store data associated with the instance; should not be modified by the plug-in. url the url that the data in the stream is read from or written to. end offset in bytes of the end of the stream (equivalent to...
...f 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 browser: the browser creates the npstream object and passes it to the plug-in initiall...
NPWindow - Archive of obsolete content
mac os: window is a pointer to an np_port. x, y the x and y coordinates for the top left corner of the plug-in relative to the page (and thus relative to the origin of the drawable). should not be modified by the plug-in. height, width the ...
... npwindow instance represents a window or a drawable. values: npwindowtypewindow: indicates that the window field holds a platform-specific handle to a window (as in navigator 2.0 and navigator 3.0). the plug-in is considered windowed. npwindowtypedrawable: indicates that the plugin is windowless. the window field holds a platform-specific handle to a drawable or an off-screen pixmap, as follows: windows: hdc mac os: pointer to np_port structure unix/x11: not used. (the drawable is provided in a graphicsexpose event, when the paint is requested.) description the npwindow structure represents the native window or a drawable, and contains information about coordinate position, size, whether the plug-in is windowed or windowless, and some platform-specific inf...
NP_GetValue - Archive of obsolete content
instance parameter is null because no instance has been created. variable plug-in information the call gets. values: nppvpluginnamestring: gets the name of the plug-in nppvplugindescriptionstring: gets the description string of the plug-in value plug-in name, returned by the function. ...
...instance parameter is null because no instance has been created. variable plug-in information the call gets. values: nppvpluginnamestring: gets the name of the plug-in nppvplugindescriptionstring: gets the description string of the plug-in value plug-in name, returned by the function. ...
NP_Port - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary used on mac os only contains information required by the window field of an npwindow structure. syntax typedef struct np_port { cgrafptr port; /* grafport */ int32 portx; /* position inside the topmost window */ int32 porty; } np_port; fields the data structure has the following fields: port standard mac os port into which the plug-in should draw. portx, porty top-left corner of the plug-in rectangle in port coordinates (taking the scroll position into account). description on mac os, the window field of an npwindow structure points to an np_port object, which is allocated by the browser. the np_port is valid for the lifetime of the npwindow, that is, until npp_setwindow is called again with a...
... description on mac os, the window field of an npwindow structure points to an np_port object, which is allocated by the browser. the np_port is valid for the lifetime of the npwindow, that is, until npp_setwindow is called again with a different value or the instance is destroyed. since the port is shared between the plug-in and other plug-ins and the browser, the plug-in should always do the following: draw only within the area designated by the npwindow. save the current port settings before changing the port for drawing. set the desired port settings before drawing. restore the previous port settings after drawing. see also npp_setwindow, npwindow ...
Why Well-Formed Web RSS Module is Popular - Syndicating Your Comments - Archive of obsolete content
there aren't many blogs out there that don't allow commenting of blog posts. however, rss does not provide sufficient facilities for dealing with them. sure rss has the <comments> element, but it points to a html page that isn't machine readable. it is desirable to be able to deal with comments in the same way one deals with rss feeds; through syndication. the rss well-formed web module exists to fill this gap. ...
...ide sufficient facilities for dealing with them. sure rss has the <comments> element, but it points to a html page that isn't machine readable. it is desirable to be able to deal with comments in the same way one deals with rss feeds; through syndication. the rss well-formed web module exists to fill this gap. ...
Proposal - Archive of obsolete content
"in development" means that they are still working on it and trying to come up with a draft. those labeled with "draft exists" can be implemented, but be warned that they could radically change. name description status easy news topics easy news topics (ent) is intended to be a very simple standard for describing how topic information can be introduced into an rss2.0 news feed. ...
...ing works better with rss. uses an http "content-type" parameter to hint at an rss feeds disposition type -- to hint at what is being syndicated. in development rsshints a module that adds elements to a feed that help an aggregator process them. draft exists source guid when an rss item is posted in response to a previous item (called the source item) rss 2.0 offers the source element which allows the item to refer to the rss feed which contains the source item. the sguid specification provides a more granular approach by offering an sourceref element which can reference the guid permalink of the source. draft exists <title>proposals</title> ...
Version - Archive of obsolete content
note: there are 3 different versions of rss 0.91. ...
... note: there are 3 different versions of rss 0.91. ...
NSPR Release Engineering Guide - Archive of obsolete content
this paper is for engineers performing formal release for the netscape portable runtime (nspr) across all platforms. nspr generally follows the iplanet product lifecycle. feature complete update ...pr/include/prinit.h with release numbers build all targets, debug and optimized on all platforms using local directories run the test suite on all targets verify release numbers show up in binaries resolve testing anomalies tag the tree with nsprpub_release_x_y_z_beta beta release checkout a whole new tree using the tag from above build all targets, debug and optimized on all platforms using the command: gmake release mdist=<dir>/mdist build_number=vx.y.z [build_opt=1 | use_debug_rtl=1] copy the bits from mdist to /share/builds/components/nspr20/.vx.y.z 1 run ...
...copy /share/builds/components/nspr20/vx.y.z/* to /share/systems/mozilla/pub/nspr/vx.y.z/ original document information author: larryh@netscape.com last updated date: september 20, 2000 1 copying files to /share/builds/components requires that...
SSL and TLS - Archive of obsolete content
uthentication occur over ssl/tls. ssl/tls uses a combination of public key and symmetric-key encryption. symmetric-key encryption is much faster than public-key encryption, but public-key encryption provides better authentication techniques. an ssl/tls session always begins with an exchange of messages called the ssl handshake, initial communication between the server and client. the handshake allows the server to authenticate itself to the client using public-key techniques, then allows the client and the server to cooperate in the creation of symmetric keys used for rapid encryption, decryption, and tamper detection during the session that follows. both of these protocols support using a variety of different cryptographic algorithms, or ciphers, for operations such as authenticating the s...
... 64-bit machines, consider using stronger keys. all cas should use at least 2048-bit keys, and stronger keys (such as 3072 or 4096 bits) if possible. as pkis using rsa keys and certificates transition to other cryptographic systems like ecc, servers should continue to support rsa. supported cipher suites for rsa cipher suites with the rsa key exchange that are commonly supported include the following: aes and sha message authentication. advanced encryption standard (aes) ciphers have a fixed block size of 128-bits, and the keys can be either 128-bit or 256-bit. there are 3.4 x 1038 possible 128-bit keys and 1.1 x 1077 possible 256-bit keys. there are more possible keys than any other cipher, making aes the strongest cipher supported by ssl. these cipher suites are fips-compliant. tripl...
Vulnerabilities - Archive of obsolete content
are present in all systems. a vulnerability is a weakness in a system that can be exploited to negatively impact confidentiality, integrity, and/or availability. there are many ways in which vulnerabilities can be categorized. this article uses three high-level vulnerability categories: software flaws, security configuration issues, and software feature misuse. these categories are described below. ...
... a security configuration setting is an element of a software’s security that can be altered through the software itself. ...
Sunbird Theme Tutorial - Archive of obsolete content
that registers the theme with sunbird some files containing the theme itself set up your theme in sunbird's profile directory. for information on how to find the profile directory, see the mozillazine article: profile folder inside the profile directory, go to the <tt>extensions</tt> directory. note: if the <tt>extensions</tt> directory is empty, you are in the wrong place—start again and follow the instructions more carefully. creating a unique identifier create an identifier that is likely to be unique, in the form: <tt>something@domain-name</tt> it must contain an at-sign (<tt>@</tt>), making it look something like an e-mail address, but it does not need to be a real e-mail address. before and after the at-sign, it can only contain the characters a-z, a-z, 0-9, full stop, hyphen ...
...r theme, change the css and image files in any way you like. for testing purposes, go to the <tt>calendar</tt> directory that you have just pasted. edit the file <tt>calendar.css</tt> there. add this line at the end: label {color: red;} save the file. fixing bug 320823 if you are using the sunbird 0.3a1 release, or a test build before 2005-12-21, then you must apply a fix for bug 320823 to allow sunbird to use themes. go to sunbird's program directory, then to the <tt>defaults</tt> directory there. in the <tt>pref</tt> directory, edit the file <tt>sunbird.js</tt> and search for the <tt>pref("extensions</tt> entries. add the line: pref("extensions.dss.enabled", false); save the file. using your theme to use your theme, restart sunbird. from the menu bar, choose tools – themes... in...
Create Your Own Firefox Background Theme - Archive of obsolete content
will be anchored to the top-right corner of the browser window. view a sample theme header here. image requirements dimensions should be 3000px wide × 200px high png or jpg file format image must be no larger than 300 kb in file size tips subtle, soft contrast images and gradients work best; highly detailed images will compete with the browser ui. firefox may reveal more of the lower portion of the image if another toolbar or other ui element is added to the top of the window. the upper right-hand side of the image should have the most important information—as a user increases the width of the browser window, the browser reveals more of the left-hand side of the image. online image editor resources pixlr — pixlr offers professional and easy-to-use tools for creati...
...tom of the window. the left-hand side of the image should have the most important information—as a user increases the width of the browser window, the browser reveals more 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 changes in Firefox 4 - Archive of obsolete content
theme is free to use icons of any size. however, the theme should be designed in such a way that the above add-on button icon sizes fit correctly. note: add-ons always use a 24x24 pixels icon when the button is displayed in the toolbar customization palette. default values of the iconsize attribute on browser toolbars if the theme doesn't override the value of the iconsize attribute, the following defaults are used: toolbar element id default iconsize value menu bar #toolbar-menubar small navigation bar #nav-bar small or large depending on user preference. bookmarks toolbar #personaltoolbar small tab bar #tabstoolbar small add-on bar #addon-bar small custom toolbars some other value ...
...stall.rdf and preview.png from <firefox-app-bundle>/contents/macos/extensions/{...} into my_theme. finally, you need to create a chrome.manifest file with the contents: skin browser classic/1.0 chrome/browser/ skin communicator classic/1.0 chrome/communicator/ skin global classic/1.0 chrome/global/ skin mozapps classic/1.0 chrome/mozapps/ this results in the following structure : /my_theme/chrome/browser/* /my_theme/chrome/communicator/* /my_theme/chrome/global/* /my_theme/chrome/mozapps/* /my_theme/chrome.manifest /my_theme/icon.png /my_theme/install.rdf /my_theme/preview.png note: for more information (and how to package into a jar) consult creating a skin for firefox which still mostly applies. most likely you must replace all occurences of classic/1...
Scratchpad - Archive of obsolete content
ed 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 permission policies allow that. but even with possible limitations present, the html code can be either manually entered or copied from the source and pasted into the "about:blank" page (a new empty tab) with the use page inspector's edit as html context menu command. usage opening scratchpad in its own window there are several different ways to open scratchpad in its own window: press shift + f4, or go to the web ...
... javascript code snippets, so you can reuse code later if you like. code completion scratchpad integrates the tern code analysis engine, and uses that to provide autocomplete suggestions and popups containing information on the current symbol. to list autocomplete suggestions, press ctrl + space. for example, try typing d, then pressing ctrl + space. you'll see the autocomplete box, as shown below: the icon next to each suggestion indicates the type, and the currently highlighted suggestion gets a popup with more information. ↑ and ↓ cycle through the suggestions and enter or tab select the highlighted choice. inline documentation to show the inline documentation popup, press ctrl + shift + space when the cursor is on an identifier. for example, if you type document.addeventlistener...
Using IO Timeout And Interrupt On NT - Archive of obsolete content
this technical memo is a cautionary note on using netscape portable runtime's (nspr) io timeout and interrupt on windows nt 3.51 and 4.0. due to a limitation of the present implementation of nspr io on nt, programs must follow the following guideline: if a thread calls an nspr io function on a file descriptor and the io function fails with <tt>pr_io_timeout_error</tt> or <tt>pr_pending_interrupt_error</tt>, the file descriptor must be closed before the thread exits. in this memo we explain the problem this guideline is trying to work around and discuss its limitations. nspr io on nt the io model of nspr 2.0 is synchronous and blocking. a thread calling an io function is blocked until the io operation finishes, either due to a successful io completion or an error. if the io operatio...
...s 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, but the second <tt>pr_close()</tt> would be freeing freed memory. a solution that may wo...
-ms-content-zoom-limit - Archive of obsolete content
fies 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 of the shorthand:-ms-content-zoom-limit-max: as specified-ms-content-zoom-limit-min: as sp...
... 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. ...
-ms-hyphenate-limit-chars - Archive of obsolete content
equired 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. <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 a...
...ger>{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 any specification. ...
-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 v...
... formal syntax auto | after specifications not part of any specification. ...
-ms-scroll-chaining - Archive of obsolete content
entsinheritednocomputed valueas specifiedanimation typediscrete syntax values chained initial value. the nearest scrollable parent element begins scrolling when the user hits a scroll limit during any manipulation. no bounce effect is shown. none a bounce effect is shown when the user hits a scroll limit during any manipulation. formal syntax chained | none examples the following example illustrates the -ms-scroll-chaining property in use. in this case the image container has its -ms-scroll-chaining 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 ob...
...rollable 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. .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 on...
-ms-scrollbar-base-color - Archive of obsolete content
[ / <alpha-value> ]? ) | hsla( <hue>, <percentage>, <percentage>, <alpha-value>? )where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples this example uses -ms-scrollbar-base-color and -ms-scrollbar-arrow-color to create two <div> objects with different scroll bar color schemes. ...
... <body> <div class="aquascroll"> lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </div> <div class="bisquescroll"> lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </div> </body> the following image shows the result. note that scrollbar-base-color sets the scroll bar face color and highlight color to different shades of the same base color. specifications not part of any specification. ...
-ms-scrollbar-track-color - Archive of obsolete content
a( <hue>, <percentage>, <percentage>, <alpha-value>? )where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples this example uses -ms-scrollbar-track-color, -ms-scrollbar-face-color, and -ms-scrollbar-arrow-color to create two <div> elements with different scroll bar color schemes. ...
... ...
::-ms-browse - Archive of obsolete content
other properties are ignored. ...
... browser compatibility historically supported in internet explorer and edge before version 79. ...
::-ms-clear - Archive of obsolete content
sed, non-empty text controls. this includes inputs that appear text-like or fall back to type="text". such inputs include: <input type="color"> <input type="date"> <input type="datetime"> <input type="datetime-local"> <input type="email"> <input type="month"> <input type="number"> <input type="search"> <input type="tel"> <input type="time"> <input type="url"> <input type="week"> allowable properties only the following css properties can be used in a rule with ::-ms-clear in its selector. other properties are ignored. -ms-high-contrast-adjust background-clip background-color background-image background-origin background-position-x background-position-y background-repeat background-size border-bottom-color border-bottom-left-radius border-bottom-right-radius bor...
... ...
::-ms-expand - Archive of obsolete content
other properties are ignored. ...
...other properties are ignored. ...
::-ms-fill - Archive of obsolete content
only animation-name applies to an indeterminate one. (a progress bar is determinate if it has a value attribute set; otherwise it is indeterminate. ...
... 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 turns off the animation so that no dots are displayed. -ms-bar shows animated dots that flow in a bar pattern. -ms-ring shows animated dots that flow in a ring pattern. allowable properties only the following css properties can be used in a rule with ::-ms-fill in its selector. other properties are ignored. animation-name background-clip, background-color, background-image, background-origin, background-repeat, and background-size border border-radius box-shado...
::-ms-track - Archive of obsolete content
input type="range">. applying the color property within the ::-ms-track selector affects the tick marks inside the track area. it is possible to use the ::-ms-ticks-after, ::-ms-ticks-before, and ::-ms-track pseudo-elements together. to do so would create three sets of tick marks, but the best user experience is one set. to remove tick marks altogether, set the color property to transparent. allowable properties only the following css properties can be used in a rule with ::-ms-track in its selector. other properties are ignored. background-clip background-color background-image background-origin background-repeat background-size border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-left-color border-left-sty...
...tyle font-weight height margin-bottom margin-left margin-right margin-top -ms-background-position-x -ms-background-position-y -ms-high-contrast-adjust opacity outline-color outline-style outline-width padding-bottom padding-left padding-right padding-top transform transform-origin visibility width syntax ::-ms-track see also ::-ms-thumb ::-ms-fill-upper ::-ms-fill-lower ::-webkit-slider-runnable-track ::-moz-range-track css-tricks: styling cross-browser compatible range inputs with css quirksmode: styling and scripting sliders ...
::-ms-value - Archive of obsolete content
other properties are ignored. ...
...other properties are ignored. ...
Displaying notifications (deprecated) - Archive of obsolete content
tent, using the standard notification system provided by the operating system. for example, on android, notifications appear in the bar at the top of the screen, and in the panel that appears when you drag that bar downward. creating a notification the first thing you need to do is create the notification object by using the navigator.moznotification object's createnotification() method, as follows: var notification = navigator.moznotification.createnotification( "hey, check this out!", "this is a notification posted by " + "firefox 4. you should take some action. right now!"); this returns a new notification object, but does not actually display the notification. this lets you configure the event listeners before the notification is shown, if you need to be notified whe...
... view live examples ...
Accessing XML children - Archive of obsolete content
"].appendchild(<quux/>); adds a child to the "bar" child node of element1. this gives an xml document of <foo> <bar> <baz/> <quux/> </bar> </foo> note, however, that assigning a non-xml value to a child element that doesn't exist will create that element. var element1 = <foo/> element1.bar = 1; produces <foo> <bar>1</bar> </foo> if the child node already exists, the . operator allows you to change its value. var elem = <foo> <bar>1</bar> </foo> elem.bar = 2; will replace the previous value of 1 with 2. you can remove a child node by using the delete command: var elem = <foo> <bar/> <baz/> </foo> delete elem.bar; leaves just <foo> <baz/> </foo> the . operator can also be used to replace particular child nodes ...
...omments[0]); // returns <!-- abc --> the * selector will return all child nodes in an xml list. var a = <foo> <bar/> <baz/> </foo>; var list = a.*; list.length(); // returns 2 element attributes many xml elements have attributes with particular values assigned to them. for instance <pets> <dog color="brown">fido</dog> <cat color="grey">fluffy</cat> </pets> e4x allows you to access the attributes of a particular element with the .@ operator. the most basic case would look something like. var element = <foo bar="1"/> element.@bar = 2; which gives <foo bar="2"/> « previousnext » ...
The global XML object - Archive of obsolete content
« previous the global xml object e4x-capable javascript engines put a new property on the global object. the xml object has several properties that allow you to customize parsing and serialization of e4x. xml elements will remember the settings of the xml object from the time of their creation. extending xml.prototype xml.prototype and xmllist.prototype (xmllist.prototype is actually just xml.prototype) cannot be extended in the same conventional way as other constructors such as object. you can only define methods in xml.prototype and not fields. ...
...r creation. extending xml.prototype xml.prototype and xmllist.prototype (xmllist.prototype is actually just xml.prototype) cannot be extended in the same conventional way as other constructors such as object. you can only define methods in xml.prototype and not fields. to add a method to xml.prototype, define xml.prototype.function::methodname or xml.prototype.function::[methodnamestring]. the following example defines the foocount() method, which returns the amount of <foo> elements in the xml: xml.prototype.function::foocount = function foocount() { return this..foo.length(); }; <foobar><foo/><foo/><foo/></foobar>.foocount() // returns 3 ignorecomments true by default. this property tells e4x to ignore comment nodes when serializing and filtering. this means that if ignorecomments is tr...
ArrayBuffer.transfer() - Archive of obsolete content
ngth is undefined, the bytelength of the oldbuffer is used. this operation leaves oldbuffer in a detached state. syntax arraybuffer.transfer(oldbuffer [, newbytelength]); parameters oldbuffer an arraybuffer object from which to transfer. newbytelength the byte length of the new arraybuffer object. return value a new arraybuffer object. description the arraybuffer.transfer() method allows you to grow and detach arraybuffer objects. the ability to grow an arraybuffer without copying has the advantage of being much faster for large buffers (similar to realloc). the ability to detach an arraybuffer gives the developer explicit control over when the underlying memory is released. this avoids having to drop all references and wait for garbage collection. examples var buf1 = new arr...
...(buf1)[0] = 42; var buf2 = arraybuffer.transfer(buf1, 80); buf1.bytelength; // 0 but if you use the polyfill then the value is still 40 buf2.bytelength; // 80 new int32array(buf2)[0]; // 42 var buf3 = arraybuffer.transfer(buf2, 0); buf2.bytelength; // 0 but if you use the polyfill then the value is still 80 buf3.bytelength; // 0 polyfill you can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of transfer() in browsers that do not natively support it. this is not the exact equivalent of this api because browsers that natively support it are be able to internally use the c++ function realloc() which extends the length of the memory and only copies it to a new location as-needed as opposed to the followin...
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
troduced after ecmascript 2015. new versions of ecmascript specifications are released yearly. so far, es2016, es2017, and es2018 have been released. this year, the es2019 specification will be released and es2020 is the current ecmascript draft specification. you can see the latest proposals on the tc39/ecma262 github repository. a channel for feedback on ecmascript standards is es-discuss. below is a list of features in es2016+ and what version of firefox they were implemented in. ecmascript 2016 array.prototype.includes() (firefox 43) typedarray.prototype.includes() (firefox 43) exponentiation operator (firefox 52) ecmascript 2017 object.values() (firefox 47) object.entries() (firefox 47) string.prototype.padstart() (firefox 48) string.prototype.padend() (firefox 48) obje...
...efox 63) string.trimstart() and string.trimend() (firefox 61) optional catch binding (firefox 58) function.tostring() revision (firefox 54) symbol.description (firefox 63) well-formed json.stringify() (firefox 64) ecmascript 2020 this is the current es.next version. implemented proposals not in es.next this section needs to be updated to reflect current changes. (may 2019) the following features are already implemented, but only available in the firefox nightly channel and not yet included in a draft edition of an ecmascript specification. additions to the arraybuffer object arraybuffer.transfer() (spec) new typedobject objects based on typed objects draft, and exposed via a global typedobject object, e.g. typedobject.structtype & typedobject.arraytype. this feature ...
ActiveXObject - Archive of obsolete content
object. to create an automation object, assign the new activexobject to an object variable: var excelapp = new activexobject("excel.application"); var excelsheet = new activexobject("excel.sheet"); this code starts the application creating the object (in this case, a microsoft excel worksheet). once an object is created, you refer to it in code using the object variable you defined. in the following example, you access properties and methods of the new object using the object variable excelsheet and other excel objects, including the application object and the activesheet.cells collection. // make excel visible through the application object. excelsheet.application.visible = true; // place some text in the first cell of the sheet. excelsheet.activesheet.cells(1,1).value = "this is column...
.... // make excel visible through the application object. excelsheet.application.visible = true; // place some text in the first cell of the sheet. excelsheet.activesheet.cells(1,1).value = "this is column a, row 1"; // save the sheet. excelsheet.saveas("c:\\test.xls"); // close excel with the quit method on the application object. excelsheet.application.quit(); requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards. not supported in windows 8.x store apps. note: creating an activexobject on a remote server is not supported in internet explorer 9 standards mode, internet explorer 10 standards mod...
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
ciated with the asynchronous operation. remarks call this function in the callback function for the asynchronous operation after the call to debug.mstraceasyncoperationcompleted. note: some debugging tools do not display the information sent to the debugger. asyncoperationid must correspond to the operation name previously returned from debug.mstraceasyncoperationstarting. example the following code provides an example of tracing an asynchronous call for a windows 8.x store app. function asyncwrapperfunction() { var opid = debug.mstraceasyncoperationstarting('async trace'); dosomethingasync().then(function (result) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_success); debug.mstraceasynccallbackstarting(opid); // process resul...
...not supported in windows 8. ...
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
us operation completes. asyncoperationid must correspond to the operation id previously returned from debug.mstraceasyncoperationstarting. the possible values for status include: debug.ms_async_op_status_success debug.ms_async_op_status_canceled debug.ms_async_op_status_error note: some debugging tools do not display the information sent to the debugger. example the following code provides an example of tracing an asynchronous call for a windows 8.x store app. function asyncwrapperfunction() { var opid = debug.mstraceasyncoperationstarting('async trace'); dosomethingasync().then(function (result) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_success); debug.mstraceasynccallbackstarting(opid); // process resul...
...not supported in windows 8. ...
Debug.setNonUserCodeExceptions - Archive of obsolete content
operty 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. (function () { debug.setnonusercodeexceptions = true; try{ var x = null; x.y(); } catch (e) { // catch the exception. } })(); 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). not su...
... to set this property. (function () { debug.setnonusercodeexceptions = true; try{ var x = null; x.y(); } catch (e) { // catch the exception. } })(); 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). not supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards. ...
Debug - Archive of obsolete content
indicates that an asynchronous operation has completed. debug.mstraceasyncoperationstarting initiates a trace for an asynchronous operation. debug.msupdateasynccallbackrelation updates the relationship status between a synchronous work item and the associated asynchronous operation. debug.write sends strings to the script debugger. ...
...he associated asynchronous operation. debug.write sends strings to the script debugger. debug.writeln sends strings to the script debugger, followed by a newline character. examples print the value of a variable this example uses the write function to display the value of the variable. var counter = 42; debug.write("the value of counter is " + counter); requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). ...
Enumerator.atEnd - Archive of obsolete content
r. the enumerator.atend method returns a boolean 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. ...
...not supported in windows 8.x store apps. applies to: enumerator object ...
Enumerator.moveFirst - Archive of obsolete content
non-standard. do not use! this object is a microsoft extension and is only supported in internet explorer. the enumerator.movefirst method resets the current item in the collection to the first item. syntax enumobj.movefirst( ) remarks the required enumobj reference is any enumerator object. if there are no items in the collection, the current item is set to undefined. ...
...not supported in windows 8.x store apps. applies to: enumerator object ...
Enumerator.moveNext - Archive of obsolete content
his object is a microsoft extension and is only supported in internet explorer. the enumerator.movenext method moves the current item to the next item in the collection. syntax enumobj.movenext( ) remarks the required enumobj reference is any enumerator object. if the enumerator is at the end of the collection or the collection is empty, the current item is set to undefined. ...
...not supported in windows 8.x store apps. applies to: enumerator object ...
Enumerator - Archive of obsolete content
emarks collections differ from arrays in that the members of a collection are not directly accessible. instead of using indexes, as you would with arrays, you can move the current item pointer only to the first or next element of a collection. the enumerator object provides a way to access any member of a collection and behaves similarly to the for...each statement in vbscript. ...
...t has no properties. methods enumerator.atend returns a boolean value indicating if the enumerator is at the end of the collection. enumerator.item returns the current item in the collection. enumerator.movefirst resets the current item in the collection to the first item. enumerator.movenext moves the current item to the next item in the collection. requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards. not supported in windows 8.x store apps. ...
Error.description - Archive of obsolete content
description of the error. remarks the description property contains the error message string associated with a specific error. use the value contained in this property to alert a user to an error. the description and message properties provide the same functionality; the descriptionproperty provides backward compatibility; the message property complies with the ecma standard. example the following example illustrates the use of the description property. try { // cause an error: x = y } catch(e) { // prints "[object error]": document.write(e) document.write (" "); // prints 5009: document.write((e.number & 0xffff)) document.write (" "); // prints "'y' is undefined": document.write(e.description); document.write (" "); // prints "'y' is undefined": documen...
...ty. try { // cause an error: x = y } catch(e) { // prints "[object error]": document.write(e) document.write (" "); // prints 5009: document.write((e.number & 0xffff)) document.write (" "); // prints "'y' is undefined": document.write(e.description); document.write (" "); // prints "'y' is undefined": document.write(e.message) } requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). applies to: error object see also number property (error) message property (error) name property (error) ...
Error.number - Archive of obsolete content
net explorer. the error.number property 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: "); d...
... // cause an error. var x = y; } catch(e) { document.write ("error code: "); document.write (e.number & 0xffff) document.write ("<br />"); document.write ("facility code: ") document.write(e.number>>16 & 0x1fff) document.write ("<br />"); document.write ("error message: ") document.write (e.message) } example the output of this code is as follows. error code: 5009 facility code: 10 error message: 'y' is undefined requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). applies t...
ScriptEngineBuildVersion - Archive of obsolete content
not use! this object is a microsoft extension and is only supported in internet explorer. the scriptenginebuildversion function bets the build version number of the scripting engine in use. syntax scriptenginebuildversion() remarks the return value corresponds directly to the version information contained in the dynamic-link library (dll) for the scripting language in use. ...
...e return value corresponds directly to the version information contained in the dynamic-link library (dll) for the scripting language in use. example the following example illustrates the use of the scriptenginebuildversion function: if(window.scriptenginebuildversion) { console.log(window.scriptenginebuildversion()); } // output: <current build version> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet 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 ...
ScriptEngineMajorVersion - Archive of obsolete content
o not use! this object is a microsoft extension and is only supported in internet explorer. the scriptenginemajorversion function gets the major version number of the scripting engine in use. syntax scriptenginemajorversion() remarks the return value corresponds directly to the version information contained in the dynamic-link library (dll) for the scripting language in use. ...
... remarks the return value corresponds directly to the version information contained in the dynamic-link library (dll) for the scripting language in use. example the following example illustrates the use of the scriptenginemajorversion function: if (window.scriptenginemajorversion) { console.log(window.scriptengine()); } output: <current major version> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). ...
ScriptEngineMinorVersion - Archive of obsolete content
not use! this object is a microsoft extension and is only supported in internet explorer. the scriptengineminorversion function gets the minor version number of the scripting engine in use. syntax scriptengineminorversion() remarks the return value corresponds directly to the version information contained in the dynamic-link library (dll) for the scripting language in use. ...
... return value corresponds directly to the version information contained in the dynamic-link library (dll) for the scripting language in use. example the following example illustrates the use of the scriptengineminorversion function. if (window.scriptengineminorversion) { console.log(window.scriptengineminorversion()); } //output: <current minor version> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). ...
VBArray.dimensions - Archive of obsolete content
non-standard. do not use! this object is a microsoft extension and is only supported in internet explorer. the vbarray.dimensions method 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 ty...
...not supported in windows 8.x store apps. applies to: vbarray object ...
VBArray.getItem - Archive of obsolete content
ion and is only supported in internet explorer. the vbarray.getitem method returns the item at the specified location. syntax safearray.getitem(dimension1[, dimension2, ...], dimensionn) parameters safearray a vbarray object. dimension1, ..., dimensionn specifies the exact location of the desired element of the vbarray. n equals the number of dimensions in the vbarray. 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 iterates the visual basic safe array and prints out the contents of each element. 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> <s...
...not supported in windows 8.x store apps. see version information. applies to: vbarray object ...
VBArray.toArray - Archive of obsolete content
a vbarray. syntax safearray.toarray( ) remarks the required safearray reference is a vbarray object. the conversion translates the multidimensional vbarray into a single dimensional javascript array. each successive dimension is appended to the end of the previous one. for example, a vbarray with three dimensions and three elements in each dimension is converted into a javascript array as follows: suppose the vbarray contains: (1, 2, 3), (4, 5, 6), (7, 8, 9). after translation, the javascript array contains: 1, 2, 3, 4, 5, 6, 7, 8, 9. there is currently no way to convert a javascript array into a vbarray. 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 converts the visu...
...not supported in windows 8.x store apps. applies to: vbarray object ...
VBArray.ubound - Archive of obsolete content
safearray a vbarray object. dimension optional the dimension of the vbarray for which the higher bound index is wanted. if omitted, ubound behaves as 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.
...not supported in windows 8.x store apps. applies to: vbarray object ...
@set - Archive of obsolete content
mode and windows 8.x store apps. conditional compilation is supported in internet explorer 10 standards mode and in all earlier versions. the @set statement creates variables used with conditional compilation statements. syntax @set @varname = term parameters varname valid javascript variable name. must be preceded by an "@" character at all times. term zero or more unary operators followed by a constant, conditional compilation variable, or parenthesized expression. remarks numeric and boolean variables are supported for conditional compilation. strings are not. variables created using @set are generally used in conditional compilation statements, but can be used anywhere in javascript code. examples of variable declarations look like this: @set @myvar1 = 12 @set @myvar2 = ...
...enthesized expression. remarks numeric and boolean variables are supported for conditional compilation. strings are not. variables created using @set are generally used in conditional compilation statements, but can be used anywhere in javascript code. examples of variable declarations look like this: @set @myvar1 = 12 @set @myvar2 = (@myvar1 * 20) @set @myvar3 = @_jscript_version the following operators are supported in parenthesized expressions: ! ~ * / % + - << >> >>> < <= > >= == != === !== & ^ | && | | if a variable is used before it has been defined, its value is nan. nan can be checked for using the @if statement: @if (@newvar != @newvar) ... this works because nan is the only value not equal to itself. requirements s...
New in JavaScript 1.5 - Archive of obsolete content
this version was included in netscape navigator 6.0 was released on november 14, 2000 and was also used in later versions of netscape navigator and firefox 1.0. you can compare javascript 1.5 to jscript version 5.5 and internet explorer 5.5, which was released in july 2000. the corresponding ecma standard is ecma-262 edition 3 (from december 1999). new features in javascript 1.5 number.prototype.toexponential() number.prototype.tofixed() number.prototype.toprecision() const is now a reserved word. multiple catch clauses in a try...catch statement are supported. javascript authors can now add getters and setters to their objects. changed functionality in javascript 1.5 runtime errors are now reported as exceptions. ...
...mber.prototype.tofixed() number.prototype.toprecision() const is now a reserved word. multiple catch clauses in a try...catch statement are supported. javascript authors can now add getters and setters to their objects. changed functionality in javascript 1.5 runtime errors are now reported as exceptions. regular expression changes: quantifiers — +, *, ? and {} — can now be followed by a ? to force them to be non-greedy. non-capturing parentheses, (?:x) can be used instead of capturing parentheses, (x). when non-capturing parentheses are used, matched subexpressions are not available as back-references. positive and negative lookahead assertions are supported. both assert a match depending on what follows the string being matched. the m flag has been added to spec...
New in JavaScript 1.7 - Archive of obsolete content
this version was included in firefox 2 (october 2006). javascript 1.7 is a language update introducing several new features, in particular generators, iterators, array comprehensions, let expressions, and destructuring assignment. using javascript 1.7 in order to use some of the new features of javascript 1.7, you need to specify that you wish to use javascript 1.7. ...
...n: version(170); the features that require the use of the new keywords "yield" and "let" require you to specify version 1.7 because existing code might use those keywords as variable or function names. the features that do not introduce new keywords (destructuring assignment and array comprehensions) can be used without specifying the javascript version. new features in javascript 1.7 the following features added with javascript 1.7 were not part of an ecma-262 standard at the time. in more recent firefox versions, the implementation is updated to work with semantics as specified in ecmascript edition 6. please see the reference pages for differences. iterators and generators array comprehensions let statement (support for let expression was dropped in gecko 41, see bug 1023609). c...
New in JavaScript 1.8 - Archive of obsolete content
this version was included in firefox 3 and is part of gecko 1.9. see bug 380236 for a tracking development bug for javascript 1.8. using javascript 1.8 in order to use some of the new features of javascript 1.8 in html, use: <script type="application/javascript;version=1.8"> ... your code ... </script> another way (not recommended) to do this is to use the deprecated <script> language attribute and define it as "javascript1.8". when using the javascript shell, javascript xpcom components, or xul <script> elements, the latest js version (js1.8 in mozilla 1.9) is used automatically (bug 381031, bug 385159). ...
... that require the use of the new keywords "yield" and "let" require you to specify version 1.7 or higher because existing code might use those keywords as variable or function names. the features that do not introduce new keywords (such as generator expressions) can be used without specifying the javascript version. new features in javascript 1.8 expression closures. generator expressions. allowing you to simply create generators (which were introduced in javascript 1.7). typically you would have to create a custom function which would have a yield in it, but this addition allows you to use array comprehension-like syntax to create an identical generator statement. array.prototype.reduce() array.prototype.reduceright() changed functionality in javascript 1.8 changes in destructuring...
Object.prototype.watch() - Archive of obsolete content
: calling watch() on an object for a specific property overrides any previous handler attached for that property. examples using watch and unwatch const o = { p: 1 }; o.watch('p', (id, oldval, newval) => { console.log('o.' + id + ' changed from ' + oldval + ' to ' + newval); return newval; }); o.p = 2; o.p = 3; delete o.p; o.p = 4; o.unwatch('p'); o.p = 5; this script displays the following: o.p changed from 1 to 2 o.p changed from 2 to 3 o.p changed from undefined to 4 using watch() to validate an object's properties you can use watch to test any assignment to an object's properties. this example ensures that every person always has a valid name and an age between 0 and 200. class person { constructor(name, age) { this.watch('age', this._isvalidassignment.bind(this));...
... ...
JSException - Archive of obsolete content
| +----java.lang.exception | +----java.lang.runtimeexception | +----netscape.javascript.jsexception description jsexception is an exception which is thrown when javascript code returns an error. constructor summary the netscape.javascript.jsexception class has the following constructors: jsexception deprecated constructors optionally let you specify a detail message and other information. method summary the netscape.javascript.jsexception class has the following methods: getwrappedexception instance method getwrappedexception. getwrappedexceptiontype instance method getwrappedexceptiontype returns the int mapping of the type of the wrappedexcep...
...ect 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. ...
LiveConnect - Archive of obsolete content
e use of this restored api. the reimplementation also restores the ability to use try-catch exceptions within javascript, and is free of the increasing number of other bugs introduced by the decline of the original liveconnect (e.g., java.lang.string and arrays not working properly). liveconnect use by applets is enabled via the use of the "mayscript" attribute in applet tags on an html page, following which the applet may refer to classes in the netscape.javascript package to access javascript objects, and scripts may directly call applet methods (using the syntax document.applets.name.methodname()). standard java objects are also available for creation and manipulation by javascript code (e.g. by writing code like "new java.lang.string('javascript string')" for classes in the java.* packag...
... ...
JavaClass - Archive of obsolete content
around an instance of java.lang.class before you pass it as a parameter to a java method -- javaclass objects are not automatically converted to instances of java.lang.class. properties the properties of a javaclass object are the static fields of the java class. methods the methods of a javaclass object are the static methods of the java class. ...
...ass in the following example, x is a javaclass object referring to java.awt.font. because bold is a static field in the font class, it is also a property of the javaclass object. x = java.awt.font; myfont = x("helv", x.bold, 10); // creates a font object the previous example omits the packages keyword and uses the java synonym because the font class is in the java package. ...
JavaObject - Archive of obsolete content
inherits public data members from the java class of which it is an instance as properties. it also inherits public data members from any superclass as properties. methods inherits public methods from the java class of which it is an instance. the javaobject also inherits methods from java.lang.object and any other superclass. ...
...g("hello, world"); because the string class is in the java package, you can also use the java synonym and omit the packages keyword when you instantiate the class: var thestring = new java.lang.string("hello, world"); example: accessing methods of a java object because the javaobject thestring is an instance of java.lang.string, it inherits all the public methods of java.lang.string. the following example uses the startswith method to check whether thestring begins with "hello". var thestring = new java.lang.string("hello, world"); thestring.startswith("hello"); // returns true example: accessing inherited methods because getclass is a method of object, and java.lang.string extends object, the string class inherits the getclass method. consequently, getclass is also a method of the ...
Old Proxy API - Archive of obsolete content
re unstable. the spidermonkey implementation may not reflect the latest specification draft. it is subject to change anytime. it is provided as an experimental 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 met...
...ame, desc) { object.defineproperty(obj, name, desc); }, delete: function(name) { return delete obj[name]; }, fix: function() { if (object.isfrozen(obj)) { return object.getownpropertynames(obj).map(function(name) { return object.getownpropertydescriptor(obj, name); }); } // as long as obj is not frozen, the proxy won't allow itself to be fixed return undefined; // will cause a typeerror to be thrown }, // derived traps has: function(name) { return name in obj; }, hasown: function(name) { return object.prototype.hasownproperty.call(obj, name); }, get: function(receiver, name) { return obj[name]; }, set: function(receiver, name, val) { obj[name] = val; ret...
Examples - Archive of obsolete content
</p> <p> this document contains inline css r...
... */ body { padding-top: 8em; } html { color: #fff; background: #000 no-repeat fixed;} p {width: 30em; font-weight: bold;} ...
Sharp variables in JavaScript - Archive of obsolete content
the number represented by the digits serves as the variable's unique identifier, but leading 0s are ignored. scope sharp variables are only in scope in the statement in which they are defined. ...
...ows serialization of objects that have cyclic references or multiple references to the same object. warning: sharp variables was a non-standard syntax for creating or serializing cyclic data graphs that used to be supported only by mozilla's spidermonkey js engine. this feature has been removed in bug 566700, firefox 12. form sharp variables have the form of a sharp sign (#) immediately followed by one or more digits. the number represented by the digits serves as the variable's unique identifier, but leading 0s are ignored. scope sharp variables are only in scope in the statement in which they are defined. usage to create a sharp variable, simply assign an object to it in a line of code using an equal sign. you cannot assign primitives (including strings) to sharp variables. make ...
Standards-Compliant Authoring Tools - Archive of obsolete content
validation is done with html tidy, so you can verify standards compliance. ...
...validation is done with html tidy, so you can verify standards compliance. ...
background-size - Archive of obsolete content
znerd 04 august 2009 chrome, iron, icab4, omniweb etc. are based on webkit, like netscape 6-8, seamonkey, camino, flock, fennec, blackbird etc. 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. ...
...o ask for layout engines, not for browsers. [that said, the popularity of chrome let me think of a table row like safari, chrome (webkit) | 4.0, 2.0 (528). but i'm not able and willing spending time for this. remember 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 r...
XForms Output Element - Archive of obsolete content
g this control single-node binding special value - xpath expression whose evaluation result is used as the output's value. if binding attributes are present on the control then the value attribute is is ignored. type restrictions the output element can be bound to a node containing simple content of any data type. representations the xforms output element can be represented by the following widgets for the specified data types (or types derived from these data types): text - default representation for instance data of most types, especially static text (xhtml/xul). calendar - used to represent instance data of type date (xhtml/xul). image - if the instance node contains an image, then an output element can be used in combination with the mediatype element to display the image...
...ay the image (fx 3.0 only, xhtml/xul). text displaying the data as text is the default presentation. xforms output is most often used when a form author needs to render simple text of an instance node (xhtml/xul). characteristics text is presented to the user when there is no type given for the bound node or a type is specified that is not handled by one of the other widgets (as documented below). analogous widgets are <xhtml:span/> and <xul:description/> calendar a form author may notice a xforms output element represented by a calendar widget in the mozilla xforms processor if the control meets the following criteria (xhtml/xul). characteristics the bound instance node is of type xsd:date or a type derived from it in addition, the appearance attribute must also contain the value...
XForms Range Element - Archive of obsolete content
introduction allows the user to choose a value from within a specific range of values (see the spec). attributes ui common appearance - isn't supported. accesskey - used to specify the keyboard shortcut for focusing this control. single-node binding special incremental - supported, default value is false start - lower bound of possible values end - upper bound of possible values step - is used for incrementing/decrementing values start/end/step attributes if the value of the bound instance node is outside the range of values specified by the start and end attributes, then the range element receives a xforms-out-of-range event. if the bound value then becomes in range, the range element receives a xforms-in-range event. ...
...er bound of possible values step - is used for incrementing/decrementing values start/end/step attributes if the value of the bound instance node is outside the range of values specified by the start and end attributes, then the range element receives a xforms-out-of-range event. if the bound value then becomes in range, the range element receives a xforms-in-range event. start specifies the lower bound of 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.
XForms Repeat Element - Archive of obsolete content
ger> attribute based repeat when using xforms within host languages like xhtml, it is often necessary to create repeating structures within constructs such as html:table. thus, one might wish to use element repeat within a table to create the rows of a table, where each row of the table binds to a distinct member of a homogeneous collection. ...
...o use element repeat within a table to create the rows of a table, where each row of the table binds to a distinct member of a homogeneous collection. since html:table doesn't (and probably never will) allow xforms:repeat elements as children, another syntax is needed. to accommodate this, xforms 1.0 defines an alternative syntax that is functionally equivalent to the repeat element, using the following attributes: repeat-model repeat-bind repeat-nodeset repeat-startindex repeat-number additionally, when using xforms action setindex, its repeat attribute (which contains an idref) can point to any element carrying these repeat attributes. similarly, the index function can be used with the repeating structures created via these repeat-attributes. the id of the element that contains the repeat...
XForms Trigger Element - Archive of obsolete content
actions are described by the xforms action module (see the spec). attributes ui common appearance - the value of this attribute gives a hint to the xforms processor as to which type of widget(s) to use to represent this control accesskey - used to specify the keyboard shortcut for focusing this control single-node binding type restrictions the trigger element can be bound to a node containing data of any type. actually, the trigger element doesn't interact with the data 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. ...
...ng type restrictions the trigger element can be bound to a node containing data of any type. actually, the trigger element doesn't interact with the data 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. representations the xforms trigger element can be represented by the following widgets for the specified appearance attribute values: button - default representation (xhtml/xul) link/clickable text - used when appearance = 'minimal' (xhtml only) button displaying a button is the default presentation (xhtml/xul). characteristics analogous widgets are <html:input type="button"/> and <xul:button/> link/clickable text xforms authors can use this representation ...
XForms Upload Element - Archive of obsolete content
the xforms author can set the filter by using the mediatype attribute directly on the upload element or by placing a mediatype element (see the spec) as a direct child of the upload element. attributes ui common appearance - isn't supported. ...
...upported. incremental - isn't supported. type restrictions the upload element can be bound to a node of type xsd:anyuri, xsd:base64binary or xsd:hexbinary or any type derived from one of these. representations the xforms upload element is represented by visually combining three widgets: a text field that shows the uri of the selected file, a button to open the file picker dialog which allows the user to select a file, and a button to clear the text field and the reference to the file from the bound node (xhtml only). characteristics analogous widget is <xhtml:input type="file"/> ...
Fixing Incorrectly Sized List Item Markers - Archive of obsolete content
was corrected shortly after 0.9.4 was finished, the bug still affects all netscape 6.2.x versions, as well as compuserve 7.0. the problem in affected browsers, list item markers will very often appear to be too big compared to the text in the list item itself. this is most obvious in ordered lists, where the number that precedes each list item may be obviously different than the content that follows it. in fact, the markers were set to be a uniform size that did not change to match the content of the list items, so in rare cases the marker might actually appear to be smaller. see bug 110360, which explains the problem and shows when the fix was applied. in addition, when a document is displayed in "quirks" mode in mozilla 0.9.4 and later, the markers of lists will not use the font size of ...
...hen the fix was applied. in addition, when a document is displayed in "quirks" mode in mozilla 0.9.4 and later, the markers of lists will not use the font size of the list item text, but will instead stay the same as the user's default font size. see bug 97351 for more details. the solution fortunately, there are mozilla-specific css-like rules that can be used to correct both problems. the following rule is derived from mozilla's html.css file: *|*:-moz-list-bullet, *|*:-moz-list-number {font-size: 1em;} this rule tells gecko-based browsers to use the computed value of font-size for the marker's parent, which is the list item itself. thus the font sizes of the marker and the content will be the same. since this rule is not valid css, it will prevent the validation of any stylesheet tha...
Fixing Table Inheritance in Quirks Mode - Archive of obsolete content
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 rule sets all aspects of a table's font, except for the font family, to match the user's preferences setting, thus emulating the beha...
...ule 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 will override the rule in quirk.css and thus allow the author to have reliable inheritance of font styles into tables when in "quirks" mode. it is also fully valid css2 and so will validate without incident. recommendations in situations where authors must put a document into "quirks" mode but wish to enforce correct font inheritance into tables, use the demonstrated rule. related resources mozilla's doctype sniffing original document...
Styling Abbreviations and Acronyms - Archive of obsolete content
the un...
... or people who are deaf." the problem authors have discovered that any abbr or acronym that has a title attribute is rendered with a dotted underline, per the following rule in resource://gre-resources/html.css abbr[title], acronym[title] { text-decoration: dotted underline; } the solution if authors wish to remove the underline from abbr and acronym elements, this can be done with the following rule: abbr[title], acronym[title] { text-decoration: none; } it may be better to lessen the visual weight of the border without actually removing it. the underline tells readers that the word in question has extra information associated with it. in mozilla, placing the mouse pointer over the element and leaving it for a moment will cause the contents of the title attribute to appear as a t...
Using the DOM File API in chrome code - Extensions
if you want to use the dom file api in chrome code, you can do so without restriction. in fact, you get one bonus feature: you can create file objects specifying the path of the file on the user's computer. this only works from privileged code, so web content can't do it. this protects users from the inherent security risks associated with allowing web content free access to the contents of their disks. if you pass a path to the file constructor from unprivileged code (such as web content), an exception will be thrown. scope availability in the jsm scope file is available without needing to do anything special. in bootstrap scope, this must be imported in like so: cu.importglobalproperties( [ "file" ] ) accessing a file by hard-coded pathname to reference a file by its path, you can si...
...finally, we instantiate the file object by calling file.createfromnsifile. other such keys as the "profd" key are available, check the known locations. notes starting in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5), you can also do this in component code. ...
Examples - Game development
mid solitaire ancient egypt pyramid solitaire app ported to webassembly with emscripten assorted demos wavegl webgl visualizer for sound sources. canvas airport simulation animated map showing planes taking off and landing at airports, along with flight path patterns. animation physics 3d rendering of terrain and cars, using ammo.js for the physics calculations. volumetric particle flow physics simulation of flowing liquid. explosion and chain reaction exploding particles that set off other explosions. canvas generated planet a planet with orbiting asteriod belt. digital fireworks animated firework effects rendered on canvas. autumn falling autumn leaves, with light source shining through. created using three.js. fire walk with me billowing fire cloud effect. rainbow...
... dungeon demo haxor-based dungeon scene with walkable character. massive assault tech demo rendered archipelago with futuristic military vehicles. flight stream 3d globe with simulated flight paths. webgl filters demo showing webgl filters being used to add effects to html elements. ...
Bounding volume collision detection with THREE.js - Game development
ductory article first, and have basic knowledge about three.js. using box3 and sphere three.js has objects that represent mathematical volumes and shapes — for 3d aabb and bounding spheres we can use the box3 and sphere objects. 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. 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. keep in mind that in order for this property to be defined, you need to manually call geometry.computeboundingbox beforehand. var knot = new three.mesh( new three...
...also have our actual box3 bounding box, we create a new box3 object and make it assume the boxhelper's shape and position. var box3 = new three.box3(); box3.setfromobject(knotboxhelper); if we change the mesh position, rotation, scale, etc. we need to call the update() method so the boxhelper instance matches its linked mesh. we also need to call setfromobject again in order to make the box3 follow the mesh. knot.position.set(-3, 2, 1); knot.rotation.x = -math.pi / 4; // update the bounding box so it stills wraps the knot knotboxhelper.update(); box3.setfromobject(knotboxhelper); performing collision tests is done in the same way as explained in the above section — we use our box3 object in the same way as described above. // box vs box box3.intersectsbox(otherbox3); // box vs point bo...
Crisp pixel art look with image-rendering - Game development
pixels. two downsides to this method are larger file sizes and compression artifacts. original size 4x size 4x size (scaled with an image editor) none vendor's algorithm nearest-neighbor algorithm a css-based solution the good news is that you can use css to automatically do the up-scaling, which not only solves the blur problem, but also allows you to use the images in their original, smaller size, thus saving download time. also, some game techniques require algorithms that analyse images, which also benefit from working with smaller images. the css property to achieve this scaling is image-rendering. it is still experimental, but there is partial support in most browsers. the steps to achieve this effect are: create a <canvas> el...
...} and some javascript to set up the canvas and load the image: // get canvas context var ctx = document.getelementbyid('game').getcontext('2d'); // load image var image = new image(); image.onload = function () { // draw the image into the canvas ctx.drawimage(image, 0, 0); } image.src = 'https://udn.realityripple.com/samples/11/a2954fe197.png'; this code used together produces the following result: note: you can check out the original code on github (and a live example.) ...
Square tilemaps implementation: Static maps - Game development
turns the tile contained at the specified column and row. if tiles were a 2d matrix, then the returned value would just be tiles[column][row]. however, it's usually more common to represent the grid with a 1-dimensional array. in this case, we need to map the column and row to an array index: var index = row * map.cols + column; wrapping up, an example of a tilemap object could look like the following. this features an 8 x 8 map with tiles 64 x 64 pixels in size: var map = { cols: 8, rows: 8, tsize: 64, tiles: [ 1, 3, 3, 3, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1 ], gettile: function(col, row) { return thi...
...3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1 ], gettile: function(col, row) { return this.tiles[row * map.cols + col] } }; rendering the map we can render the map by iterating over its columns and rows. this snippets assumes the following definitions: context: a 2d canvas context. tileatlas: an image object containing the tile atlas. map: the tilemap object discussed above. for (var c = 0; c < map.cols; c++) { for (var r = 0; r < map.rows; r++) { var tile = map.gettile(c, r); if (tile !== 0) { // 0 => empty tile context.drawimage( tileatlas, // image (tile - 1) * map.tsize, // source x ...
Bounce off the walls - Game development
edges of the canvas. simple collision detection to detect the collision we will check whether the ball is touching (colliding with) the wall, and if so, we will change the direction of its movement accordingly. to make the calculations easier let's define a variable called ballradius that will hold the radius of the drawn circle and be used for calculations. add this to your code, somewhere below the existing variable declarations: var ballradius = 10; now update the line that draws the ball inside the drawball() function to this: ctx.arc(x, y, ballradius, 0, math.pi*2); bouncing off the top and bottom there are four walls to bounce the ball off — let's focus on the top one first. we need to check, on every frame, whether the ball is touching the top edge of the canvas — if yes, ...
...ed to check, on every frame, whether the ball is touching the top edge of the canvas — if yes, we'll reverse the ball movement so it will start to move in the opposite direction and stay within the visible boundaries. remembering that the coordinate system starts from the top left, we can come up with something like this: if(y + dy < 0) { dy = -dy; } if the y value of the ball position is lower than zero, change the direction of the movement on the y axis by setting it equal to itself, reversed. if the ball was moving upwards with a speed of 2 pixels per frame, now it will be moving "up" with a speed of -2 pixels, which actually equals to moving down at a speed of 2 pixels per frame. the code above would deal with the ball bouncing off the top edge, so now let's think about the botto...
Initialize the framework - Game development
render the game inside. this can be done using html — the phaser framework will generate the required <canvas> element. the game's html the html document structure is quite simple, as the game will be rendered entirely on the <canvas> element generated by the framework. ...
... function preload() {} function create() {} function update() {} </script> </body> </html> downloading the phaser code next, 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 ab...
The score - Game development
xt with. the last parameter looks very similar to css styling. in our case the score text will be blue, sized at 18 pixels, and use the arial font. updating the score when bricks are destroyed we will increase the number of points every time the ball hits a brick and update the scoretext to display the current score. ...
... using the settext() method — add the two new lines seen below to the ballhitbrick() function: function ballhitbrick(ball, brick) { brick.kill(); score += 10; scoretext.settext('points: '+score); } that's it for now — reload your index.html and check that the score updates on every brick hit. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps we now have a scoring system, but what's the point of playing and keeping score if you can't win? let's see how we can add a victory state, allowing us to win the game. « previousnext » ...
Win the game - Game development
« previousnext » this is the 12th step out of 16 of the gamedev phaser tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson12.html. implementing winning in our game is quite easy: if you happen to destroy all the bricks, then you win. ...
...me, congratulations!'); location.reload(); } } we loop through the bricks in the group using bricks.children, checking for the aliveness of each with each brick's .alive() method. if there are no more bricks left alive, then we show a winning message, restarting the game once the alert is dismissed. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps both losing and winning are implemented, so the core gameplay of our game is finished. now let's add something extra — we'll give the player three lives instead of one. « previousnext » ...
Visual-js game engine - Game development
sic licence rules : 1) each file in this project has its own license , be careful , do not violate the basic rules. 2) you are free to use any version of visual js library in any other project (even commercial projects) as long as the copyright header is left intact except for plugins on sale and graphics that come with them (they have special commercial licence). 3) please read the following terms and conditions before using this application: disclaimer of warranty 'visual js' is provided "as-is" and without warranty of any kind, express, implied or otherwise, including without limitation, any warranty of merchantability or fitness for a particular purpose. in no event shall the author of this software be held liable for data loss, damages, loss ...
... 1) click create application 2) enter new application name in input prompt 3) select folder for server part of application (important...
Abstraction - MDN Web Docs Glossary: Definitions of Web-related terms
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. ...
... 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. ...
Canvas - MDN Web Docs Glossary: Definitions of Web-related terms
it provides an empty graphic zone on which specific javascript apis can draw (such as canvas 2d or webgl). ...
...it provides an empty graphic zone on which specific javascript apis can draw (such as canvas 2d or webgl). ...
Conditional - MDN Web Docs Glossary: Definitions of Web-related terms
or change it, depending on whether the condition is completed or not. an instruction or a set of instructions is executed if a specific condition is fulfilled. ...
...r a set of instructions is executed if a specific condition is fulfilled. otherwise, another instruction is executed. ...
Distributed Denial of Service - MDN Web Docs Glossary: Definitions of Web-related terms
botmaster, identifies and infects other vulnerable systems with malware. eventually, the assailant instructs the controlled machines to launch an attack against a specified target. there are two types of ddos attacks: a network-centric attack (which overloads a service by using up bandwidth) and an application-layer attack (which overloads a service or database with application calls). the overflow of data to the target causes saturation in the target machine so that it cannot respond or responds very slowly to legitimate traffic (hence the name "denial of service"). the infected computers' owners normally don't know that their computers have been compromised, and they also suffer loss of service. a computer under an intruder's control is called a zombie or bot. a network of co-infected co...
... under an intruder's control is called a zombie or bot. a network of co-infected computers is known as a botnet or a zombie army. both kaspersky labs and symantec have identified botnets -- not spam, viruses, or worms -- as the biggest threat to internet security. ...
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...
... large assets such as high resolution images, audio, and sd video. 4g 0ms ∞ the network is suited for hd video, real-time video, etc. ...
Fetch directive - MDN Web Docs Glossary: Definitions of Web-related terms
all fetch directives fall back to default-src. ...
... all fetch directives fall back to default-src. ...
Fragmentainer - MDN Web Docs Glossary: Definitions of Web-related terms
fragmented contexts are found in css paged media, where the fragmentainer would be the box which defines a page. in multiple-column layout the fragmentainer is the column box created when columns are defined on a multicol container. ...
... fragmented contexts are found in css paged media, where the fragmentainer would be the box which defines a page. in multiple-column layout the fragmentainer is the column box created when columns are defined on a multicol container. ...
Function - MDN Web Docs Glossary: Definitions of Web-related terms
sion. the function name's scope depends on whether the function name is a declaration or expression. different types of functions an anonymous function is a function without a function name. only function expressions can be anonymous, function declarations must have a name: // when used as a function expression (function () {}); // or using the ecmascript 2015 arrow notation () => {}; the following terms are not used in the ecmascript language specification, they're jargon used to refer to different types of functions. a named function is a function with a function name: // function declaration function foo() {}; // named function expression (function bar() {}); // or using the ecmascript 2015 arrow notation const foo = () => {}; an inner function is a function inside another functio...
...kipedia.org/wiki/immediately-invoked_function_expression) /* ​function foo() { console.log('hello foo'); }(); */ // function expressions, named or anonymous, can be called immediately (function foo() { console.log("hello foo"); }()); (function food() { console.log("hello food"); })(); (() => console.log('hello world'))(); if you'd like to know more about iifes, check out the following page on wikipedia : immediately invoked function expression learn more technical reference functions arrow functions ...
HTTP header - MDN Web Docs Glossary: Definitions of Web-related terms
the value finish at the next crlf or at the end of the message. ...
... or about the server itself (name, version, …). entity header: headers containing more information about the body of the entity, like its content length or its mime-type. ...
High-level programming language - MDN Web Docs Glossary: Definitions of Web-related terms
the amount of abstraction provided defines how "high-level" a programming language is. ...
...the amount of abstraction provided defines how "high-level" a programming language is. ...
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
clarations are physically moved to the top of your code, but this is not in fact what happens. instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code. learn more technical example one of the advantages of javascript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code. for example: function catname(name) { console.log("my cat's name is " + name); } catname("tiger"); /* the result of the code above is: "my cat's name is tiger" */ the above code snippet is how you would expect to write the code for it to work. now, let's see what happens when we call the function before we write it: catname("chloe...
...efore they are declared. only declarations are hoisted javascript only hoists declarations, not initializations. if a variable is declared and initialized after using it, the value will be undefined. for example: console.log(num); // returns undefined, as only declaration was hoisted, no initialization has happened at this stage var num; // declaration num = 6; // initialization the example below only has initialization. no hoisting happens so trying to read the variable results in referenceerror exception. console.log(num); // throws referenceerror exception num = 6; // initialization below are more examples demonstrating hoisting. // example 1 // only y is hoisted x = 1; // initialize x, and if not already declared, declare it - but no hoisting as there is no var in the statement. c...
Intrinsic Size - MDN Web Docs Glossary: Definitions of Web-related terms
ical 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 opposite — in the case of text, this would have the text display as wide as possible, doing no soft-wrapping, even i...
... 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 opposite — in the case of text, this would have the text display as wide as possible, doing no soft-wrapping, even if an overflow was caused. the keyword value max-content exposes this behavior. ...
Media (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
in the context of css (cascading style sheets), the term media refers to the destination to which the document is to be drawn by the rendering engine. typically, this is a screen—but it may also be a printer, a speech synthesizer, braille display, or another type of device. css offers several features that allow you to tweak your document's styles—or even offer different styles—according to the media type (such as screen or print, to name two) or media capabilities (such as width, resolution, or other values) of the viewer's device. learn more general knowledge using media queries technical reference media queries define a set of characteristics or parameters required to apply the css styles that are specified within the curly braces of the media query; for example: ...
...to name two) or media capabilities (such as width, resolution, or other values) of the viewer's device. learn more general knowledge using media queries technical reference media queries define a set of characteristics or parameters required to apply the css styles that are specified within the curly braces of the media query; for example: only applying certain css styles for devices below 768 pixels. @media at-rule conditionally apply part of a stylesheet, based on the result of a media query. window.matchmedia() test the viewing device against a media query. ...
Network throttling - MDN Web Docs Glossary: Definitions of Web-related terms
network throttling is an intentional slowing down of internet speed. in web performance, network throttling, or network condition emulation, it is used to emulate low bandwidth conditions experienced by likely a large segment of a site's target user base. it’s important not to overlook network conditions users experience on mobile. the internet speeds for developers creating web applications in a corporate office building on a powerful computer are generally very fast. as a developer, tech writer, or designer, this is likely your experience. the network speeds of a mobile user accessing that web application, possibly while traveling or in a remote area with poor data plan covereage, will likely be very slow, if they are able to get online at all. network throttling enables a devel...
...online at all. network throttling enables a developer to emulate an experience of a user. most browser developer tools, such as the browser inspector, provide a function to emulate different network conditions. by emulating your user's experience via network throttling, you can more readily identify and fix load time issues. browser developer tools generally have network throttling options, to allow you to test your app under slow network conditions. firefox's developer tools for example have a drop-down menu available in both the network monitor and responsive design mode containing network speed options (e.g. wifi, good 3g, 2g...) see also synthetic monitoring ...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
lue, primitive data type) is data that is not an object and has no methods. there are 6 primitive data types: string, number, bigint, boolean, undefined, and symbol. there also is null, which is seemingly primitive, but indeed is a special case for every object: and any structured type is derived from null by the prototype chain. 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. it is important not to confuse a primitive itself with a variable assigned a primitive value. the variable may be reassigned a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered. example this example will help you understand that ...
....log(bar); // baz // using an array method mutates the array var foo = []; console.log(foo); // [] foo.push("plugh"); console.log(foo); // ["plugh"] // assignment gives the primitive a new (not a mutated) value bar = bar.touppercase(); // baz a primitive can be replaced, but it can't be directly altered. another example [ step-by-step ] the following example will help you go through how javascript deals with primitives. javascript // the primitive let foo = 5; // defining a function that should change the primitive value function addtwo(num) { num += 2; } // another function trying to do the same thing function addtwo_v2(foo) { foo += 2; } // calling our first function while passing our primitive as an argument addtwo(foo); // ge...
Quality values - MDN Web Docs Glossary: Definitions of Web-related terms
quality values, or q-values and q-factors, are used to describe the order of priority of values in a comma-separated list. it is a special syntax allowed in some http headers and in html. the importance of a value is marked by the suffix ';q=' immediately followed by a value between 0 and 1 included, with up to three decimal digits, the highest value denoting the highest priority. when not present, the default value is 1. examples the following syntax text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 indicates the order of priority: value priority text/html and application/xhtml+xml 1.0 application/xml 0.9 */* 0.8 if there is no priority defined for the first two values, the order in the list is irrelevant. ...
...e first two values, the order in the list is irrelevant. nevertheless, with the same quality, more specific values have priority over less specific ones: text/html;q=0.8,text/*;q=0.8,*/*;q=0.8 value priority text/html 0.8 (but totally specified) text/* 0.8 (partially specified) */* 0.8 (not specified) some syntax, like the one of accept, allow additional specifiers like text/html;level=1. these increase the specificity of the value. their use is extremely rare. browser-specific information firefox starting with firefox 18, the quality factor values are clamped to 2 decimal places. they used to be clamped to only 1 decimal place in earlier versions (bug 672448). more information http headers using q-values in their syntax: accept...
Response header - MDN Web Docs Glossary: Definitions of Web-related terms
nt of the message. response headers, like age, location or server are used to give a more detailed context of the response. not all headers appearing in a response are response headers. for example, the content-length header is an entity header referring to the size of the body of the response message. however, these entity requests are usually called responses headers in such a context. ...
...e headers. for example, the content-length header is an entity header referring to the size of the body of the response message. however, these entity requests are usually called responses headers in such a context. the following shows a few response headers after a get request. ...
Scope - MDN Web Docs Glossary: Definitions of Web-related terms
urrent scope," then it is unavailable for use. scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa. a function serves as a closure in javascript, and thus creates a scope, so that (for example) a variable defined exclusively within the function cannot be accessed from outside the function or within other functions. ...
...t (for example) a variable defined exclusively within the function cannot be accessed from outside the function or within other functions. ...
Semantics - MDN Web Docs Glossary: Definitions of Web-related terms
ext it wraps around the role (or meaning) of "a top level heading on your page." <h1>this is a top level heading</h1> by default, most browser's user agent stylesheet will style an <h1> with a large font size to make it look like a heading (although you could style it to look like anything you wanted). on the other hand, you could make any element look like a top level heading. consider the following: <span style="font-size: 32px; margin: 21px 0;">is this a top level heading?</span> this will render it to look like a top level heading, but it has no semantic value, so it will not get any extra benefits as described above. it is therefore a good idea to use the right html element for the right job. html should be coded to represent the data that will be populated and not based on its def...
...semantic value, so it will not get any extra benefits as described above. it is therefore a good idea to use the right html element for the right job. html should be coded to represent the data that will be populated and not based on its default presentation styling. presentation (how it should look), is the sole responsibility of css. ...
Vendor Prefix - MDN Web Docs Glossary: Definitions of Web-related terms
mpatibility and to work on new features; it's also been harmful to smaller browsers who wind up forced to add other browsers' prefixes in order to load popular web sites. lately, the trend is to add experimental features behind user-controlled flags or preferences, and to create smaller specifications which can reach a stable state much more quickly. ...
...y is prefixed. ...
Cacheable - MDN Web Docs Glossary: Definitions of Web-related terms
a response to a post or patch request can also be cached if freshness is indicated and the content-location header is set, but this is rarely implemented. ...
...ached if freshness is indicated and the content-location header is set, but this is rarely implemented. (for example, firefox does not support it per https://bugzilla.mozilla.org/show_bug.cgi?id=109553.) other methods, like put or delete are not cacheable and their result cannot be cached. the status code of the response is known by the application caching, and it is considered cacheable. the following status code are cacheable: 200, 203, 204, 206, 300, 301, 404, 405, 410, 414, and 501. there are specific headers in the response, like cache-control, that prevents caching. note that some non-cacheable requests/responses to a specific uri may invalidate previously cached responses on the same uri. for example, a put to pagex.html will invalidate all cached get or head requests to the same u...
Loop - MDN Web Docs Glossary: Definitions of Web-related terms
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. example: for(var i = 0; i < 10; i++){ console.log(i) } //this loop will print numbers 0-9, will stop when condition is met (i = 10) for the above example, the syntax is as follows: statement 1 sets the variable for the loop (var i = 0). statement 2 sets the loop condition (i < 10). statement 3 increases the value of i (i++) each time the code block is run. while loop syntax: while (condition){ execute code block } the code block will continue to loop as long as the condition is true. example: var i = 0; while(i < 5){ console.log(i) i++ } //this lo...
... 3 increases the value of i (i++) each time the code block is run. while loop syntax: while (condition){ execute code block } the code block will continue to loop as long as the condition is true. example: var i = 0; while(i < 5){ console.log(i) i++ } //this loop will print number 0-4, will stop when condition becomes false (i >=5) for the above example, the syntax is as follows: the code block will continue to run as long as the variable (i) is less than 5. ...
non-normative - MDN Web Docs Glossary: Definitions of Web-related terms
learn more description of normative and informative content in whatwg wiki ...
... learn more description of normative and informative content in whatwg wiki ...
Safe - MDN Web Docs Glossary: Definitions of Web-related terms
but unsafe. even if safe methods have a read-only semantic, servers can alter their state: e.g. they can log or keep statistics. what is important here is that by calling a safe method, the client doesn't request any server change itself, and therefore won't create an unnecessary load or burden for the server. browsers can call safe methods without fearing to cause any harm to the server; this allows them to perform activities like pre-fetching without risk. web crawlers also rely on calling safe methods. safe methods don't need to serve static files only; a server can generate an answer to a safe method on-the-fly, as long as the generating script guarantees safety: it should not trigger external effects, like triggering an order in an e-commerce web site. it is the responsibility of the ...
...swer to a safe method on-the-fly, as long as the generating script guarantees safety: it should not trigger external effects, like triggering an order in an e-commerce web site. it is the responsibility of the application on the server to implement the safe semantic correctly, the webserver itself, being apache, nginx or iis, can't enforce it by itself. in particular, an application should not allow get requests to alter its state. a call to a safe method, not changing the state for the server: get /pagex.html http/1.1 a call to a non-safe method, that may change the state of the server: post /pagex.html http/1.1 a call to an idempotent but non-safe method: delete /idx/delete http/1.1 learn more general knowledge definition of safe in the http specification. technical knowledg...
About Scriptable Interfaces - Interfaces
status of this document this is just a starter document, it should not be considered complete. most of the information of this document is based on http://www.mozilla.org/scriptable/ and creating xpcom components scriptable interfaces interfaces allow xpcom components to expose their functionality to the outside world while hiding the inner details of the component implementation. interfaces are written in an interface description language. ...
...s of the component implementation. interfaces are written in an interface description language. when we label an interface as scriptable, we're saying that components exporting this interface can be referenced (through this interface) from scripts (e.g javascript), and that we can write new components implementing the interface using script languages. xpconnect xpconnect is a technology that allows scriptable interfaces to be used/implemented from/in javascript scripts. no other scripts languages are supported by xpconnect. python there's an extension extensions/python that bridges the gap between xpcom and python, allowing scriptable interfaces to be used/implemented from/in python scripts. ...
Assessment: Accessibility troubleshooting - Learn web development
, 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 abilities, answering the questions given below. color the text is difficult to read because of the current color scheme. can you do a test of the current color contrast (text/background), report the results of the test, and then fix it by changing the assigned colors? semantic html the content is still not very accessible — report on what happens when you try to navigate it using a screenreader. can you update the article text to mak...
...tice the styling looking better. the images the images are currently inaccessible to screenreader users. can you fix this? the audio player the <audio> player isn't accessible to hearing impaired (deaf) people — can you add some kind of accessible alternative for these users? the <audio> player isn't accessible to those using older browsers that don't support html5 audio. how can you allow them to still access the audio? the forms the <input> element in the search form at the top could do with a label, but we don't want to add a visible text label that would potentially spoil the design and isn't really needed by sighted users. how can you add a label that is only accessible to screenreaders? the two <input> elements in the comment form have visible text labels, but they are ...
A cool-looking box - Learn web development
ut it in a <style> element in the head of the document. 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 your task is to create a cool, fancy box and explore the fun we can have with css. general tasks apply the css to the html. styling the box we'd like you to style the provided <p>, giving it the following: a reasonable width for a large button, say around 200 pixels. a reasonable height for a large button, centering the text vertically in the process. centered text. a slight increase in font size, to around 17-18 pixel computed style. use rems. write a comment about how you worked out the value. a base color for the design. give the box this color as its background color. the same color...
....2 opacity by 30% along, and remaining at the same color until the end. multiple box shadows. give it one standard box shadow to make the box look slightly raised off the page. the other two should be inset box shadows — a semi-transparent white shadow near the top left and a semi-transparent black shadow near the bottom right — to add to the nice raised 3d look of the box. example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a ...
Creating fancy letterheaded paper - Learn web development
ound color to the letter. add a 1mm top and bottom solid border to the letter, in a color that is inkeeping with the rest of the color scheme. the logo to the <h1>, add the logo as a background image. add a filter to the logo to give it a subtle drop shadow. now comment out the filter and implement the drop shadow in a different (slightly more cross-browser compatible) way, which still follows the shape of the round image. hints and tips remember that you can create a fallback for older browsers by putting the fallback version of a declaration first, followed by the version that works across newer browsers only. older browsers will apply the first declaration and ignore the second one, whereas newer browsers will apply the first one, then override it with the second one. feel fr...
...a fallback for older browsers by putting the fallback version of a declaration first, followed by the version that works across newer browsers only. older browsers will apply the first declaration and ignore the second one, whereas newer browsers will apply the first one, then override it with the second one. feel free to create your own graphics for the assessment if you wish. example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a ...
Fundamental CSS comprehension - Learn web development
e> element in the head of the document. 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 you have been provided with some raw html and an image, and need to write the necessary css to style this into a nifty little online business card, which can perhaps double as a gamer card or social media profile. the following sections describe what you need to do. basic setup: first of all, create a new file in the same directory as your html and image files. call it something really imaginative like style.css. link your css to your html file via a <link> element. the first two rulesets in the css resource file are yours, for free! after you've finished rejoicing at your good fortune, copy and paste them into...
... hints and tips you don't need to edit the html in any way, except to apply the css to your html. when trying to work out the em value you need to represent a certain pixel length, think about what base font size the root (<html>) element has, and what it needs to be multiplied by to get the desired value. that'll give you your em value, at least in a simple case like this. example the following screenshot shows an example of what the finished design should look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a...
Test your skills: tables - Learn web development
the aim of this task is to help you check your understanding of the skills you studied in the lesson on styling tables. note: you can try out solutions in the interactive 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. task in the lesson we styled up a table in a rather garish manner. in this task we are going to style the same table, but using some good practices for table design as outlined in the external article web typography: designing tables to be read not looked at. our finished table will look like the image below. there are a number of ways that you can achieve thi...
...of this page. task in the lesson we styled up a table in a rather garish manner. in this task we are going to style the same table, but using some good practices for table design as outlined in the external article web typography: designing tables to be read not looked at. our finished table will look like the image below. there are a number of ways that you can achieve this, but i suggest following similar patterns as used in the tutorial to do the following things. align headings and data for columns containing numbers right. align headings and data for columns containing text left. add a top and bottom border, plus a border above the footer. stripe every odd row of the main table. for assessment or further work purposes, download the starting point for this task to work in...
Using your new knowledge - Learn web development
hem. this assessment gives you a chance to do that. prerequisites: before attempting this assessment you should have worked through the rest of the css basics module, and also have an understanding of html basics (study introduction to html). objective: to have a play with some css and test your new-found knowledge. starting point you can work in the live editor below, or you can download the starting point to work with in your own editor. this is a single page with the html, plus the starting point css in the head of the document. if you prefer you could move this css to a separate file when you create the example on your local computer. alternatively use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. note: if you get stuck, then ...
...e starting point css in the head of the document. if you prefer you could move this css to a separate file when you create the example on your local computer. alternatively use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. working with css the following live example shows a biography, which has been styled using css. the css properties that i have used are as follows — each one links to its property page on mdn, which will give you more examples of its use. font-family color border-bottom font-weight font-size text-decoration i have used a mixture of selectors, styling elements such as h1 and h2, but also creating a class for the ...
Styling text - Learn web development
html, as discussed in the introduction to html module, and be comfortable with css fundamentals, as discussed in introduction to css. 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, codepen or glitch. guides this module contains the following articles, which will teach you all of the essentials behind styling html text content. fundamental text and font styling in this article we go through all the basics of text/font styling in detail, including setting font weight, family and style, font shorthand, text alignment and other effects, and line and letter spacing. styling lists lists behave like any other text for the most part...
... practices to consider. this article explains all. styling links when styling links, it is important to understand how to make use of pseudo-classes to style link states effectively, and how to style links for use in common varied interface features such as navigation menus and tabs. we'll look at all these topics in this article. web fonts here we will explore web fonts in detail — these allow you to download custom fonts along with your web page, to allow for more varied, custom text styling. assessments the following assessments will test your understanding of the text styling techniques covered in the guides above. typesetting a community school homepage in this assessment we'll test your understanding of styling text by getting you to style the text for a community school's ...
Learn to style HTML using CSS - Learn web development
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 isn't absolutely necessary as much of what is covered in the css basics article is also covered in our css first steps module, albeit in a lot more detail. modules this topic contains the following modules, in a suggested order for working through them. you should definitely start with the first one. css first steps css (cascading style sheets) is used to style and lay out web pages — for example, to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features. this module provides a gentle beginning to yo...
...id understanding of even the basics of css. ...
What text editors are available? - Learn web development
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 manipulate? what kind of basic features do i expect from my text editor? do i want to add extra features to my text editor? do i need support/help while using my text editor? does my text edit...
...itor? an extensible editor comes with fewer built-in features, but can be extended based on your needs. if you aren't sure which features you want, or your favorite editor lacks those features out of the box, look for an extensible editor. the best editors provide many plugins, and ideally a way to look for and install new plugins automatically. if you like lots of features and your editor is slowing down because of all your plugins, try using an ide (integrated development environment). an ide provides many tools in one interface and it's a bit daunting for beginners, but always an option if your text editor feels too limited. here are some popular ides: aptana studio eclipse komodo ide netbeans ide visual studio webstorm do i need support/help while using my text editor? it's ...
What HTML features promote accessibility? - Learn web development
if the html is linear, as it should be, a logical tabbing order should automatically fall into place. <ul> <li><a href="here.html" tabindex="1">here</a></li> <li><a href="there.html" tabindex="3">there</a></li> <li><a href="anywhere.html" tabindex="2">anywhere</a></li> </ul> in this example (which is used purely as a demonstration—do not do this), tabbing would jump from “here” to “anywhere” to “there”. ...
...explanation and an apology.">click here</a> to find out more.</p> access keys access keys provide easier navigation by assigning a keyboard shortcut to a link, which will usually gain focus when the user presses alt or ctrl + the access key. the exact key combination varies by platform. <a href="somepage.html" accesskey="s">some page</a> skip links to aid tabbing, you can supply links that allow users to jump over chunks of your web page. you might want to allow someone to jump over a plethora of navigation links, for example, so they can just read a page’s main content rather than cycle through all of the links. <header> <h1>the heading</h1> <a href="#content">skip to content</a> </header> <nav> <!-- navigation stuff --> </nav> <section id="content"> <!--your content --> </...
How do you host your website on Google App Engine? - Learn web development
a google account. go to the app engine dashboard on the google cloud platform console and press the create button. if you've not created a project before, you'll need to select whether you want to receive email updates or not, agree to the terms of service, and then you should be able to continue. enter a name for the project, edit your project id and note it down. for this tutorial, the following values are used: project name: gae sample site project id: gaesamplesite click the create button to create your project. creating an application each cloud platform project can contain one app engine application. let's prepare an app for our project. we'll need a sample application to publish. if you've not got one to use, download and unzip this sample app. have a look a...
... form you like. the app.yaml file is a configuration file that tells app engine how to map urls to your static files. you don't need to edit it. publishing your application now that we've got our project made and sample app files collected together, let's publish our app. open google cloud shell. drag and drop the sample-app folder into the left pane of the code editor. run the following in the command line to select your project: gcloud config set project gaesamplesite then run the following command to go to your app's directory: cd sample-app you are now ready to deploy your application, i.e. upload your app to app engine: gcloud app deploy enter a number to choose the region where you want your application located. enter y to confirm. now navigate your brow...
How do I start to design my website? - Learn web development
jumping into the technical side—for example, code and tools—you must first step back and decide in detail what you want to do. an hour's discussion with friends is a good start, but inadequate. you must sit down and structure your ideas to get a clear view of what path you must take to make your ideas a reality. to do this, you need only pen and paper and some time to answer at least the following questions. note: there are countless ways to carry out project ideation. we cannot lay them all out here (a whole book wouldn't be enough). what we will present here is a simple method to handle what professionals call project ideation, project planning, and project management. what exactly do i want to accomplish? this is the most important question to answer, since it drives everything ...
...s sense in this case to build a dedicated website of our own. such a website is the best way to aggregate all the stuff we want to publish in a single place (good for goals 3, 5, and 6) and promote interaction between us and the public (good for goals 2 and 4). in short, since these goals all revolve around the same topic, having everything in one place will help us meet our goals and help our followers connect with us. how can a website help me reach my goals? by answering that, you'll find the best way to reach your goals and save yourself from wasted effort. what needs to be done, and in what order, to reach my goals? now that you know what you want to accomplish, it's time to turn those goals into actionable steps. as a side note, your goals are not necessarily set in stone. they evolv...
What is a URL? - Learn web development
omy of a url here are some examples of urls: https://developer.mozilla.org https://developer.mozilla.org/docs/learn/ https://developer.mozilla.org/search?q=url any of those urls can be typed into your browser's address bar to tell it to load the associated page (resource). a url is composed of different parts, some mandatory and others optional. let's see the most important parts using the following url: http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#somewhereinthedocument http is the protocol. the first part of the url indicates which protocol the browser must use. a protocol is a set method for exchanging or transferring data around a computer network. usually for websites it is the http protocol or its secured version, https. the web requires one of these t...
...sting that url. implicit domain name /docs/learn this is the most common use case for an absolute url within an html document. the browser will use the same protocol and the same domain name as the one used to load the document hosting that url. note: it isn't possible to omit the domain name without omitting the protocol as well. examples of relative urls to better understand the following examples, let's assume that the urls are called from within the document located at the following url: https://developer.mozilla.org/docs/learn sub-resources skills/infrastructure/understanding_urls because that url does not start with /, the browser will attempt to find the document in a sub-directory of the one containing the current resource. so in this example, we really want to r...
What is accessibility? - Learn web development
chnical limitations, maybe your visitors can't experience your website the way you hoped. in this article we give general accessibility principles and explain a few rules. active learning there is no active learning available yet. dig deeper accessibility: general principles we might associate accessibility at first with negative limitations. this building has to be accessible, so it must follow these regulations for door width and toilet size and elevator placement. that's a narrow way to think of accessibility. think of it as a wonderful way to empower people and serve more customers. what can the people in brazil do with your english website? can the people with smartphones browse a heavy, cluttered website designed for a large desktop monitor and unlimited bandwidth? they'll go some...
...em pause the video to read the subtitles or process the information. keyboard capacity let the user tab into/out of a video, play it, and pause it without being trapped in it. the basics of web accessibility a few necessities for basic web accessibility include: whenever your site needs an image to convey meaning, include text as an alternative for visually-challenged users or those with slow connections. make sure all users can operate graphical interfaces (like unfolding menus) solely with a keyboard (e.g., with tab and the return key). provide an attribute explicitly specifying your content's language, so that screen readers read your text properly. make sure that a user can navigate to all widgets on a page solely with the keyboard, without getting trapped. (at least let them t...
What software do I need to build a website? - Learn web development
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 separate article. for now, here's a short list of free basic (s)ftp clients: operating system ftp software windows winscp moba xterm filezilla (all os) ...
... nautilus/files (gnome) dolphin (kde) mac os cyberduck chrome os shiftedit (all os) browsing websites as you already know, you need a web browser to view websites. there are dozens of browser options for your personal use, but when you're developing a website you should test it at least with the following major browsers, to make sure your site works for most people: mozilla firefox google chrome microsoft internet explorer apple safari if you're targeting a specific group (e.g., technical platform or country), you may have to test the site with additional browsers, like opera, konqueror, or uc browser. but testing gets complicated because some browsers only run on certain operating sys...
Sending forms through JavaScript - Learn web development
out for fetch. if you control the front-end (the code that's executed in the browser) and the back-end (the code which is executed on the server), you can send json/xml and process them however you want. but if you want to use a third party service, you need to send the data in the format the services require. so how should we send such data? the different techniques you'll require are done below. sending form data there are 3 ways to send form data: building an xmlhttprequest manually. using a standalone formdata object. using formdata bound to a <form> element. let's look at them in detail. building an xmlhttprequest manually xmlhttprequest is the safest and most reliable way to make http requests. to send form data with xmlhttprequest, prepare the data by url-encoding it, an...
...or binary data, including filereader, canvas, and webrtc. unfortunately, some legacy browsers can't access binary data or require complicated workarounds. to learn more about the filereader api, see using files from web applications. the least complicated way of sending binary data is by using formdata's append() method, demonstrated above. if you have to do it by hand, it's trickier. ...
How the Web works - Learn web development
e). servers are computers that store webpages, sites, or apps. when a client device wants to access a webpage, a copy of the webpage is downloaded from the server onto the client machine to be displayed in the user's web browser. the other parts of the toolbox the client and server we've described above don't tell the whole story. there are many other parts involved, and we'll describe them below. for now, let's imagine that the web is a road. on one end of the road is the client, which is like your house. on the other end of the road is the server, which is a shop you want to buy something from. in addition to the client and the server, we also need to say hello to: your internet connection: allows you to send and receive data on the web. it's basically like the street between you...
... this is like a car or a bike (or however else you might get around). dns: domain name servers are like an address book for websites. when you type a web address in your browser, the browser looks at the dns to find the website's real address before it can retrieve the website. the browser needs to find out which server the website lives on, so it can send http messages to the right place (see below). this is like looking up the address of the shop so you can access it. http: hypertext transfer protocol is an application protocol that defines a language for clients and servers to speak to each other. this is like the language you use to order your goods. component files: a website is made up of many different files, which are like the different parts of the goods you buy from the shop. the...
Getting started with the Web - Learn web development
ls you need to construct a simple webpage and publish your own simple code. the story of your first website 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. by working through the articles listed below in order, you will go from nothing to getting your first webpage online. let's begin our journey! installing basic software when it comes to tools for building a website, there's a lot to pick from. if you're just starting out, you might be confused by the array of code editors, frameworks, and testing tools out there. in installing basic software, we show you step-by-step how to install just t...
...here. in installing basic software, we show you step-by-step how to install just the software you need to begin some basic web development. what will your website look like? before you start writing the code for your website, you should plan it first. what information are you showcasing? what fonts and colors are you using? what will your website look like? we outline a simple method you can follow to plan out your site's content and design. dealing with files a website consists of many files: text content, code, stylesheets, media content, and so on. when you're building a website, you need to assemble these files into a sensible structure and make sure they can talk to one another. dealing with files explains how to set up a sensible file structure for your website and what issues you s...
Using data attributes - Learn web development
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. ...
... use the attribute selectors in css to change styles according to the data: article[data-columns='3'] { width: 400px; } article[data-columns='4'] { width: 600px; } you can see all this working together in this jsbin example. data attributes can also be stored to contain information that is constantly changing, like scores in a game. using the css selectors and javascript access here this allows you to build some nifty effects without having to write your own display routines. see this screencast for an example using generated content and css transitions (jsbin example). data values are strings. number values must be quoted in the selector for the styling to take effect. issues do not store content that should be visible and accessible in data attributes, because assistive technology...
Marking up a letter - Learn web development
ew .html file using your text editor or use an online tool such as codepen, jsfiddle, or glitch to complete the tasks. 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, your task is to mark up a letter that needs to be hosted on a university intranet. the letter is a response from a research fellow to a prospective phd student concerning their application to the university. block/structural semantics use appropriate document structure including doctype, and <html>, <head> and <body> elements. in general, the letter should be marked up as an organization of headings and paragraphs, with the following exception. there is one top level heading (the "re:" line) and three second level head...
... meta tag. the author of the letter should be specified in an appropriate meta tag. the provided css should be included inside an appropriate tag. hints and tips use the w3c html validator to validate your html. award yourself bonus points if it validates. you don't need to know any css to do this assignment. you just need to put the provided css inside an html element. example the following screenshot shows an example of what the letter might look like after being marked up. assessment or further help if you would like your work assessed, or if you get stuck and want to ask for help: put your work in an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should...
Introduction to HTML - Learn web development
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) the code examples in an online coding program such as jsbin or glitch. guides this module contains the following articles, which will take you through all the basic theory of html and provide ample opportunity for you to test out some skills. getting started with html covers the absolute basics of html, to get you started — we define elements, attributes, and other important terms, and show where they fit in the language. we also show how a typical html page is structured and how an html element is...
... as "the header," "the navigation menu," or "the main content column.") this article looks into how to plan a basic website structure and how to write the html to represent this structure. debugging html writing html is fine, but what if something goes wrong, and you can't work out where the error in the code is? this article will introduce you to some tools that can help. assessments the following assessments will test your understanding of the html basics covered in the guides above. marking up a letter we all learn to write a letter sooner or later; it is also a useful example to test out text formatting skills. in this assessment, you'll be given a letter to mark up. structuring a page of content this assessment tests your ability to use html to structure a simple page of conte...
Assessment: Structuring planet data - Learn web development
you could paste the html, css and javascript into one of these online editors. if the online editor you are using doesn't have separate javascript/css panels, feel free to put them inline <script>/<style> elements inside the html page. ...
... inline <script>/<style> elements inside the html page. project brief you are working at a school; currently your students are studying the planets of our solar system, and you want to provide them with an easy-to-follow set of data to look up facts and figures about the planets. an html data table would be ideal — you need to take the raw data you have available and turn it into a table, following the steps below. the finished table should look like this: you can also see the example live here (no looking at the source code — don't cheat!) steps to complete the following steps describe what you need to do to complete the table example. all the data you'll need is contained in the planets-data.txt file. if you have trouble visualising the data, look at the live example above, ...
Asynchronous JavaScript - Learn web development
here we look at the traditional methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g. a set number of times per second), talk about what they are useful for, and look at their inherent issues. handling async operations gracefully with promises promises are a comparatively new feature of the javascript language that allow you to defer further actions until after the previous action has completed, or respond to its failure. this is really useful for setting up a sequence of operations to work correctly. this article shows you how promises work, where you'll see them in use in webapis, and how to write your own. making asynchronous programming easier with async and await promises can be somewhat complex to set up ...
...is really useful for setting up a sequence of operations to work correctly. this article shows you how promises work, where you'll see them in use in webapis, and how to write your own. making asynchronous programming easier with async and await promises can be somewhat complex to set up and understand, and so modern browsers have implemented async functions and the await operator. the former allows standard functions to implicitly behave asynchronously with promises, whereas the latter can be used inside async functions to wait for promises before the function continues. this makes chaining promises simpler and easier to read. choosing the right approach to finish this module off, we'll consider the different coding techniques and features we've discussed throughout, looking at which one...
JavaScript building blocks - Learn web development
. 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 multiple times. in this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define functions, scope, and parameters. build your own function with mos...
...t 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 understanding of the javascript basics covered in the guides above. image gallery now that we've looked at the fundamental building blocks of javascript, we'll test your knowledge of loops, functions, conditionals and events by building a fairly common item you'll see on a lot of websites — a javascript-powered image gallery. ...
JavaScript First Steps - Learn web development
iables, strings, numbers and arrays. 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 javascript knowledge, but you should have some familiarity with html and css. you are advised to work through the following modules before starting on javascript: getting started with the web (which includes a really basic javascript introduction). introduction to html. introduction to css. 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. g...
...ining and splitting strings, substituting one character in a string for another, and more. arrays in the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides. assessments the following assessment will test your understanding of the javascript basics covered in the guides above. silly story generator in this assessment you'll be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. have fun! ...
Solve common problems in your JavaScript code - Learn web development
common beginner's mistakes correct spelling and casing if your code doesn't work and/or the browser complains that something is undefined, check that you've spelt all your variable names, function names, etc. correctly. some common built-in browser functions that cause problems are: correct wrong getelementsbytagname() getelementbytagname() getelementsbyname() getelementbyname() getelementsbyclassname() getelementbyclassname() getelementbyid() getelementsbyid() semi-colon position you need to make sure you don't place any semi-colons incorrectly. ...
...example: correct wrong elem.style.color = 'red'; elem.style.color = 'red;' functions there are a number of things that can go wrong with functions. one of the most common errors is to declare the function, but not call it anywhere. for example: function myfunction() { alert('this is my function.'); }; this code won't do anything unless you call it with the following statement: myfunction(); function scope remember that functions have their own scope — you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e. not inside any functions), or return the value from the function. running code after a return statement remember also that when you return from a function, the javascript ...
Web performance resources - Learn web development
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. ...
... 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 and then change to all once loaded. the following snippet includes an onload attribute, requiring javascript, so it is important to include a noscript tag with a traditional fallback. <link rel="stylesheet" href="/path/to/my.css" media="print" onload="this.media='all'"> <noscript><link rel="stylesheet" href="/path/to/my.css"></noscript> the downside with this approach is the flash of unstyled text (fout.) the simplist way to address this i...
The business case for web performance - Learn web development
f web performance. it highlights the importance of understanding 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...
... be both a set of important business metrics in measuring the impact of user experience and performance on the business's top line, and a way of demonstrating the benefits of prioritizing performance. here are some kpis to consider: conversion rate the percent of your traffic that takes an intended action, such as completing a purchase or signing up for a newsletter. when a business site is slow, it can prevent users from completing their intended task. this can lead to low conversion rates. time on site the average time that your users in aggregate spend on your site. when a site performance slowly, users are more likely to abandon the site prematurely which can lead to low time on site metrics. net promotion score the net promoter score (nps) is a metric for assessing customer loya...
Learning area release notes - Learn web development
etails significant changes made to the learning area. check back here if you want to know what new content is available, and what existing content has been improved. if you want to give feedback on any of these new additions, please leave comments in our discourse forum. june 2020 our front-end web developer learning pathway is officially launched! check it out for an opinionated pathway to follow for learning front-end development! also see our hacks post — introducing the mdn web docs front-end developer learning pathway — for more information about the rationale behind it. may 2020 our understanding client-side javascript frameworks module is now available. learn why frameworks exist, when you should use one (and when you shouldn't), what kinds of features are common to all framew...
...ssments accompanying the articles. april 2020 our new understanding client-side web development tools module has been released! learn the essentials of web development tooling, including what kind of tools exist, the command line, package managers, and how to assemble your own functioning tool chain. ...
Server-side website programming - Learn web development
b server operations easy. basic knowledge of programming concepts (or of a particular programming language) is useful, but not essential. similarly, expertise in client-side coding is not required, but a basic knowledge will help you work better with the developers creating your client-side web "front end". you will need to understand "how the web works". ...
...creating your client-side web "front end". you will 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. modules this topic contains the following modules. you should start with the first module, then go on to one of the following modules, which show how to work with two very popular server-side languages using appropriate web frameworks. server-side website programming first steps this module provides technology-agnostic information about server-side website programming such as "what is it?", "how does it differ from client-side pr...
Git and GitHub - Learn web development
the most popular vcs (at least among web developers) is git, along with github, a site that provides hosting for your repositories and several tools for working with them. this module aims to teach you what you need to know about both of them. ...
...ing 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. guides note that the links below take you to resources on external sites. eventually we will are aiming to have our own dedicated git/github course, but for now, these will help you get to grips with the subject in hand. hello world (from github) this is a good place to start — this practical guide gets you to jump right into using github, learning the basics of git such as creating repositories and branches, making commit...
Tools and testing - Learn web development
ls, 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, and how to make use of the current in...
...rt of their tooling, so many front-end development jobs now require framework experience. this module gives you some fundamental background knowledge about how client-side frameworks work and how they fit into your toolset, before moving on to tutorial series covering some of today's most popular ones. git and github all developers will use some kind of version control system (vcs), a tool to allow them to collaborate with other developers on a project without danger of them overwriting each other's work, and roll back to previous versions of the code base if a problem is discovered later on. the most popular vcs (at least among web developers) is git, along with github, a site that provides hosting for your repositories and several tools for working with them. this module aims to teach you...
Accessible Toolkit Checklist
stions or feedback. the work when implementing a new toolkit it's important to: implement standard keyboard behavior, which can vary from platform to platform. expose your ui - a way for assistive technologies such as screen readers, screen magnifiers and voice dictation software to understand your software. provide theme compatibility with the operating system, at least as an option. some low vision users will be running your software with high contrast or large font themes. go beyond section 508. implement true usability for everyone, and make your toolkit follow the guidelines 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...
...vide 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 will need to test extensively and fill in the holes. you will also need to provide a way for custom a...
Accessibility and Mozilla
these articles provide mozilla-specific details about accessibility. accessibility api cross-referencethis cross-reference helps us see the difference between today's accessibility api's. ...
...ccessible2.accessible toolkit checklistplease contact the mozilla accessibility community with questions or feedback.csun firefox materialsfirefox 1.5 is a fast, free, standards compliant web browser which is rapidly gaining recognition for its fresh, streamlined approach to browsing the web. in addition to winning major awards such as pc world product of the year, firefox has attracted a huge following among savvy users who simply care enough about their web browsing experience to download a new piece of software. websites such as online magazines with sophisticated audiences are now reporting upwards of 25% firefox usage.embedding api for accessibilityevent process procedurethis diagram outlines how events are processed within gecko. gecko info for windows accessibility vendorsplease co...
Lightweight themes
will be anchored to the top-right corner of the browser window. view a sample theme header here. image requirements dimensions should be 3000px wide × 200px high png or jpg file format image must be no larger than 300 kb in file size tips subtle, soft contrast images and gradients work best; highly detailed images will compete with the browser ui. firefox may reveal more of the lower portion of the image if another toolbar or other ui element is added to the top of the window. the upper right-hand side of the image should have the most important information - as a user increases the width of the browser window, the browser reveals more of the left-hand side of the image. ultrawide monitors can run to 3440px wide, to look good on these monitors, ensure the left of the imag...
... pixlr — pixlr offers professional and easy-to-use tools for creating and editing images within a browser. photoshop — tweak, rotate and touch up photos with photoshop® 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 ...
Add-ons
they are written using standard web technologies - javascript, html, and css - plus some dedicated javascript apis. among other things, an add-on could: change the appearance or content of particular websites modify the firefox user interface add new features to firefox there are several types of add-ons, but the most common type are extensions. developing extensions in the past, there were several toolsets for developing firefox extensions, but as of november 2017, extensions must be built using webextensions apis. other toolsets, such as overlay add-ons, bootstrapped add-ons, and the add-on sdk, are no longer supported. ...
...community of users and creators and find an audience for your add-on. you are not required to list your add-on on amo, but your add-on must be signed by mozilla else users will not be able to install it. for an overview for the process of publishing your add-on see signing and distributing your add-on. other types of add-ons in addition to extensions, there are a few other add-on types that allow users to customize firefox. those add-ons include: user dictionaries let you spell-check in different languages. language packs let you have more languages available for the user interface of firefox. ...
Browser chrome tests
as all tests, they won't work in a build with tests disabled (--disable-tests). running the browser chrome tests to run mochitest, first build mozilla with your changes; then run ./mach mochitest -f browser this will launch your build and open a "browser chrome tests" window, and report the results in the ui and to stdout. it is possible to run specific groups of tests. ...
...n the mozilla source tree. if the path points to a directory, then the tests in that directory and all of its subdirectories will be run. for example, to run the tests in browser/base/content/test the command would be: ./mach mochitest -f browser browser/base/content/test/ or without mach test_path=<path_to_the_tests> make -c <objdir> mochitest-browser-chrome to run tests in debugger the following should work ./mach mochitest -f browser --debugger gdb browser/base/content/test/ run ./mach help mochitest-browser for more options. writing browser chrome tests browser chrome tests are snippets of javascript code that run in the browser window's global scope. a simple test would look like this: function test() { ok(gbrowser, "gbrowser exists"); is(gbrowser.tabs.length, 1, "brows...
Cookies Preferences in Mozilla
network.cookie.prefsmigrated default value: false migration pref for users with older profiles (before mozilla 1.7). if you have the old-style prefs, they will ...
... network.cookie.prefsmigrated default value: false migration pref for users with older profiles (before mozilla 1.7). ...
Creating MozSearch plugins
arch plugin packaged in a firefox extension, or if you are creating plugins meant to be shipped by default in a firefox build. for creating search plugins for installation from the web, see creating opensearch plugins for firefox the plugin file the mozsearch format is similar to the opensearch format. the only difference is the root element and xml namespace. ...
..." value="{searchterms}"/> <param name="ei" value="utf-8"/> <mozparam name="fr" condition="pref" pref="yahoo-fr" /> </url> <searchform>http://search.yahoo.com/</searchform> </searchplugin> let's say the user chooses to use the yahoo! search engine plugin and enters "mozilla" in the search box and presses the enter key. firefox will use the above search engine description to construct the following search url: http://search.yahoo.com/search?p=mozilla&ei=utf-8&fr=moz2 if the user clicks the magnifying glass icon in the search bar, or chooses the web search option in the tools menu when the search bar isn't visible, the browser will take them to http://search.yahoo.com/, the value of the <searchform> element. example: searching mdc this plugin lets you easily search the mozilla develop...
Creating Sandboxed HTTP Connections
passed in as arguments. since nsistreamlistener does not cover cookies, the current channel being used will need to be stored as a global, since another listener will be used for cookie notifications (covered in the next section). it is usually best to use a javascript wrapper that implements all the required methods and calls the specified callback function when the connection has completed. ...
...he old value is overwritten. getresponseheader(aheader) - returns the response header value for the requested header. setresponseheader(aheader, avalue, amerge) - sets the response header's value. if amerge is true, the new value is appened, otherwise the old value is overwritten. these methods provide all the required functionality needed to modify cookies before they are processed/sent, allowing for sandboxed cookie connections that don't affect the user's cookies. http referrer if the http request needs to have a referrer set, two additional steps are needed after the nsichannel is created, but before it is opened. first, a nsiuri needs to be generated for the referrer url. like before, the nsiioservice is used: var referreruri = ioservice.newuri(referrerurl, null, null); next, ...
Capturing a minidump
t appears, open the firefox.exe executable in your firefox program folder (c:\program files\mozilla firefox). if firefox is already running, open windbg from the start menu (start->all programs->debugging tools for windows->windbg). next, open the "file" menu and choose "attach to a process...". in the file chooser window that appears, find the firefox.exe executable process with the lowest pid. you should now see a "command" text window with debug output at the top and an input box at the bottom. from the menu, select debug → go, and firefox should start. if the debugger spits out some text right away and firefox doesn't come up, select debug → go again. when the program is about to crash, windbg will spit out more data, and the prompt at the bottom will chan...
... ...
Debugging
chniques 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, to help debug intermittent mochitest failures. detecting defects in firefox with coverity coverity is a static analysis system that can detect defects in firefox. gecko logging using old-school logging to try ...
...verity is a static analysis system that can detect defects in firefox. gecko logging using old-school logging to try to track down what's going on. debugging specific parts of the mozilla codebase debugging opengl if you're working on code that involves opengl calls, and need to debug it, you can turn on a special opengl debugging mode. debugging frame reflow and debugging table reflow notes on debugging issues in gecko's layout engine. miscellaneous debugging safari some tips for debugging safari debugging chrome some tips for debugging chrome debugging internet explorer some tips for debugging internet explorer providing useful information to the mozilla developers how to...
Building Firefox with Debug Symbols
this is enabled by default so unless you have explcitly disabled it your build you should include symbols. ac_add_options --enable-debug-symbols this can optionally take an argument for the type of symbols that need to be produced (like "-g3"). by default it uses "-g" on linux and macos. ...
... symbols. ac_add_options --enable-debug-symbols this can optionally take an argument for the type of symbols that need to be produced (like "-g3"). by default it uses "-g" on linux and macos. this value takes precedence over the flags set in moz_debug_flags note that this will override the values provided for cflags and cxxflags. breakpad symbol files after the build is complete, run the following command to generate an archive of breakpad symbol files: mach buildsymbols the tinderbox uses an additional uploadsymbols target to upload symbols to a socorro server. see https://dxr.mozilla.org/mozilla/source/toolkit/crashreporter/tools/upload_symbols.sh for more information about the environment variables used by this target. make package if you use make package to package your build, ...
Simple Sunbird build
building sunbird is no longer supported. you can give it a try, but its likely that the build system will present you an error. instead it is suggested to build thunderbird with lightning. please refer to the simple thunderbird build guide. you can build a bleeding-edge, development version of sunbird using the commands below. for complete information, see the build documentation. installing build tools if your system is not listed below, see the build prerequisites page. ubuntu linux: sudo apt-get build-dep sunbird sudo apt-get install mercurial libasound2-dev libcurl4-openssl-dev libnotify-dev libiw-dev autoconf2.13 cvs fedora linux: sudo yum groupinstall 'development tools' 'development libraries' 'gnome software development' sudo yum install mercurial autoconf213 ...
...building sunbird building sunbird requires at least 2.5 gb of disk space, 500 mb of ram, and lots of available swap space. on windows, if you open the command prompt you are usually in your user profile folder which often contains spaces ( c:\documents and settings\...). this causes problems while building. to avoid this issue, change to a directory without spaces (i.e. c:\ ) before doing the following steps. you can use the "cd" command to do so. # get the source hg clone http://hg.mozilla.org/comm-central/ cd comm-central python client.py checkout # setup a basic .mozconfig file echo 'ac_add_options --enable-application=calendar' > .mozconfig # let's build sunbird... echo 'mk_add_options moz_objdir=@topsrcdir@/objdir-sb-release' >> .mozconfig # ...in this directory... # ...
Updating NSPR or NSS in mozilla-central
an individual change by mistake, your change will be lost when the nspr and nss teams push a new hg tag to mozilla-central. ...
... 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 have nss installed or your version is too old])]) fi commit the update: $ hg commit -a in order to eliminate any pr...
Windows SDK versions
mozilla, from time to time, might support building against multiple versions of the windows sdk as a compatibility/transitional measure. if it does, several features will be disabled if you build with an sdk older than the default, which means that you'll have to specify a non-default sdk version explicitly. quick start follow the instructions for whichever version of visual c++ you're using. visual studio professional 2013 this comes with the windows 8.1 sdk included. visual studio express 2013 for windows desktop this comes with the windows 8.1 sdk included. visual studio professional 2012 this comes with the windows 8.0 sdk included. visual studio 2012 express for windows desktop this comes with the windows 8.0 sdk included. visual c++ 10 (vs2010) professional this comes with the w...
... represent a valid system volume" error you may require to set environmental variable %windir% to something like "c:\windows" instead of "%systemroot%". older sdks these are no longer supported, further information is available at obsolete build caveats and tips [en-us] under the windows sdk article. troubleshooting help! i know i have the correct sdk, but configure.in's still failing! try the following things in order: run the windows sdk configuration tool (if available) and make sure the right sdk is selected. restart the msys console. delete your entire object directory and start over. ...
ESLint
le by running path="$path:/path/to/node.js/". for example: in windows 10, if you have installed node.js on "c:\nodejs", then the command should look like: export path=$path:/c/nodejs enabling eslint for a new directory remove the directory from .eslintignore (in the base directory of the repository) fix errors that occur when running ./mach eslint path/to/dir, see also the no-undef rules below. no-undef the no-undef rule is currently being enabled throughout the code base. here are some common issues: my script is imported into the global browser.xul scope. add a line like: /* eslint-env mozilla/browser-window */ or enable the rule in a .eslintrc.js if it will apply to the whole directory. my script is a frame-script, or includes items that loade...
... either, specify the global at the top of the file: /* globals mychromeglobal */ or, add to the global section toolkit/.eslintrc.js if it is widely used. foo.jsm exports a symbol, but that is not recognised by eslint check it is listed correctly in tools/lint/eslint/modules.json using services.scriptloader.loadsubscript? you'll need to include the following just above it: /* import-globals-from relative/path/to/file.js */ do_check_eq, add_task not defined in a test directory. ensure there is a .eslintrc.js file that extends one of: "plugin:mozilla/browser-test" "plugin:mozilla/chrome-test" "plugin:mozilla/mochitest-test" "plugin:mozilla/xpcshell-test" see other test directories f...
Reviewer Checklist
good web citizenship make sure new web-exposed apis actually make sense and are either standards track or preffed off by default. in c++, wrapper-cache as needed. if your object can be gotten from somewhere without creating it in the process, it needs to be wrapper-cached. ...
...ality. 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 modelines. new js files should use strict mode. trailing whitespace (git diff and splinter view both highlight this, as does hg with the color extension enabled). whitespace can be fixed easily in merc...
Linux compatibility matrix
the following table lists the available library versions for the mozilla.org-distributed firefox builds dependencies, and/or to build firefox. distribution kernel glibc glib gtk+2 gtk+3 pixman stdc++ gcc clang python3 released eol fedora 16 3.1 2.14 2.30 2.24 3.2 0.22 4.6 4.6 2.9 n/a nov 2011 feb 2013 fedora 17 3.3 2.15 2.32 2.24 3.4 0.24 4.7 4.7 3.0 n/a may 2012 jul 2013 fedora 18 3.6 2.16 2.34 2.24 3.6 0.26 4.7 4.7 3.1 n/a jan 2013 jan 2014 fedora 19 3.9 2.17 2.36 2.24 3.8 0.30 4.8.1 4.8 3.3 n/a jul 2013 jan 2015 fedora 20 3.11 2.18 2.38 2.24 ...
... 2.54 2.24 3.22 0.34 8.2 7.5, 8.2, 9.2 5.0, 7.0 3.6 jun 2019 ? distribution kernel glibc glib gtk+2 gtk+3 pixman stdc++ gcc clang python3 released eol notes red backgrounds denote lack of compatibility with current versions of firefox. in the eol column, they denote distribution versions past their end of life. yellow backgrounds denote compatibility with esr78 green backgrounds denote compatibility with the current release (as of writing, 78) greener backgrounds denote compatibility with the current mozilla-central (as of writing, 80). the table is generated with the script and data in https://github.com/glandium/firefox-linux-compat-matrix ...
Frame script environment
addeventlistener() listen to events from content. removeeventlistener() stop listening to events from content. addmessagelistener() listen to messages from chrome. removemessagelistener() stop listening to messages from chrome. sendasyncmessage() send an asynchronous message to chrome. sendsyncmessage() send a synchronous message to chrome. ...
...u can use a sandbox. frame scripts run with system privileges and have access to the components object, enabling them to use xpcom objects and jsms. however, some apis that work in the chrome process will not work in a frame script. see limitations of frame scripts for more details. events besides the regular dom events being captured/bubbling up from content the current content object the following additional events get fired in a frame script environment: unload fires when the frame script environment is shut down, i.e. when a tab gets closed. if you use a capturing event listener on the contentframemessagemanager, you should verify that its event.target is set to the contentframemessagemanager global object in order to avoid handling unload events from content. ...
Frame script environment
addeventlistener() listen to events from content. removeeventlistener() stop listening to events from content. addmessagelistener() listen to messages from chrome. removemessagelistener() stop listening to messages from chrome. sendasyncmessage() send an asynchronous message to chrome. sendsyncmessage() send a synchronous message to chrome. ...
...u should use a sandbox. frame scripts run with system privileges and have access to the components object, enabling them to use xpcom objects and jsms. however, some apis that work in the chrome process do not work in a frame script. see limitations of frame scripts for more details. events besides the regular dom events being captured/bubbling up from content the current content object the following additional events get fired in a frame script environment: unload bubbles no fires when the frame script environment is shut down, i.e. when a tab gets closed. if you use a capturing event listener on the contentframemessagemanager, you should verify that its event.target is set to the contentframemessagemanager global object to avoid handling unload...
Firefox and the "about" protocol
about:crashes lists all crashes, which happened during the runtime of firefox (in case the user enabled the crash reporter) about:credits lists all...
...settings about:compat lists overriding site compatability fixes, linked to specific bug issues. ...
mozbrowsercaretstatechanged
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: rect an object that defines information about the bounding rectangle of the current selection. its properties are width: the width of the bounding rectangle, in css pixels. height: the height of the bounding rectangle, in css pixels. top: the top position of the bounding rectangle, in css pixels. bottom: the bottom position of the bounding rectangle, in css pixels. ...
...lean indicating whether the caret is currently visible (true) or not (false.) selectionvisible a boolean indicating whether the current selection is visible (true) or not (false.) selectioneditable a boolean indicating whether the current selection is editable (true) or not (false.) selectedtextcontext a domstring containing the currently-selected text content. senddocommandmsg a method allowing you to issue a command via an anonymouse function, i.e. function(command). possible values are cut, copy, paste and selectall. examples var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsercaretstatechanged", function( event ) { // do stuff with event.details }); related events mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchang...
mozbrowsermetachange
dard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mozbrowsermetachange event is fired when a <meta> element related to web applications is added, removed or changed. see below for the applicable types. general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eventtarget the browser iframe type read only domstring the type of event. bubbles read only boolean whether ...
... the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: name a domstring representing the <meta> name attribute value. this can be viewmode, theme-color, theme-group, or application-name. content a domstring representing the <meta> content attribute value, i.e. the content of the meta tag. type a domstring representing the type of meta change that this event object represents. this can be added, changed, removed, or undefined. ...
Chrome-only API reference
Mozilla › Gecko › Chrome › API
this page lists apis that only run in gecko chrome code (and sometimes in other privileged circumstances). note: most of the apis exposed to the web in general are also usable in chrome code: see web apis for a list of these. browser apithe html browser api is an extension of the html <iframe> element that allows web apps to implement browsers or browser-like applications. it currently works in (privileged) chrome code on firefox desktop (version 47 and above).chromeworkerif you're developing privileged code, and would like to create a worker that can use js-ctypes to perform calls to native code, you can do so by using chromeworker instead of the standard worker object. it works exactly like a standard worker, except that it has access to js-ctypes via a global ctypes object availa...
...rker that can use js-ctypes to perform calls to native code, you can do so by using chromeworker instead of the standard worker object. it works exactly like a standard worker, except that it has access to js-ctypes via a global ctypes object available in the global scope of the worker. examples of chromeworker's using js-ctypes are availabe on github and are linked to from the see also section below. to use a postmessage with callback version of chromeworker that features promises, see promiseworker. ...
Chrome-only CSS reference
Mozilla › Gecko › Chrome › CSS
se cursor is presently hovering over a tree row.::-moz-tree-separatoractivated by the properties attribute.::-moz-tree-twistyactivated by the properties attribute.css -moz-bool-pref() @supports functionthe -moz-bool-pref() @supports condition is available to gecko chrome and ua stylesheets to check if a boolean preference is enabled.css <display-xul> component</display-xul>firefox supports the following -moz- prefixed xul display values:overflow-clip-boxthe overflow-clip-box css property specifies relative to which box the clipping happens when there is an overflow. it is short hand for the overflow-clip-box-inline and overflow-clip-box-block properties.overflow-clip-box-blockthe overflow-clip-box-block css property specifies relative to which box the clipping happens when there is an overflo...
...ues:overflow-clip-boxthe overflow-clip-box css property specifies relative to which box the clipping happens when there is an overflow. it is short hand for the overflow-clip-box-inline and overflow-clip-box-block properties.overflow-clip-box-blockthe overflow-clip-box-block css property specifies relative to which box the clipping happens when there is an overflow — in the block direction.overflow-clip-box-inlinethe overflow-clip-box-inline css property specifies relative to which box the clipping happens when there is an overflow — in the inline direction. ...
Gecko's "Almost Standards" Mode
identifier "-//w3c//dtd html 4.01 frameset//en", with a system identifier the ibm system doctype "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd" a complete doctype contains a public identifier and a system identifier. in discussions of doctypes, many people will refer to a doctype as being "with uri" or "without uri." the uri is the system identifier. ...
...ansitional.dtd" a complete doctype contains a public identifier and a system identifier. in discussions of doctypes, many people will refer to a doctype as being "with uri" or "without uri." the uri is the system identifier. for example, consider the following doctype: <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> the parts are as follows: public identifier: "-//w3c//dtd html 4.01 transitional//en" system identifier: "http://www.w3.org/tr/html4/loose.dtd" thus any html 4.01 transitional or frameset doctype with a uri (system identifier) will trigger "almost standards" mode, as will any xhtml 1.0 transitional or frameset doctype, with or without the uri. authors outside of ibm do not need to worry about the custom doctype th...
Getting from Content to Layout
emory: the content tree and the frame tree. changes to a document originate in the content tree (from dom modification by scripting, insertion of elements from the parser, etc.) and are propogated to the layout tree through magic that primarily resides in //github.com/realityripple/uxp/blob/master/layout/base/nscssframeconstructor.cpp the frame constructor implements nsimutationobserver which allows it to "watch" the content tree. nscssframeconstructor gets notified from the document's presshell (which implements nsidocumentobserver and observes the document) about all nodes in the document. the frame constructor takes these notifications and does the following: dispatches "restyle events" which trigger the reprocessing of relevant css selectors and any restyling that needs to occur. ...
...hat need to be restyled are marked with flags (e.g element_has_pending_restyle) and are stored in the mpendingrestyles hashtable. a list of restyle roots (places in the content tree where all descendants need to be restyled but nothing on the parent chain does) are also stored. the restyles accumulated 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 relevan...
How to add a build-time test
file somewhere so that the build system knows about it. standalone executables to add a test that is written in c or c++ and which is called as a standalone executable, a few things must be done. for standalone executables, if one sets up the right variables, then the rules.mk file will do lots of magic and most of the heavy lifting. a simple example of adding a test is in . note that the following variables are supplied by the rules.mk file: cppsrcs, simple_programs, run_test_program. xpcshell tests here are the simple guidelines for adding an xpcshell test to the build system. for now, enclose your test-related code (in the makefile) with ifdef enable_tests run the test program from the "check" target in the makefile. (example to run the testcookie program) in the test progr...
...and/or print the string "fail" to stdout if the test passes, exit with a zero status and don't print the string "fail" (bonus points for printing "pass" :) ) write the test so that you expect it to pass on all platforms, since if the test fails, the tree will go orange (once we've set this up - see bug 352240 for status). for example, to add an xpcshell test to a module, do the following: copy tools/test-harness/xpcshell-simple/example to yourmoduledir/tests_type, wheretests_type is something that describes your tests. you can of course use unit or test if you're not feeling creative. in <tt>yourmoduledir/tests_type/makefile.in</tt> change depth, module, and xpcshell_tests appropriately: depth should be a relative path pointing to <tt>mozilla/</tt>, e.g. if you're i...
IPDL Best Practices
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. ...
...r 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 construction, the parent will send a kickoffquery message and presumably ignore the actor until it receives returnresult, at which point it will be deleted. it makes sense to fold construction and the first message together, as well as the penultimate and deletion messages, so that the final protocol looks like this: async protocol pasyncquerier { child: pasyncquery(nsstring query); }...
Implementing QueryInterface
status = ns_ok; } *ainstanceptr = foundinterface; return status; } what's so good about it? it's clear and simple. ok. it has more than one return, but the primary return is at the end of the function as expected; and the additional return is clear and alone at the top of the function. it only has one addref. it addrefs the resulting interface, not this, thus following the com-correct way (particularly important in aggregation) it uses nscomtypeinfo<t>::getiid() instead of ktiid thus saving a global declaration and global space it uses c 's static_cast, via ns_static_cast, which detects errors when you can't really get to the desired interface. it avoids repeated uses of and assignments to *ainstanceptr, which compilers have trouble optimizing. it clears...
... calling an inherited queryinterface sometimes you are just adding one or two new interfaces to an implementation that already supports many other interfaces. in such cases, you'll probably want to call through to the underlying implementation, after you've tested for the particular iids that you care about. this saves code-space and reduces complexity. the differences are highlighted in the following code. class nsmyimplmentation : public nsbaseimplementation, public nsix, public nsiy { ... }; ns_imethodimp nsmyimplementation::queryinterface( refnsiid aiid, void** ainstanceptr ) /* i just add the interfaces |nsix| and |nsiy|. my base class |nsbaseimplementation| provides all the rest. */ { ns_assertion(ainstanceptr, "queryinterface requires a non-null destinat...
Integrated Authentication
egotiateauth. mozilla also supports raw ntlm authentication using an internal implementation (based on the documentation provided by eric glass) that supports ntlmv1/lmv1 and ntlm2 session key modes. as of mozilla 1.7, there is no support for ntlmv2/lmv2. this is mainly due to the fact that ntlmssp does not provide a means to negotiate use of ntlmv2/lmv2. <i>this document is incomplete ...</i> flow diagram the diagram below shows how various components interact. configuration by default, mozilla rejects all spnego challenges from a web server. this is to protect the user from the possibility of dns-spoofing being used to stage a man-in-the-middle exploit (see bug 17578 for more info). moreover, with windows clients ntlm may be negotiated as the authentication protocol. so, it is paramo...
...legation-uris lists the sites for which the browser may delegate user authorization to the server. network.automatic-ntlm-auth.trusted-uris lists the trusted sites to use ntlm authentification. if you wish to use non-fully-qualified entries of the form mydomain.com in the above preferences for ntlm and spnego authentication, you will also need to set the preferences network.automatic-ntlm-auth.allow-non-fqdn and network.negotiate-auth.allow-non-fqdn (respectively) to true. original document information author(s): darin fisher last updated date: december 27, 2005 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
JavaScript Tips
t/lastchild with next/previoussibling. but prefer haschildnodes() to childnodes.length > 0. similarly prefer document.getelementsbytagname(atag).item(0) != null to document.getelementsbytagname(atag).length > 0. prefer to use localname rather than tagname. xul elements have many of the attributes mapped to properties. this was done for a reason, so use them! the properties are: align allowevents contextmenu datasources dir flex height id left maxheight maxwidth minheight minwidth observes orient pack persist ref statustext top tooltip tooltiptext width xul also maps the ordinal attribute but this defaults to "1" if it is not present. xul also maps the class attribute, but unfortunately class is a reserved ident...
...oks silly.) xul also maps the hidden and collapsed attributes to properties, but note that these are boolean properties whereas the above list are all string properties. xul also maps other useful properties and methods using xbl bindings; these vary from element to element. for best performance give ids to all important elements. however in addition to locating elements by tag name xul also allows you to locate an element by attribute, starting at any element in the document. references this was started as a reprint of neil's guide some more current info on this blog post how to remove duplicate objects from an array javascript ...
DownloadSummary
number number of bytes currently transferred as part of all the downloads that are currently in progress. this is zero if no downloads are currently in progress. methods bindtolist() this method may be called once to bind this object to a downloadlist. views on the summarized data can be registered before this object is bound to an actual list. this allows the summary to be used without requiring the initialization of the downloadlist first. note: this method is already called internally by the downloads.getsummary() function. promise bindtolist( downloadlist alist ); parameters alist underlying downloadlist whose contents should be summarized. promise resolves to undefined when the view on the underlying list has been regist...
... underlying downloadlist whose contents should be summarized. promise resolves to undefined when the view on the underlying list has been registered. addview() adds a view that will be notified of changes to the summary. the newly added view will receive an initial onsummarychanged notification. promise addview( object aview ); parameters aview the view object to add. the following methods may be defined: onsummarychanged: optional called after any property of the summary has changed. promise resolves to undefined when the view has been registered and the onsummarychanged notification has been sent. removeview() removes a view that was previously added using addview(). promise removeview( object aview ); parameters aview the view obj...
Http.jsm
method get, post or put (this is automatically set if postdata exists). ...
...ccurs, it takes three parameters: the error, the responsetext and the xhr object. logger an object that implements the debug and log methods (e.g. log.jsm). headers or post data are given as an array of arrays, for each inner array the first value is the key and the second is the value. for example: [["key1", "value1"], ["key2", "value2"]]. submitting post data httprequest allows attaching data to the post requests. the data can be specified via postdata option. postdata can be of 2 different types: a string or an array of parameters. when null/undefined is given, no post data will be attached. if a string is given the data will be appended to the request as is. in case an array of parameters is given, it will be treated as an array of key-value pairs. the elements of th...
JNI.jsm
js-ctypes required for writing jni code. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/jni.jsm"); this module was available in firefox since version 17. if you would like to support versions before that, you can copy and paste the contents of the jsm file int jni stands for java native interface; this library allows calling java code running in java virtual machines (jvms), etc. the most common use for this module is in add-ons and other works on firefox for android (fennec). with this module, all of the android sdk functions that firefox has permissions for are at your fingertips. a note about firefox for android, this jsm file is already globally imported and is available from the privileged window scope...
...t(2); // 0 ia.get(3); // 0 ia.get(4); // 0 ia.set(2, 10); // void ia.get(2); // 10 ia.setelements(3, [50, 75]); // void ia.get(0); // 0 ia.get(1); // 0 ia.get(2); // 10 ia.get(3); // 50 ia.get(4); // 75 } finally { if (my_jenv) { jni.unloadclasses(my_jenv); } } casting this example shows how to cast, the casting happens at jni.classes.android.view.windowmanager.__cast__(wm) below: function main() { var my_jenv; try { my_jenv = jni.getforthread(); var sig = { windowmanager: 'landroid/view/windowmanager;', windowmanager_layoutparams: 'landroid/view/windowmanager$layoutparams;', viewgroup_layoutparams: 'landroid/view/viewgroup$layoutparams;', view: 'landroid/view/view;', void: 'v', ...
NetUtil.jsm
y an nsichannel as the input source, and its notification callbacks have already been set, callers are responsible for implementing nsibadcertlistener and nsisslerrorlistener. newchannel() creates a new channel for the specified uri string, nsiuri, or nsifile. nsichannel newchannel( awhattoload, [optional] aorigincharset, [optional] abaseuri ); parameters return value an nsichannel allowing access to the specified data source. awhattoload a string specifying a uri, or an nsiuri or nsifile object. the returned method will allow access to the specified data. aorigincharset the optional character set to use when interpreting awhattoload as a string; this is ignored if awhattoload is not a string. defaults to utf-8 if not provided. abaseuri the base uri for the spec, specifie...
...rom 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 process. this is a javascript object with fields as specified in options. options the aoptions parameter is a javascript object which can have any or all of the following fields: field name description charset the character encoding to use when interpreting the input stream. if you don't provide this, the input won't be decoded at all and the raw bytes will be returned. replacement a character with which to replace any invalid byte sequences in the input stream. if you don't specify a replacement character, any invalid seque...
OS.File.Info
rences 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. ...
...e systems. ...
OSFile.jsm
cute 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 i/o is wasting battery. consequently, one of the key design choices of os.file is to provide opera...
...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 i/o is wasting battery. consequently, one of the key design choices of os.file is to provide operations that are low-level enough that they do not hide any i/o from the developer (which could cause the developer to perform more i/o than they think) and, since not all platforms have the same features, offer system-specific information that the developer can use to optimize his algorithms for a platform. using os.file ... from the main thread most uses of os.file are from the main thread. in this mode, main...
Deferred
a deferred object is returned by the obsolete promise.defer() method to provide a new promise along with methods to change its state. starting from gecko 30, this object is obsolete and should not be used anymore. use the new promise() constructor instead (or use the above backwards/forwards compatible deferred function given below). for example, the equivalent of var deferred = promise.defer(); dosomething(function cb(good) { if (good) deferred.resolve(); else deferred.reject(); }); return deferred.promise; would be return new promise(function(resolve, reject) { dosomething(function cb(good) { if (good) resolve(); else reject(); }); }); method overview void resolve([optional] avalue); void...
...ve no effect the second time, as the associated promise is already resolved to the pending promise value as its resolution. void resolve( avalue ); parameters avalue optional if this value is not a promise, including undefined, it becomes the fulfillment value of the associated promise. if this value is a promise, then the associated promise will be resolved to the passed promise, and follow the state as the provided promise (including any future transitions). reject() rejects the associated promise with the specified reason. if the promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. note: this function is bound to its associated promise when promise.defer() is called, and can be called with any value of this. void rej...
Task.jsm
been converted to tasks and some not. if you specify anything else, the yield operator returns exactly what you specified. method overview function async(atask); promise spawn(atask); properties attribute type description result read only constructor constructs a special exception that, when thrown inside a legacy generator function, allows the associated task to be resolved with a specific value. example: task.spawn( function() { yield ... ; throw new task.result("value"); } note: if you want to exit early from a generator function, without returning a value for the task, you can just use the return statement without any arguments. note: if you want to return a result from a non-legacy generator function, don't use ...
...etrieve the associated iterator. the generator function is a task, that is can yield promise objects to wait upon. the promise returned by the task either fulfills with the returned value if generator returns or rejects with the thrown error if the generator throws. if you specify the iterator returned by a generator function you called, the generator function is also executed as a task. this allows you to call the function with arguments. the promise returned by the task either fulfills with the returned value if generator returns or rejects with the thrown error if the generator throws. if you specify a function that is not a generator, it is called with no arguments, and its return value is used to fulfill the returned promise. if you specify anything else, you get a promise that is ...
XPCOMUtils.jsm
r( enumerator ); parameters enumerator the nsistringenumerator or nsiutf8stringenumerator instance to iterate over. return value a generator yielding enumerated strings. example for (var section in xpcomutils.iterstringenumerator(iniparser.getsections())) console.log(section); post-registration callback the post-registration callback called by generatemodule() should have the following signature: postregister( nsicomponentmanager compmgr, nsifile filespec, componentsarray ); parameters compmgr an nsicomponentmanager instance to use for managing the component. filespec an nsifile instance for... what? componentsarray an array of the components, as passed to generatemodule(). the function doesn't need to return a value. pre-unregistration callback the pre-...
... filespec, componentsarray ); parameters compmgr an nsicomponentmanager instance to use for managing the component. filespec an nsifile instance for... what? componentsarray an array of the components, as passed to generatemodule(). the function doesn't need to return a value. pre-unregistration callback the pre-unregistration callback passed to generatemodule() should have the following signature: preunregister( nsicomponentmanager compmgr, nsifile filespec, componentsarray ); parameters compmgr the nsicomponentmanager instance to use for managing the component. filespec an nsifile instance for... what? componentsarray the array of components passed to generatemodule(). this function doesn't need to return a value. examples definelazygetter var myservice...
L10n Checks
installation (releases) l10n checks needs to be installed. to do that, you must have python 2.5, 2.6, or 2.7 installed on your machine. once python is installed, the easiest way to install l10n checks (on mac or linux) is to just run: $ sudo easy_install -u l10n-checks or, if you're on windows: $ easy_install -u l10n-checks installation (development versions) l10n checks needs to be installed, and it requires that you have python and mercurial installed on your machine. ...
... or, if you're on windows: $ hg clone http://hg.mozilla.org/users/akalla_aviary.pl/silme-patched/ $ cd silme-patched/ $ python setup.py install running it mercurial source (source) mode l10n checks gathers the directories to compare from an ini file, usually found in $app/locales/l10n.ini. you pass both the path to the ini file and the parent directory of the localizations as first arguments, followed by the locale codes of the locales you want to compare. if you want to test the localization for de, run: check-l10n-completeness browser/locales/l10n.ini ../l10n/ de add-ons (xpi) mode l10n checks gathers the locales to compare from the chrome.manifest file inside the xpi file. you pass the path to the xpi file (optionally) followed by the locale codes of the locales you want to compare. if y...
L10n testing with xcode
open the client.xcodeproj file in xcode. select the client project in the left pane and choose editor > import localizations from the toolbar and select your localized xliff file. a window will then appear showing the diff between the imported xliff file and the existing resources in the project folder. click the import button. ...
...e simulator. this guide should help. press the run button in the upper left-hand corner (the button has a playback icon). navigate to the newly opened ios simulator window many strings are accessibility strings and are only revieled when a user hovers their finger over the button. to view these strings, you'll need to start the accessibility inspector within the ios simulator by doing the following. in the ios simulator, press the home button from the hardware toolbar menu. navigate to the settings app, open it, and go to general > accessibility. slide the accessibility inspector switch to on. the accessibility inspector remains active until you turn it off, even if you quit and restart ios simulator. press the home button again, navigate to the pane with your firefox for ...
Localizing XLIFF files for iOS
ue (e.g., target-language="xx-xx"). strings are located within <trans-unit> tags. source english strings are contained in <source> child tags. here is an example of such a <trans-unit> <trans-unit id="add to bookmarks"> <source>add to bookmarks</source> </trans-unit> your translations must be contained inside <target> child tags. go through the full xliff page adding <target></target> 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 ...
...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.</note> </tra...
Localizing extension metadata on addons.mozilla.org
summary description eula privacy policy version notes developer comments when you submit a new extension to amo, the process is divided into several steps. in step 2, you'll be asked to provide the attributes listed above in the add-on's default locale (selected in step 1). the values you provide here are used as fallback values if someone requests a language that doesn't exist. step 4 allows you to translate any of the above fields into any other language amo supports. remember, all fields are optional when localizing. any field that is blank will just show up in the default locale. getting translation help you are kindly advised not to use any automatic online translation, which can bring unpleasant low-quality output to users. always prefer a qualified human translation. amo do...
...re is no localization structure yet. you can already request for amo fields localization on the forums, and these fields will be added soon to the web translation system. amazon mechanical turk this is not free, but for a very modest amount of money you can get your amo page quickly translated by native speakers. create an account and then, using the “basic open-ended question” template, follow the instructions to upload the text of your amo page. on the properties page you can specify the location of the worker in order to restrict to people living in the country where the language is spoken. the reward is up to you, but $5-10 per translation seems to work well. localization codes amo offers 33 localizations, including english. here is a list of the codes: arabic (ar), catalan (ca),...
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). ...
... 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 and 5 for each of them. review the english content following 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 min...
MathML In Action
a 1 ) n 1 + a 2 ) n 2 + ... + a p ) n p ( ... ( ( a 0 + a 1 ) n 1 + a 2 ) n 2 + ... + a p ) n p the roots of this bold equation y 3 + p y + q = 0 are also bold y = - q 2 + q 2 4 + p 3 27 2 3 + - q 2 - q 2 4 + p 3 27 2 3 . ...
... this bold equation y 3 + p y + q = 0 are also bold y = - q 2 + q 2 4 + p 3 27 2 3 + - q 2 - q 2 4 + p 3 27 2 3 . ...
MathML Demo: <mspace> - space
mathml demo: <mspace> - space the background color of <mspace> elements has been set to yellow for easier viewing. you can set the width ∑ x y height ∫ x y and depth [ x y ] of mspace elements (click the math text to view the numeric values that are set). interactive sizing html content <p> use the control buttons below to adjust the parameters of the <code>mspace</code> element and see the effects. <br /> height <a class="control" href="javascript:upheight();" title="increase height">+</a>/ <a class="control" href="javascript:downheight();" title="decrease height">-</a> width <a class="control" href="javascript:upwidth();" title="increase width">+</a>/ <a class="control" href="javascript:downwidth();" title="decrease width">-</a> depth <a class="contro...
...pwidth();" title="increase width">+</a>/ <a class="control" href="javascript:downwidth();" title="decrease width">-</a> depth <a class="control" href="javascript:updepth();" title="increase depth">+</a>/ <a class="control" href="javascript:downdepth();" title="decrease depth">-</a> <math display="block"> <mstyle displaystyle="true"> <msqrt> <mrow> <mn>3</mn> <mspace style="background-color: yellow" id="thespace" height="0.1ex" depth="0.1ex" width="0.1em" /> <mi>x</mi> </mrow> </msqrt> </mstyle> </math> </p> javascript content var height=0; var width=0; var depth=0; function upheight() { height++; document.getelementbyid("thespace").setattribute("height",height+".1ex"); } function downheight() { height--; document.getelementbyid("thespace").setattribute("height",height+".1ex")...
Mozilla Development Strategies
tation 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. you (or someone else) will be back in that code someday.
...is not linear to time to review. a twenty line patch doesn't take twice as long to review as a ten line patch, it usually takes much more time. if you can divide and conquer what you are working on into smaller chunks, you will find you'll get faster reviews. of course, not everything can be divided up. and, shorter fixes aren't necessarily better than longer ones. having parallel trees should allow you to work on other items while you are awaiting reviews. get advice before working on a patch or feature, instead of after if you are blocked, or stumped as to what to work on, talk to a lead sooner rather than later. most likely they will have a bug they can hand off to you, or they can help get you unblocked. since they are going to be reviewing your code later, run your plan of attack by t...
JS::PerfMeasurement
osx (bug 583323) as well, and we welcome patches for other operating systems. the js::perfmeasurement class, found in jsperf.h, lets you take detailed performance measurements of your code. it is a stopwatch profiler -- that is, it counts events that occur while code of interest is running; it does not do call traces or sampling. ...
... values in the above table. you bitwise-or the ones you want together and pass them to the constructor. perfmeasurement::all in a constructor call, this special value means "measure everything that can possibly be measured." perfmeasurement::num_measurable_events this constant equals the total number of events defined by the api - not necessarily the total number of events that a particular os allows you to measure. (at time of writing, linux allows all the above events to be measured, and we don't have back ends for any other operating system. static bool perfmeasurement::canmeasuresomething() this class method returns true if and only if some -- not necessarily all -- events can be measured by the current build of spidermonkey, running on the current os. at present, it returns true on li...
Leak Gauge
leak gauge is a tool that can be used to detect certain kinds of leaks in gecko, including those involving documents, window objects, and docshells. it has two parts: (a) instrumentation in gecko that produces a log file, and (b) a script to post-process the log file. getting a log file to get a log file, run the browser with the following environment variables set. nspr_log_modules=domleak:5,documentleak:5,nsdocshellleak:5,nodeinfomanagerleak:5 nspr_log_file=nspr.log # or any other filename of your choice this will overwrite any existing file called nspr.log. the browser will run with negligible slowdown. you must exit the browser before post-processing the log file or the results will be unreliable. post-processing a log file post-process the log file with tools/leak-gaug...
...me of your choice this will overwrite any existing file called nspr.log. the browser will run with negligible slowdown. you must exit the browser before post-processing the log file or the results will be unreliable. post-processing a log file post-process the log file with tools/leak-gauge/leak-gauge.pl or tools/leak-gauge/leak-gauge.html. if there are no leaks, output will look like the following. results of processing log leak.log : summary: leaked 0 out of 11 dom windows leaked 0 out of 44 documents leaked 0 out of 3 docshells leaked content nodes in 0 out of 0 documents if there are leaks, output will look like the following. results of processing log leak2.log : leaked outer window 2c6e410 at address 2c6e410. leaked outer window 2c6ead0 at address 2c6ead0. leaked inner window 2...
perf
perf is a powerful system-wide instrumentation service that is part of linux. this article discusses how it can be relevant to power profiling. 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. energy estimates perf can access the intel rapl energy estimates. the following example shows how to invoke it for this purpose. sudo perf stat -a -r 1 \ -e "power/energy-pkg/" \ -e "power/energy-cores/" \ -e "power/energy-gpu/" \ -e "power/energy-ram/" \ <command> the -a is necessary; it means "all cores", and without it all the measurements will be zero. the -r 1 means <command> is executed once; higher values can be used to get variations. the output will look like the...
...voke it for this purpose. sudo perf stat -a -r 1 \ -e "power/energy-pkg/" \ -e "power/energy-cores/" \ -e "power/energy-gpu/" \ -e "power/energy-ram/" \ <command> the -a is necessary; it means "all cores", and without it all the measurements will be zero. the -r 1 means <command> is executed once; higher values can be used to get variations. the output will look like the following. performance counter stats for 'system wide': 51.58 joules power/energy-pkg/ [100.00%] 14.80 joules power/energy-cores/ [100.00%] 9.93 joules power/energy-gpu/ [100.00%] 27.38 joules power/energy-ram/ [100.00%] 5.003049064 seconds time elapsed it's not clear from the output, but the following relationship holds. energy-pkg >= energy-cores + energy-gpu the measu...
MailNews automated testing
this page and its sub-pages describe (and link to) the available test mechanisms within mailnews, and provide supporting information for developers and testers. functional testing xpcshell-tests and make check these are core test harnesses to which mailnews adds its own tests. these tests are run against almost every changeset that gets committed to the thunderbird and seamonkey code bases. xpcshell-tests are run in javascript without any chrome present. ...
...sts are run against almost every changeset that gets committed to the thunderbird and seamonkey code bases. xpcshell-tests are run in javascript without any chrome present. this makes them especially useful for testing at the component / module level. xpcshell-tests are the quickest tests to run. mailnews provides additional facilities as described on the mailnews automated testing page (see below). "make check" is used to run compiled code tests. these tests can go beyond the limitations of xpcshell-tests (for example, access c++ code) and other testing options that don't test at the right level. testing frameworks the asynctestutils extended framework supports: asynchronous test operation: a reasonably convenient means of writing tests that involve asynchronous operations by using...
Midas
em will bump up a level in the list or break out of the list entirely. paste this command will paste the contents of the clipboard at the location of the caret. if there is a selection, it will be deleted prior to the insertion of the clipboard's contents. note: this command won't work without setting a pref or using signed js. user_pref("capability.policy.policynames", "allowclipboard"); user_pref("capability.policy.allowclipboard.clipboard.paste", "allaccess"); see: more about security preferences note: the shortcut key will automatically trigger this command (typically accel-v) with or without the signed js or any code on the page to handle it. redo this command will redo the previous undo action. if undo was not the most recent action, this...
...f the stylewithcss command is false and generate css style attribute if the stylewithcss command is true. subscript if there is no selection, the insertion point will set subscript for subsequently typed characters. if there is a selection and all of the characters are already subscripted, the subscript will be removed. otherwise, all selected characters will be drawn slightly lower than normal text. superscript if there is no selection, the insertion point will set superscript for subsequently typed characters. if there is a selection and all of the characters are already superscripted, the superscript will be removed. otherwise, all selected characters will be drawn slightly higher than normal text. underline if there is no sel...
Creating a Cookie Log
enabling cookie logging windows open a command prompt (this is under programs or programs/accessories in normal installations of windows). ...
... enabling cookie logging windows open a command prompt (this is under programs or programs/accessories in normal installations of windows). ...
Cached Monitors
this chapter describes the functions you use when you work with cached monitors. unlike a plain monitor, a cached monitor is associated with the address of a protected object, and the association is maintained only while the protection is needed. this arrangement allows a cached monitor to be associated with another object without preallocating a monitor for all objects. a hash table is used to quickly map addresses to their respective monitors. the system automatically enlarges the hash table as needed. important cached monitors are slower to use than their uncached counterparts. see monitors for information about uncached monitors. cached monitors functions cached monitors allow the client to associate monitoring protection and state change synchronization in a lazy fashion. the monit...
...this additional flexibility comes at the cost of a small loss in performance. pr_centermonitor enters the lock associated with a cached monitor. pr_cexitmonitor decrements the entry count associated with a cached monitor. pr_cwait waits for a notification that a monitor's state has changed. ...
Dynamic Library Linking
path 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. (this is admittedly an omission that should be fixed.) however, it is possible to look up symbols defined in the main executable program as follows. prlibrary *lib; void *funcptr; funcptr = pr_findsymbolandlibrary("functionname", &lib); when pr_findsymbolandlibrary returns, funcptr is the value of the function pointer you want to look up, and the variable lib references the main executable program. you can then call pr_findsymbol on lib to look up other symbols defined in the main program. remember to call pr_unloadlibrary(lib) to close...
...ing the dynamic library search path is shlib_path. moreover, the executable program must be linked with the +s option so that it will search for shared libraries in the directories specified by shlib_path at run time. alternatively, you can enable the +s option as a postprocessing step using the chatr tool. for example, link your executable program a.out without the +s option, then execute the following: chatr +s enable a.out on rhapsody, the environment variable is dyld_library_path. on win32, the environment variable is path. the same search path is used to search for executable programs and dlls. exporting symbols from the main executable program on some systems, symbols defined in the main executable program are not exported by default. on hp-ux, you must link the executable pro...
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. ...
...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. ...
Named Shared Memory
the chapter describes the nspr api for named shared memory. shared memory allows multiple processes to access one or more common shared memory regions, using it as an interprocess communication channel. the nspr shared memory api provides a cross-platform named shared-memory interface that is modeled on similar constructs in the unix and windows operating systems. shared memory protocol named shared memory functions shared memory protocol using named shared memory functions pr_opensharedmemory creates the shared memory segment, if it does not already exist, or opens a connection with the existing shared memory segment if it already exists. pr_attachsharedmemory should be called following pr_opensharedmemory to map the memory segment to an address in the application's address space. ...
... pr_attachsharedmemory may also be called to remap a shared memory segment after detaching the same prsharedmemory object. be sure to detach it when you're 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_op...
PRHostEnt
ethostbyaddr and passed to pr_enumeratehostent. clients should avoid directly accessing any of the structure's fields. syntax #include <prnetdb.h> typedef struct prhostent { char *h_name; char **h_aliases; #if defined(_win32) print16 h_addrtype; print16 h_length; #else print32 h_addrtype; print32 h_length; #endif char **h_addr_list; } prhostent; fields the structure has the following fields: h_name pointer to the official name of host. 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 s...
... ...
PRLinger
structure used with the pr_sockopt_linger socket option to specify the time interval (in printervaltime units) to linger on closing a socket if any data 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 remai...
...altime 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 structure of type prlinger, makes it possible to change this default as follows: if polarity is set to pr_false, pr_close returns immediately, but if there are any data remaining in the socket send buffer, the runtime attempts to deliver the data to the peer. if polarity is set to pr_true and linger is set to 0 (pr_interval_no_wait), the runtime aborts the connection when it is closed and discards any data remaining in the socket send buffer. if polarity is set to pr_tr...
PRNetAddr
type used with socket manipulation functions to specify a network address. syntax #include <prio.h> union prnetaddr { struct { pruint16 family; char data[14]; } raw; struct { pruint16 family; pruint16 port; pruint32 ip; char pad[8]; } inet; #if defined(_pr_inet6) struct { pruint16 family; pruint16 port; pruint32 flowinfo; pripv6addr ip; } ipv6; #endif /* defined(_pr_inet6) */ }; typedef union prnetaddr prnetaddr; fields the structure has the following fields: family address family: pr_af_inet|pr_af_inet6 for raw.family, pr_af_inet for inet.family, pr_af_inet6 for ipv6.family. data raw address data. port port number of tcp or udp, in network byte order. ip the actual 32 (for inet.ip) or 128 (for ipv6.ip) bits of ip...
... description the union prnetaddr represents a network address. nspr supports only the internet address family. by default, nspr is built to support only ipv4, but it's possible to build the nspr library to support both ipv4 and ipv6. ...
PRSockOption
pr_sockopt_keepalive periodically test whether connection is still alive. pr_sockopt_recvbuffersize receive buffer size. pr_sockopt_sendbuffersize send buffer size. pr_sockopt_iptimetolive ip...
... pr_sockopt_keepalive periodically test whether connection is still alive. pr_sockopt_recvbuffersize receive buffer size. ...
PRSocketOptionData
keep_alive periodically test whether connection is still alive. mcast_loopback ip multicast loopback. no_delay disable nagle algorithm. don't delay send to coalesce packets. max_segment tcp ...
... keep_alive periodically test whether connection is still alive. mcast_loopback ip multicast loopback. no_delay disable nagle algorithm. ...
PR_AcceptRead
accepts a new connection and receives a block of data. syntax #include <prio.h> print32 pr_acceptread( prfiledesc *listensock, prfiledesc **acceptedsock, prnetaddr **peeraddr, void *buf, print32 amount, printervaltime timeout); parameters the function has the following parameters: listensock a pointer to a prfiledesc object representing a socket descriptor that has been called with the pr_listen function, also known as the rendezvous socket. acceptedsock a pointer to a pointer to a prfiledesc object. on return, *acceptedsock points to the prfiledesc object for the newly connected socket. this parameter is valid only if the function return does not indicate failure. peeraddr a pointer a pointer to a prnetaddr object. on return, peeraddr points to the address of the r...
...eraddr points to the address of the remote socket. the prnetaddr object that peeraddr points to will be in the buffer pointed to by buf. this parameter is valid only if the function return does not indicate failure. buf a pointer to a buffer to hold data sent by the peer and the peer's address. this buffer must be large enough to receive amount bytes of data and two prnetaddr structures (thus allowing the runtime to align the addresses as needed). amount the number of bytes of data to receive. does not include the size of the prnetaddr structures. if 0, no data will be read from the peer. timeout the timeout interval only applies to the read portion of the operation. pr_acceptread blocks indefinitely until the connection is accepted; the read will time out after the timeout interval ela...
PR_Bind
if unsuccessful, pr_failure. further information can be obtained by calling pr_geterror. ...
... if unsuccessful, pr_failure. further information can be obtained by calling pr_geterror. ...
PR_CExitMonitor
if unsuccessful, pr_failure. this may indicate that the address parameter is invalid or that the calling thread is not in the monitor. ...
... if unsuccessful, pr_failure. this may indicate that the address parameter is invalid or that the calling thread is not in the monitor. ...
PR_Close
if the file descriptor is not closed successfully, pr_failure. description the file descriptor may represent a normal file, a socket, or an end point of a pipe. ...
... if the file descriptor is not closed successfully, pr_failure. description the file descriptor may represent a normal file, a socket, or an end point of a pipe. ...
PR_CloseFileMap
if the memory region is not successfully unmapped, pr_failure. the error code can be retrieved via pr_geterror. ...
... if the memory region is not successfully unmapped, pr_failure. the error code can be retrieved via pr_geterror. ...
PR_CreateThread
creates a new thread. syntax #include <prthread.h> prthread* pr_createthread( prthreadtype type, void (*start)(void *arg), void *arg, prthreadpriority priority, prthreadscope scope, prthreadstate state, pruint32 stacksize); parameters pr_createthread has the following parameters: type specifies that the thread is either a user thread (pr_user_thread) or a system thread (pr_system_thread). 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 specif...
...erence if necessary. state specifies whether the thread is joinable (pr_joinable_thread) or unjoinable (pr_unjoinable_thread). stacksize specifies your preference for the size of the stack, in bytes, associated with the newly created thread. if you pass zero in this parameter, pr_createthread chooses the most favorable machine-specific stack size. returns the function returns one of the following values: if successful, a pointer to the new thread. this pointer remains valid until the thread returns from its root function. if unsuccessful, (for example, if system resources are unavailable), null. description if you want the thread to start up waiting for the creator to do something, enter a lock before creating the thread and then have the thread's root function enter and exit th...
PR_Delete
if the file is not deleted, pr_failure. ...
... if the file is not deleted, pr_failure. ...
PR_EnumerateHostEnt
to begin an enumeration, this argument is set to zero. ...
...ter to a prhostent structure obtained from pr_gethostbyname or pr_gethostbyaddr. port the port 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 prhos...
PR_GetHostByAddr
buf a pointer to a buffer, allocated by the caller, that is filled in with host data on output. all of the pointers in the hostentry structure point to data saved in this buffer. this buffer is referenced by the runtime during a call to pr_enumeratehostent. ...
...o data saved in this buffer. this buffer is referenced by the runtime during a call to pr_enumeratehostent. bufsize number of bytes in the buf parameter. the buffer must be at least pr_netdb_buf_size bytes. hostentry this structure is allocated by the caller. on output, this structure is filled in by the runtime if the function returns pr_success. 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 pr_gethostbyaddr is used to perform reverse lookups of network addresses. that is, given a valid network address (of type prnetaddr), pr_gethostbyaddr discovers the address' primary name, any aliases, and any other network addresses for the same...
PR_GetHostByName
buf a pointer to a buffer, allocated by the caller, that is filled in with host data on output. all of the pointers in the hostentry structure point to data saved in this buffer. this buffer is referenced by the runtime during a call to pr_enumeratehostent. bufsize number of bytes in the buf parameter. ...
...o data saved in this buffer. this buffer is referenced by the runtime during a call to pr_enumeratehostent. bufsize number of bytes in the buf parameter. the buffer must be at least pr_netdb_buf_size bytes. hostentry this structure is allocated by the caller. on output, this structure is filled in by the runtime if the function returns pr_success. 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. ...
PR_GetIdentitiesLayer
if not successful, null. ...
... if not successful, null. ...
PR_GetNameForIdentity
if unsuccessful, the function returns null. ...
... if unsuccessful, the function returns null. ...
PR_GetSpecialFD
gets the file descriptor that represents the standard input, output, or error stream. syntax #include <prio.h> prfiledesc* pr_getspecialfd(prspecialfd id); parameter the function has the following parameter: id a pointer to an enumerator of type prspecialfd, indicating the type of i/o stream desired: pr_standardinput, pr_standardoutput, or pr_standarderror. returns if the id parameter is valid, pr_getspecialfd returns a file descriptor that represents the corresponding standard i/o stream. otherwise, pr_getspecialfd returns null and sets the error to pr_invalid_argument_error. ...
...or of type prspecialfd, indicating the type of i/o stream desired: pr_standardinput, pr_standardoutput, or pr_standarderror. returns if the id parameter is valid, pr_getspecialfd returns a file descriptor that represents the corresponding standard i/o stream. otherwise, pr_getspecialfd returns null and sets the error to pr_invalid_argument_error. description type prspecialfd is defined as follows: typedef enum prspecialfd{ pr_standardinput, pr_standardoutput, pr_standarderror } prspecialfd; #define pr_stdin pr_getspecialfd(pr_standardinput) #define pr_stdout pr_getspecialfd(pr_standardoutput) #define pr_stderr pr_getspecialfd(pr_standarderror) file descriptors returned by pr_getspecialfd are owned by the runtime and should not be closed by the caller. ...
PR ImportTCPSocket
if the import of the native tcp socket failed, null. description a native tcp socket osfd can be imported into nspr with pr_importtcpsocket. ...
... if the import of the native tcp socket failed, null. description a native tcp socket osfd can be imported into nspr with pr_importtcpsocket. ...
PR_Init
initializes the runtime. syntax #include <prinit.h> void pr_init( prthreadtype type, prthreadpriority priority, pruintn maxptds); parameters pr_init has the following parameters: type this parameter is ignored. priority this parameter is ignored. maxptds this parameter is ignored. description nspr is now implicitly initialized, usually by the first nspr function called by a program. ...
...pruintn maxptds); parameters pr_init has the following parameters: type this parameter is ignored. priority this parameter is ignored. maxptds this parameter is ignored. description nspr is now implicitly initialized, usually by the first nspr function called by a program. pr_init is necessary only if a program has specific initialization-sequencing requirements. ...
PR_Initialize
provides an alternate form of explicit initialization. in addition to establishing the 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 vec...
...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 parameter is ignored. returns the value returned from the root 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_JoinThread
description pr_jointhread is used to synchronize the termination of a thread. ...
... description pr_jointhread is used to synchronize the termination of a thread. ...
PR_Listen
if unsuccessful, pr_failure. further information can be obtained by calling pr_geterror. ...
... if unsuccessful, pr_failure. further information can be obtained by calling pr_geterror. description pr_listen turns the specified socket into a rendezvous socket. ...
PR_NetAddrToString
if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. ...
... if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. ...
PR_NewTCPSocket
if the creation of a new tcp socket failed, null. description tcp (transmission control protocol) is a connection-oriented, reliable byte-stream protocol of the tcp/ip protocol suite. pr_newtcpsocket creates a new ipv4 tcp socket. a tcp connection is established by a passive socket (the server) accepting a connection setup request from an active socket (the client). ...
...transmitfile. pr_acceptread is suitable for use by the server to accept a new client connection and read the client's first request in one function call. a tcp connection can be shut down by pr_shutdown, and the sockets should be closed by pr_close. see also pr_newtcpsocket is deprecated because it is hardcoded to create an ipv4 tcp socket. new code should use pr_opentcpsocket instead, which allows the address family (ipv4 or ipv6) of the new tcp socket to be specified. ...
PR_NewUDPSocket
if the creation of a new udp socket failed, null. description udp (user datagram protocol) is a connectionless, unreliable datagram protocol of the tcp/ip protocol suite. udp datagrams may be lost or delivered in duplicates or out of sequence. pr_newudpsocket creates a new udp socket. the socket may be bound to a well-known port number with pr_bind. ...
...dpsocket creates a new udp socket. the socket may be bound to a well-known port number with pr_bind. datagrams can be sent with pr_sendto and received with pr_recvfrom. when the socket is no longer needed, it should be closed with a call to pr_close. see also pr_newudpsocket is deprecated because it is hardcoded to create an ipv4 udp socket. new code should use pr_openudpsocket instead, which allows the address family (ipv4 or ipv6) of the new udp socket to be specified. ...
PR_Notify
if unsuccessful, pr_failure. description notification of a monitor signals the change of state of some monitored data. ...
... if unsuccessful, pr_failure. description notification of a monitor signals the change of state of some monitored data. ...
PR_NotifyAll
if unsuccessful, pr_failure. description a call to pr_notifyall causes all of the threads waiting on the monitor to be scheduled to be promoted to a ready state. ...
... if unsuccessful, pr_failure. description a call to pr_notifyall causes all of the threads waiting on the monitor to be scheduled to be promoted to a ready state. ...
PR_OpenTCPSocket
if the creation of a new tcp socket failed, null. ...
... if the creation of a new tcp socket failed, null. ...
PR OpenUDPSocket
if the creation of a new udp socket failed, null. ...
... if the creation of a new udp socket failed, null. ...
PR_Read
the value 0 means end of file is reached or the network connection is closed. ...
... the value 0 means end of file is reached or the network connection is closed. the value -1 indicates a failure. ...
PR_RecvFrom
receives bytes from a socket and stores the sending peer's address. syntax #include <prio.h> print32 pr_recvfrom( prfiledesc *fd, void *buf, print32 amount, printn flags, prnetaddr *addr, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. buf a pointer to a buffer containing the data received. amount the size of buf (in bytes). flags this obsolete parameter must always be zero. ...
...r to a buffer containing the data received. amount the size of buf (in bytes). flags this obsolete parameter must always be zero. addr a pointer to the prnetaddr object that will be filled in with the address of the sending peer on return. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. returns the function returns one of the following values: a positive number indicates the number of bytes actually received. the value 0 means the network connection is closed. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_geterror. description pr_recvfrom receives up to a specified number of bytes from socket, which may or may not be connected. the operation blocks until one or more bytes ...
PR_Rename
if file is not successfully renamed, pr_failure. description pr_rename renames a file from its old name (from) to a new name (to). ...
... if file is not successfully renamed, pr_failure. description pr_rename renames a file from its old name (from) to a new name (to). ...
PR_Seek
moves the current read-write file pointer by an offset expressed as a 32-bit integer. deprecated in favor of pr_seek64. syntax #include <prio.h> print32 pr_seek( prfiledesc *fd, print32 offset, prseekwhence whence); parameters the function has the following parameters: fd a pointer to a prfiledesc object. offset a value, in bytes, used with the whence parameter to set the file pointer. a negative value causes seeking in the reverse direction. whence a value of type prseekwhence that specifies how to interpret the offset parameter in setting the file pointer associated with the fd parameter. the value for the whence parameter can be one of the following: pr_seek_set. sets the file pointer to the value of the offset parameter. pr_seek_cur. sets the file pointer to ...
... if the function fails, the file pointer remains unchanged and the function returns -1. the error code can then be retrieved with pr_geterror. ...
PR_Seek64
moves the current read-write file pointer by an offset expressed as a 64-bit integer. syntax #include <prio.h> print64 pr_seek64( prfiledesc *fd, print64 offset, prseekwhence whence); parameters the function has the following parameters: fd a pointer to a prfiledesc object. offset a value, in bytes, used with the whence parameter to set the file pointer. a negative value causes seeking in the reverse direction. whence a value of type prseekwhence that specifies how to interpret the offset parameter in setting the file pointer associated with the fd parameter. the value for the whence parameter can be one of the following: pr_seek_set. sets the file pointer to the value of the offset parameter. pr_seek_cur. sets the file pointer to its current location plus the value...
... if the function fails, the file pointer remains unchanged and the function returns -1. the error code can then be retrieved with pr_geterror. ...
PR_SetLibraryPath
a runtime. syntax #include <prlink.h> prstatus pr_setlibrarypath(const char *path); parameters the function has this parameter: path a pointer to a character array that contains the directory path that the application should use as a default. the syntax of the pathname is not defined, nor whether that pathname should be absolute or relative. ...
...pathname is not defined, nor whether that pathname should be absolute or relative. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. this may indicate that the function cannot allocate sufficient storage to make a copy of the path string description this function registers a default library pathname with the runtime. this allows an environment to express policy decisions globally and lazily, rather than hardcoding and distributing the decisions throughout the code. ...
PR_SetThreadPrivate
if the index is invalid, pr_failure. ...
... if the index is invalid, pr_failure. ...
PR_Shutdown
shuts down part of a full-duplex connection on a specified socket. syntax #include <prio.h> prstatus pr_shutdown( prfiledesc *fd, prshutdownhow how); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a connected socket. how the kind of disallowed operations on the socket. possible values include the following: pr_shutdown_rcv. further receives will be disallowed. pr_shutdown_send. further sends will be disallowed. pr_shutdown_both. further sends and receives will be disallowed. returns the function returns one of the following values: upon successful completion of shutdown request, pr_success. if unsuccessful, pr_failure. further information can be obtained by calling pr_geterror. description the prshu...
... pr_shutdown_send. further sends will be disallowed. pr_shutdown_both. further sends and receives will be disallowed. returns the function returns one of the following values: upon successful completion of shutdown request, pr_success. if unsuccessful, pr_failure. further information can be obtained by calling pr_geterror. ...
PR_StringToNetAddr
if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. description for ipv4 addresses, the input string represents numbers in the internet standard "." notation. ...
... if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. description for ipv4 addresses, the input string represents numbers in the internet standard "." notation. ...
PR_TransmitFile
sends a complete file across a connected socket. syntax #include <prio.h> print32 pr_transmitfile( prfiledesc *networksocket, prfiledesc *sourcefile, const void *headers, print32 hlen, prtransmitfileflags flags, printervaltime timeout); parameters the function has the following parameters: networksocket a pointer to a prfiledesc object representing the connected socket to send data over. sourcefile a pointer to a prfiledesc object representing the file to send. headers a pointer to the buffer holding the headers to be sent before sending data. hlen length of the headers buffer in bytes. flags one of the following flags: pr_transmitfile_keep_open indicates that the socket will be kept open after the data is sent. pr_transmitfile_close_socket indicates that t...
...e_socket flag is ignored. the reason for the failure can be obtained by calling pr_geterror. ...
PR_Unmap
if the memory region is not successfully unmapped, pr_failure. the error code can be retrieved via pr_geterror. ...
... if the memory region is not successfully unmapped, pr_failure. the error code can be retrieved via pr_geterror. ...
PR_Wait
waits for an application-defined state of the monitored data to exist. syntax #include <prmon.h> prstatus pr_wait( prmonitor *mon, printervaltime ticks); parameters the function has the following parameter: mon a reference to an existing structure of type prmonitor. the monitor object referenced must be one for which the calling thread currently holds the lock. ticks the amount of time (in printervaltime units) that the thread is willing to wait for an explicit notification before being rescheduled. returns the function returns one of the following values: pr_success means the thread is being resumed from the pr_wait call either because it was explicitly notified or because the time specified by the parameter ticks has expired. pr_failure means pr_wait encountered a sy...
...ty of the programmer to evaluate the data and act accordingly. this is usually done by evaluating a boolean expression involving the monitored data. while the boolean expression is false, the thread should wait. the thread should act on the data only when the expression is true. the boolean expression must be evaluated while in the monitor and within a loop. in pseudo-code, the sequence is as follows: pr_entermonitor(&ml); while (!expression) wait; ... act on the state 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 expre...
PR_Write
the value -1 indicates that the operation failed. ...
... the value -1 indicates that the operation failed. the reason for the failure is obtained by calling pr_geterror. ...
NSS CERTVerify Log
port_newarena(512); log = port_arenaznew(arena,log); log->arena = arena; you can then pass this log into your favorite cert verify function. on return: log->count is the number of entries. log->head is the first entry; log->tail is the last entry. each entry is a certverifylognode. defined in certt.h: /* * this structure is used to keep a log of errors when verifying * a cert chain. this allows multiple errors to be reported all at * once. */ struct certverifylognodestr { certcertificate *cert; /* what cert had the error */ long error; /* what error was it? */ unsigned int depth; /* how far up the chain are we */ void *arg; /* error specific argument */ struct certverifylognodestr *next; /* next in the list */ struct certverif...
...when you are through, you will need to walk the list and free all the cert entries, then free the arena. ...
Deprecated SSL functions
each function name is linked to its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. ...
...each function name is linked to its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. ...
NSS 3.14.1 release notes
nss 3.14.1 is licensed under the mpl 2.0. distribution information the cvs tag is nss_3_14_1_rtm. nss 3.14.1 requires nspr 4.9.4 or newer. nss 3.14.1 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_1_rtm/src/ new in nss 3.14.1 new functionality nss now has the ability to create signed ocsp responses. ...
...pported them. bug 611451 - when built with the current version of apple xcode on mac os x, the nss shared libraries will now only export the public nss functions. bug 810582 - tls false start is now only used with servers that negotiate a cipher suite that supports forward secrecy. note: the criteria for false start may change again in future nss releases. bugs fixed in nss 3.14.1 the following bugzilla query returns all of the bugs fixed in nss 3.14.1: https://bugzilla.mozilla.org/buglist.cgi?list_id=5216669;resolution=fixed;query_format=advanced;bug_status=resolved;bug_status=verified;target_milestone=3.14.1;product=nss compatability nss 3.14.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will...
NSS 3.14.2 release notes
nss 3.14.2 should be used with nspr 4.9.5 or newer. the release is available for download from https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_2_rtm/src/ for the primary nss documentation pages please visit /docs/nss new in nss 3.14.2 nss will now make use of the intel aes-ni and avx instruction sets for hardware-accelerated aes-gcm on 64-bit linux systems. note: the new assembly code requires gnu as version 2.19 or newer. ...
... 64-bit mode, nss will include runtime detection to check if the platform supports aes-ni and pclmulqdq. if so, nss uses the optimized code path, reducing the cpu cycles per byte to 1/20 of what was required before the patch (https://bugzilla.mozilla.org/show_bug.cgi?id=805604 and https://crypto.stanford.edu/realworldcrypto/slides/gueron.pdf). support for other platforms, such as windows, will follow in a future nss release. (https://bugzilla.mozilla.org/show_bug.cgi?id=540986) sqlite has been updated to 3.7.15. note: please apply the patch in https://bugzilla.mozilla.org/show_bug.cgi?id=837799 if you build nss with the system sqlite library and your system sqlite library is older than 3.7.15. bug 816853 - when using libpkix for certificate validation, applications may now supply addition...
NSS 3.14.4 release notes
users are encouraged to upgrade immediately. ...
...users are encouraged to upgrade immediately. bug 894370 - (cve-2013-1739) avoid uninitialized data read in the event of a decryption failure. new in nss 3.14.4 new functionality no new major functionality is introduced in this release. ...
NSS 3.14.5 release notes
users are encouraged to upgrade immediately. ...
...users are encouraged to upgrade immediately. bug 934016 - (cve-2013-5605) handle invalid handshake packets new in nss 3.14.5 new functionality no new major functionality is introduced in this release. this release is a patch release to address cve-2013-5605. ...
NSS 3.15.3.1 release notes
users are encouraged to upgrade immediately. ...
...users are encouraged to upgrade immediately. bug 946351 - misissued google certificates from dcssi new in nss 3.15.3.1 new functionality no new major functionality is introduced in this release. ...
NSS 3.15.3 release notes
users are encouraged to upgrade immediately. ...
...users are encouraged to upgrade immediately. ...
NSS 3.15.4 release notes
users are encouraged to upgrade immediately. ...
...users are encouraged to upgrade immediately. ...
NSS 3.16.2 release notes
distribution information the hg tag is nss_3_16_2_rtm. nss 3.16.2 requires nspr 4.10.6 or newer. nss 3.16.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_16_2_rtm/src/ new in nss 3.16.2 new functionality dtls 1.2 is supported. the tls application layer protocol negotiation (alpn) extension is also supported on the server side. ...
... command has three new certificate usage specifiers: l: certificateusagesslca a: certificateusageanyca y: certificateusageverifyca the pp command has a new command-line option -u, which means "use utf-8". the default is to show a non-ascii character as ".". on linux, nss is built with the -ffunction-sections -fdata-sections compiler flags and the --gc-sections linker flag to allow unused functions to be discarded. bugs fixed in nss 3.16.2 this bugzilla query returns all the bugs fixed in nss 3.16.2: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.16.2 ...
NSS 3.16.4 release notes
introduction network security services (nss) 3.16.4 is a patch release for nss 3.16. the bug fixes in nss 3.16.4 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_16_4_rtm. nss 3.16.4 requires nspr 4.10.6 or newer. nss 3.16.4 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_4_rtm/src/ new in nss 3.16.4 this release consists primarily of ca certificate changes 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 disc...
... has been included, without explicit trust. the intention is to mitigate the effects of the previous removal of the 1024-bit entrust.net root certificate, because many public internet sites still use the "usertrust legacy secure server ca" intermediate certificate that is signed by the 1024-bit entrust.net root certificate. the inclusion of the intermediate certificate is a temporary measure to allow those sites to function, by allowing them to find a trust path to another 2048-bit root ca certificate. the temporarily included intermediate certificate expires november 1, 2015. bugs fixed in nss 3.16.4 this bugzilla query returns all the bugs fixed in nss 3.16.4: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milest...
NSS 3.16.5 release notes
users are encouraged to upgrade immediately. ...
...users are encouraged to upgrade immediately. bug 1064636 - (cve-2014-1568) rsa signature forgery in nss. see also mfsa 2014-73 for details. new in nss 3.16.5 new functionality no new functionality is introduced in this release. ...
NSS 3.17.1 release notes
users are encouraged to upgrade immediately. ...
...users are encouraged to upgrade immediately. bug 1064636 - (cve-2014-1568) rsa signature forgery in nss. see also mfsa 2014-73 for details. new in nss 3.17.1 this patch release adds new functionality and fixes a bug that caused nss to accept forged rsa signatures. ...
NSS 3.18 release notes
to tls 1.2. similarly, the highest dtls protocol version enabled by default has been increased from dtls 1.0 to dtls 1.2. the default key size used by certutil when creating an rsa key pair has been increased from 1024 bits to 2048 bits. on mac os x, by default the softokn shared library will link with the sqlite library installed by the operating system, if it is version 3.5 or newer. ...
...ate authority sha1 fingerprint: d2:32:09:ad:23:d3:14:23:21:74:e4:0d:7f:9d:62:13:97:86:63:3a cn = equifax secure global ebusiness ca-1 sha1 fingerprint: 7e:78:4a:10:1c:82:65:cc:2d:e1:f1:6d:47:b4:40:ca:d9:0a:19:45 cn = tc trustcenter class 3 ca ii sha1 fingerprint: 80:25:ef:f4:6e:70:c8:d4:72:24:65:84:fe:40:3b:8a:8d:6a:db:f5 the following ca certificates were added cn = staat der nederlanden root ca - g3 sha1 fingerprint: d8:eb:6b:41:51:92:59:e0:f3:e7:85:00:c0:3d:b6:88:97:c9:ee:fc cn = staat der nederlanden ev root ca sha1 fingerprint: 76:e2:7e:c1:4f:db:82:c1:c0:a6:75:b5:05:be:3d:29:b4:ed:db:bb cn = identrust commercial root ca 1 sha1 fingerprint: df:71:7e:aa:4a:d9:4e:...
NSS 3.19.2.3 release notes
(current users of nss 3.19.3, nss 3.19.4 or nss 3.20.x are advised to update to nss 3.21.1, nss 3.22.2, or a later release.) distribution information the hg tag is nss_3_19_2_3_rtm. nss 3.19.2.3 requires nspr 4.10.10 or newer. ...
...r newer. nss 3.19.2.3 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_3_rtm/src/ new in nss 3.19.2.3 new functionality no new functionality is introduced in this release. security fixes in nss 3.19.2.3 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures. an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user. acknowledgements the nss development team would like to thank security researcher francis gabriel for responsibly disclosing the issue in bug 1245528. compatibility nss 3.19...
NSS 3.22 release notes
es 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. pseudorandom functions based 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 1009...
...pe ckm_rsa_pkcs_pss is now supported for rsa in addition to ckm_rsa_pkcs. the ck_rsa_pkcs_pss mechanism takes a parameter of type ck_rsa_pkcs_pss_params. ...
NSS 3.27.1 release notes
in this release. this is a patch release to address a tls compatibility issue which some applications experienced with nss 3.27. notable changes in nss 3.27.1 availability of the tls 1.3 (draft) implementation has been re-disabled in the default build. previous versions of nss made tls 1.3 (draft) available only when compiled with nss_enable_tls_1_3. nss 3.27 set this value on by default, allowing tls 1.3 (draft) to be disabled using nss_disable_tls_1_3, although the maximum version used by default remained tls 1.2. however, some applications query the list of protocol versions that are supported by the nss library, enabling all supported tls protocol versions. because nss 3.27 enabled compilation of tls 1.3 (draft) by default, it caused those applications to enable tls 1.3 (draft). th...
...abled compilation of tls 1.3 (draft) by default, it caused those applications to enable tls 1.3 (draft). this resulted in connectivity failures, as some tls servers are version 1.3 intolerant, and failed to negotiate an earlier tls version with nss 3.27 clients. nss 3.27.1 once again requires nss_enable_tls_1_3 to be deliberately set to enable tls 1.3 (draft). bugs fixed in nss 3.27.1 the following bug has been fixed in nss 3.27.1: re-disable tls 1.3 by default compatibility nss 3.27.1 shared libraries are backwards compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.27.1 shared libraries without recompiling or relinking. applications that restrict their use of nss apis to the functions listed in nss public func...
NSS 3.27 release notes
eleased nss 3.27, which is a minor release. 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). added support for rsa-pss signatures in tls 1.2 and tls 1.3 new functions in ssl.h ssl_namedgroupconfig notable changes in nss 3.27 update 2016-10-02: the maximum tls version supported has been increased to tls 1.3 (draft). although the maximum tls version enabled by default is sti...
... enable all supported versions. for those applications, updating to nss 3.27 may result in tls 1.3 (draft) to be enabled. the tls 1.3 (draft) protocol can be disabled, by defining symbol nss_disable_tls_1_3 when building nss. npn can not be enabled anymore. hard limits on the maximum number of tls records encrypted with the same key are enforced. disabled renegotiation in dtls. ...
NSS 3.28.3 release notes
distribution information the hg tag is nss_3_28_3_rtm. nss 3.28.3 requires netscape portable runtime (nspr) 4.13.1 or newer. nss 3.28.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_28_3_rtm/src/ new in nss 3.28.3 new functionality no new functionality is introduced in this release. this is a patch release to fix binary compatibility issues. ...
...rsion 3.28, 3.28.1 and 3.28.2 contained changes that were in violation with the nss compatibility promise. ecparams, which is part of the public api of the freebl/softokn parts of nss, had been changed to include an additional attribute. that size increase caused crashes or malfunctioning with applications that use that data structure directly, or indirectly through ecpublickey, ecprivatekey, nsslowkeypublickey, nsslowkeyprivatekey, or potentially other data structures that reference ecparams. the change has been reverted to the original state in bug 1334108. seckeyecpublickey had been extended with a new attribute, named "encoding". if an application passed type seckeyecpublickey to nss (as part of seckeypublickey), the nss library read the uninitialized attribute. with this nss release se...
NSS 3.29.1 release notes
distribution information the hg tag is nss_3_29_1_rtm. nss 3.29.1 requires netscape portable runtime (nspr) 4.13.1 or newer. nss 3.29.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_29_1_rtm/src/ new in nss 3.29.1 new functionality no new functionality is introduced in this release. this is a patch release to fix binary compatibility issues. ...
...3.28, 3.28.1, 3.28.2 and 3.29 contained changes that were in violation with the nss compatibility promise. ecparams, which is part of the public api of the freebl/softokn parts of nss, had been changed to include an additional attribute. that size increase caused crashes or malfunctioning with applications that use that data structure directly, or indirectly through ecpublickey, ecprivatekey, nsslowkeypublickey, nsslowkeyprivatekey, or potentially other data structures that reference ecparams. the change has been reverted to the original state in bug 1334108. seckeyecpublickey had been extended with a new attribute, named "encoding". if an application passed type seckeyecpublickey to nss (as part of seckeypublickey), the nss library read the uninitialized attribute. with this nss release se...
NSS 3.31 release notes
eleased nss 3.31, which is a minor release. 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. new functions in cert.h cert_getcertisperm - retrieve the permanent storage status attribute of a certificate in a thread safe way. cert_getcertistemp - retrieve the temporary storage status attribute of a certificate in a th...
... tls version range have been changed to trim the requested range to the overlap with a systemwide crypto policy, if configured. ssl_versionrangegetsupported can be used to query the overlap between the library's supported range of tls versions and the systemwide policy. previously, ssl_versionrangeset and ssl_versionrangesetdefault returned a failure if the requested version range wasn't fully allowed by the systemwide crypto policy. they have been changed to return success, if at least one tls version overlaps between the requested range and the systemwide policy. an application may call ssl_versionrangeget and ssl_versionrangegetdefault to query the tls version range that was effectively activated. corrected the encoding of domain name constraints extensions created by certutil nss suppo...
NSS 3.32 release notes
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_32_rtm/src/ notable changes in nss 3.32 various minor improvements and correctness fixes. the code signing trust bit was turned off for all, included root certificates. ...
...was turned off for the following root certificates. ...
NSS 3.34 release notes
released nss 3.34, which is a minor release. distribution information the hg tag is nss_3_34_rtm. nss 3.34 requires netscape portable runtime (nspr) 4.17, or newer. ...
...z o.o. sha-256 fingerprint: d8:e0:fe:bc:1d:b2:e3:8d:00:94:0f:37:d2:7d:41:34:4d:99:3e:73:4b:99:d5:65:6d:97:78:d4:d8:14:36:24 cn = startcom certification authority sha-256 fingerprint: c7:66:a9:be:f2:d4:07:1c:86:3a:31:aa:49:20:e8:13:b2:d1:98:60:8c:b7:b7:cf:e2:11:43:b8:36:df:09:ea cn = st...
NSS 3.37 release notes
rity/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. added hacl* poly1305 32-bit the code to support the npn protocol, which had already been disabled in a previous release, has been fully removed. nss allows servers now to register alpn handling callbacks to select a protocol. nss supports opening sql databases in read-only mode. nss now requires the sqlite apis of version 3.5.0 or newer. starting with nss version 3.31, an alternative implementation for rng seeding on the linux/unix platform was available (bug 1346735), which performed seeding exclusively based on /dev/urandom. this alte...
...tion for linux/unix can be selected in "make" builds by defining the environment variable nss_seed_only_dev_urandom. with nss 3.37, this alternative implementation for linux has been enhanced to use the glibc function getentropy(), instead of reading from /dev/urandom directly, if the build and runtime linux platform supports it. the ca certificates list was updated to version 2.24. ...
NSS 3.42 release notes
er. 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. ...
...lla.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. new in nss 3.42 new functionality bug 818686 - support xdg basedir specification new functions none notable changes in nss 3.42 the following ca certificates were added: none the following ca certificates were removed: none added support for some of the testcases from the wycheproof project: bug 1508666 - added aes-gcm test cases bug 1508673 - added chacha20-poly1305 test cases bug 1514999 - added the curve25519 test cases thanks to jonas allmann for adapting these tests. bugs fixed in ns...
NSS 3.44 release notes
nss test certificates, use @example.com (not @bogus.com) 1538479 - post-handshake messages after async server authentication break when using record layer separation 1521578 - x25519 support in pk11pars.c 1540205 - freebl build fails with -dnss_disable_chachapoly 1532312 - post-handshake auth doesn't interoperate with openssl 1542741 - certutil -f crashes with segmentation fault 1546925 - allow preceding text in try comment 1534468 - expose chacha20 primitive 1418944 - quote cc/cxx variables passed to nspr 1543545 - allow to build nss as a static library 1487597 - early data that arrives before the handshake completes can be read afterwards 1548398 - freebl_gtest not building on linux/mac 1548722 - fix some coverity warnings 1540652 - softoken/sdb.c: logically dead code 1549413 ...
...1487597 - early data that arrives before the handshake completes can be read afterwards 1548398 - freebl_gtest not building on linux/mac 1548722 - fix some coverity warnings 1540652 - softoken/sdb.c: logically dead code 1549413 - android log lib is not included in build 1537927 - ipsec usage is too restrictive for existing deployments 1549608 - signature fails with dbm disabled 1549848 - allow building nss for ios using gyp 1549847 - nss's sqlite compilation warnings make the build fail on ios 1550041 - freebl not building on ios simulator 1542950 - macos cipher test timeouts this bugzilla query returns all the bugs fixed in nss 3.44: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.44 compat...
NSS 3.45 release notes
adds new experimental functions: ssl_settimefunc, ssl_createantireplaycontext, ssl_setantireplaycontext, and ssl_releaseantireplaycontext. the experimental function ssl_initantireplay is removed. bug 1546477 - various changes in response to the ongoing fips review note: the source package size has increased substantially due to the new fips test vectors. ...
... ssl_releaseantireplaycontext. the experimental function ssl_initantireplay is removed. bug 1546477 - various changes in response to the ongoing fips review note: the source package size has increased substantially due to the new fips test vectors. this will likely prompt follow-on work, but please accept our apologies in the meantime. ...
NSS 3.52 release notes
9663 - add ikev1 quick mode kdf. bug 1629661 - mpconfig calls in ssl initialize policy before nss is initialized. bug 1629655 - support temporary session objects in ckfw. bug 1629105 - add pkcs11 v3.0 functions to module debug logger. bug 1626751 - fix error in generation of fuzz32 docker image after updates. bug 1625133 - fix implicit declaration of function 'getopt' error. bug 1624864 - allow building of gcm-arm32-neon on non-armv7 architectures. bug 1624402 - fix compilation error in firefox android. bug 1624130 - require ck_function_list structs to be packed. bug 1624377 - fix clang warning for unknown argument '-msse4'. bug 1623374 - support new pkcs #11 v3.0 message interface for aes-gcm and chachapoly. bug 1623184 - fix freebl_cpuid for querying extended features. bug 16225...
...n non-armv7 architectures. bug 1624402 - fix compilation error in firefox android. bug 1624130 - require ck_function_list structs to be packed. bug 1624377 - fix clang warning for unknown argument '-msse4'. bug 1623374 - support new pkcs #11 v3.0 message interface for aes-gcm and chachapoly. bug 1623184 - fix freebl_cpuid for querying extended features. bug 1622555 - fix argument parsing in lowhashtest. bug 1620799 - introduce nss_disable_gcm_arm32_neon to build on arm32 without neon support. bug 1619102 - add workaround option to include both dtls and tls versions in dtls supported_versions. bug 1619056 - update readme: tls 1.3 is not experimental anymore. bug 1618915 - fix ubsan issue in ssl_parsesessionticket. bug 1618739 - don't assert fuzzer behavior in ssl_parsesessionticket.
NSS 3.54 release notes
p.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). ...
...47905950641f26421b15ed089198b518ae2ea1b99 bug 1641716 - microsoft ecc root certificate authority 2017 sha-256 fingerprint: 358df39d764af9e1b766e9c972df352ee15cfac227af6ad1d70e8e4a6edcba02 bug 1641716 - microsoft rsa root certificate authority 2017 sha-256 fingerprint: c741f70f4b2a8d88bf2e71c14122ef53ef10eba0cfa5e64cfa20f418853073e0 the following ca certificates were removed: bug 1645199 - addtrust class 1 ca root sha-256 fingerprint: 8c7209279ac04e275e16d07fd3b775e80154b5968046e31f52dd25766324e9a7 bug 1645199 - addtrust external ca root sha-256 fingerprint: 687fa451382278fff0c8b11f8d43d576671c6eb2bceab413fb83d965d06d2ff2 bug 1641718 - luxtrust global root 2 sha-25...
nss tech note6
o operate in fips 140 mode. the new checksum file is called libsoftokn3.chk on unix/linux and softokn3.chk on windows. it must be put in the same directory as the nss libraries. the libsoftokn3.chk/softokn3.chk file contains a checksum for the softoken. when in fips 140 mode, the softoken is required to compute its checksum and compare it with the value in libsoftokn3.chk/softokn3.chk. the following applies to nss 3.8 through 3.10 : on 32-bit solaris sparc (i.e., not x86, and not 64-bit sparc) and 32-bit hp-ux pa-risc (i.e., not itanium, and not 64-bit pa-risc), there are two more .chk files: libfreebl_pure32_3.chk and libfreebl_hybrid_3.chk. the following applies to nss 3.11 : the low-level freebl cryptographic code has been separated from softoken on all platforms. even on platforms f...
...eet this requirement is for your application never to modify the nss binaries. any offer of binary support that may have been previously made to you by nss developers is null and void. if your build process modifies nss libraries in any way (for example, to strip the symbols), it should consider not doing so for the reasons cited above. if you still decide to make unsupported changes, you can allow the softoken to come up in fips 140 mode of operation by regenerating the .chk files yourself. the tool to do that is called shlibsign. it is released as part of the nss binary distributions. if your build process does not modify nss shared libraries, you can just use the .chk files in the nss binary distributions. so you have two options. 1. do not modify nss libraries in your build proce...
nss tech note8
ids. a sid (or sslsessionid struct) contains all the info needed to restart the ssl session at a later time on another socket. the protocol code builds such a structure, and then asks the cache code (client or server) to save the info. the protocol code can also ask to remove a sid from the cache. every ssl socket has two function pointers, ss->sec.cache and ss->sec.uncache, which have the following types: typedef void (*sslsessionidcachefunc) (sslsessionid *sid); typedef void (*sslsessioniduncachefunc)(sslsessionid *sid); there are two separate implementations of each function, one for clients and one for servers. the client implementation caches or uncaches the sid in the client session cache. the server implementation caches or uncaches the sid in the server session cache. for ser...
...he callers relied on the ability of the respective cache functions to be able to compute the expiration time. all callers computed the expiration times explicitly, as shown above. the server side of the session cache code was largely rewritten for nss 3.4. the objectives were to make the server session cache faster, and to fix bugs that caused corruption in multi-process servers, and also to allow separate virtual servers to have their own session caches. the new approach was to use shared memory for the server session cache, and to allow multiple different server session caches to coexist. as part of that work, i decided that each cache would have its own variables containing the ssl2 and ssl3 session durations. this means that client cache session lifetimes are separate from server sess...
Migration to HG
, especially the instructions about setting environment variables. updated instructions for building nss with nspr can be found at: /docs/nss_reference/building_and_installing_nss/build_instructions it's best to refer to the above document to learn about the various environment variables that you might have to set to build on your platform (this part hasn't changed). ...
... because of the changes described above, we have decided to use a new series of (minor) version numbers. the first releases using the new code layout will be nspr 4.10 and nss 3.15 ...
FC_InitToken
name fc_inittoken() - initialize or re-initialize a token. syntax ck_rv fc_inittoken( ck_slot_id slotid, ck_char_ptr ppin, ck_ulong ulpinlen, ck_char_ptr plabel ); parameters fc_inittoken() has the following parameters: slotid the id of the token's slot ppin the password of the security officer (so) ulpinlen the length in bytes of the so password plabel points to the label of the token, which must be padded with spaces to 32 bytes and not be null-terminated description fc_inittoken() initializes a brand new token or re-initializes a token that was initialized before. 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 certifi...
...ves 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 be able to call fc_inittoken() without logging into the token (to assume the nss user role) because either the user's password hasn't been set yet or the user forgets the password and needs to blow away the password-encrypted private key database and start over. note: the so password should be the empty string, i.e., ulpinlen argument should be 0. fc_inittoken() ignores the plabel argument. return value fc_inittoken() returns the following return codes. ckr_ok: token initialization succeeded. ckr_slot_id_invalid: slot id is invalid. ckr_token_write_protected we don't have a refer...
FC_Initialize
arameters pinitargs points to a ck_c_initialize_args structure. description fc_initialize initializes the nss cryptographic module for the fips mode of operation. in addition to creating the internal data structures, it performs the fips software integrity test and power-up self-tests. the pinitargs argument must point to a ck_c_initialize_args structure whose members should have the following values: createmutex should be null. destroymutex should be null. lockmutex should be null. unlockmutex should be null. flags should be ckf_os_locking_ok. libraryparameters should point to a string that contains the library parameters. preserved should be null. the library parameters string has this format: "configdir='dir' certprefix='prefix1' keyprefix='prefix2' secmod='file' flags= ...
...ion='software security device' cryptoslotdescription='psm internal cryptographic services' dbslotdescription='psm private keys' fipsslotdescription='psm internal fips-140-1 cryptographic services' fipstokendescription='psm fips-140-1 user private key services' minps=0" see pkcs #11 module specs for complete documentation of the library parameters string. 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 flag is not set in pinitargs->flags. the nss cryptographic module always uses os locking and doesn't know how to use the lock functions provi...
NSC_InitToken
name nsc_inittoken() - initialize or re-initialize a token. syntax ck_rv nsc_inittoken( ck_slot_id slotid, ck_char_ptr ppin, ck_ulong ulpinlen, ck_char_ptr plabel ); parameters nsc_inittoken() has the following parameters: slotid the id of the token's slot ppin the password of the security officer (so) ulpinlen the length in bytes of the so password plabel points to the label of the token, which must be padded with spaces to 32 bytes and not be null-terminated description nsc_inittoken() initializes a brand new token or re-initializes a token that was initialized before. 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 ce...
...s 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 so password should be the empty string, i.e., ulpinlen argument should be 0. nsc_inittoken() ignores the plabel argument. return value nsc_inittoken() returns the following return codes. ckr_ok: token initialization succeeded. ckr_slot_id_invalid: slot id is invalid. ckr_token_write_protected slot id is 1. (the non-fips mode has two slots: 1 and 2. the key database is in slot 2. slot 1 doesn't have a key database.) we don't have a reference to the key database (we failed to open the key database or we have released our reference). ckr_device_error: failed...
NSS_Initialize
ecmodname [in] name of the security module database, usually "secmod.db". flags [in] bit flags that specify how nss should be initialized. description nss_initialize initializes nss. it is more flexible than nss_init, nss_initreadwrite, and nss_nodb_init. if any of those simpler nss initialization functions suffices for your needs, call that instead. the flags parameter is a bitwise or of the following flags: nss_init_readonly - open the databases read only. nss_init_nocertdb - don't open the cert db and key db's, just initialize the volatile certdb. nss_init_nomoddb - don't open the security module db, just initialize the pkcs #11 module. nss_init_forceopen - continue to force initializations even if the databases cannot be opened. nss_init_norootinit - don't try to look for the root cert...
...at nss is accessing without going through nss, for example, java sunpkcs11 provider. nss_init_nopk11finalize - never call c_finalize on any pkcs#11 module. this may be necessary in order to ensure continuous operation and proper shutdown sequence if another piece of code is using the same pkcs#11 modules that nss is accessing without going through nss, for example, java sunpkcs11 provider. the following limitation applies when this is set : secmod_waitforanytokenevent will not use c_waitforslotevent, in order to prevent the need for c_finalize. this call will be emulated instead. nss_init_reserved - currently has no effect, but may be used in the future to trigger better cooperation between pkcs#11 modules used by both nss and the java sunpkcs11 provider. this should occur after a new flag is...
NSS Key Functions
ckeykeydbhandle. description nss_init opens the certificate, key, and security module databases that you specify for use with nss. seckeykeydbhandle returns a handle to the key database opened by nss_init. seckey_destroyprivatekey destroys a private key structure. syntax include <key.h> include <keyt.h> void seckey_destroyprivatekey(seckeyprivatekey *key); parameter this function has the following parameter: key a pointer to the private key structure to destroy. description certificate and key structures are shared objects. when an application makes a copy of a particular certificate or key structure that already exists in memory, ssl makes a shallow copy--that is, it increments the reference count for that object rather than making a whole new copy. when you call cert_destroycertifica...
... ...
NSS tools : cmsutil
ographic message syntax (cms) messages. synopsis cmsutil [options] arguments description the cmsutil command-line uses the s/mime toolkit to perform basic operations, such as encryption and decryption, on cryptographic message syntax (cms) messages. to run cmsutil, type the command cmsutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section. each command takes one option. each option may take zero or more arguments. to see a usage string, issue the command without options. options and arguments options options specify an action. option arguments modify an action. the options and arguments for the cmsutil command are defined as follows: -d decode a message. -c encrypt a message. -e envelope a message. -o create a certifica...
...-c content use this detached content (decode only). ...
NSS reference
should a particular page require the use of an underscore, please see the documentation for the title override extension. ...
... these functions are listed in this section. error codes based on "nss and ssl error codes" in the ssl reference. nss environment variables nss cryptographic module nss tech notes nss tech notes nss memory allocation tools based o...
NSS Tools certutil-tasks
improve coherence of key and certificate nicknames. ...
... improve coherence of key and certificate nicknames. ...
NSS tools : cmsutil
Mozilla › Projects › NSS › tools › cmsutil
ms) messages. synopsis cmsutil [options] arguments description the cmsutil command-line uses the s/mime toolkit to perform basic operations, such as encryption and decryption, on cryptographic message syntax (cms) messages. to run cmsutil, type the command cmsutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section. each command takes one option. each option may take zero or more arguments. to see a usage string, issue the command without options. options and arguments options options specify an action. option arguments modify an action. the options and arguments for the cmsutil command are defined as follows: -d decode a message. -c encrypt a mes...
... -c content use this detached content (decode only). ...
NSS tools : signver
Mozilla › Projects › NSS › tools › signver
originally used berkeleydb databases to store security information. the last versions of these legacy databases are: o cert8.db for certificates o key3.db for keys o secmod.db for pkcs #11 module information berkeleydb has performance limitations, though, which prevent it from being easily used by multiple applications simultaneously. nss has some flexibility that allows applications to use their own, independent database engine while keeping a shared database and working around the access issues. still, nss requires more flexibility to provide a truly shared security database. in 2009, nss introduced a new set of databases that are sqlite databases rather than berkleydb. these new databases provide more accessibility and performance: o ...
...f the pkcs #11 modules contained in a new subdirectory in the security databases directory because the sqlite databases are designed to be shared, these are the shared database type. the shared database type is preferred; the legacy format is included for backward compatibility. by default, the tools (certutil, pk12util, modutil) assume that the given security databases follow the more common legacy type. using the sqlite databases must be manually specified by using the sql: prefix with the given security directory. for example: # signver -a -s signature -d sql:/home/my/sharednssdb to set the shared database type as the default type for the tools, set the nss_default_db_type environment variable to sql: export nss_default_db_type="sql" this line c...
Pork Tools
utparamdel converts functions to return via return value instead of an outparam. it takes a list of functions as input and rewrites the definition and call sites of those functions. <caption>rewrites performed</caption> nsresult getter(nsifoo **aresult) { *aresult = ... if (!*aresult) return ns_error_failure; return ns_ok; } nsifoo* getter() { nsifoo *result = null; // aresult below is kept for complicated cases // typically it wont be needed and can be removed nsifoo **aresult = &result; // *aresult patterns are replaced with result result = ... if (result) return nsnull; // error returns are changed to nsnull //instead ns_ok, actual result is returned return result; } caller1 { //case 1 nsresult rv; rv = getter(&var); ns_ensure_success(rv,rv...
...re_success(rv,rv); //case 2: naked call getter(&var); //case 3: nsresult decl nsresult rv2 = getter(&var); ns_ensure_success(rv2,rv2); } 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 mod...
Rhino Examples
the liveconnect.js script shows a sample usage of liveconnect (java-to-javascript connectivity). the jsdoc.js script is a javascript analog to java's javadoc. it makes heavy use of regular expressions. ...
... typing interactively while the shell is running. primitivewrapfactory primitivewrapfactory.java is an example of a wrapfactory 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.
Small Footprint
sponding to 1,171,708 bytes of all uncompressed rhino classes with debug information included. with various changes js.jar size can be reduced to 204,689 bytes corresponding to 424,774 bytes of uncompressed classes. tools most embeddings won't need any of the classes in org.mozilla.javascript.tools or any of its sub-packages. optimizer it is possible to run rhino with interpreter mode only, allowing you to remove code for classfile generation that include all the classes from <tt>org.mozilla.javascript.optimizer</tt> package. javaadapter implementing the javaadapter functionality requires the ability to generate classes on the fly. removing org.mozilla.javascript.javaadapter will disable this functionality, but rhino will otherwise run correctly. class generation library if you do not...
...ut 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 license
rhino is available under open source licenses. mpl/gpl license the majority of the source code for rhino is available under a mpl 1.1/gpl 2.0 license. license for portions of the rhino debugger additionally, some files (currently the contents of toolsrc/org/mozilla/javascript/tools/debugger/treetable/) are available under the following license: * copyright 1997, 1998 sun microsystems, inc. all rights reserved. * * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - redistributions in binary form must reproduce the above copyright * notice...
...d use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - neither the name of sun microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * this software is provided by the copyright holders and contributors "as * is" and any e...
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. ...
...the constructor call to new array(n). a constructor call like that indicates to the runtime that a javascript array should be used for the first n entries of the array. similarly, new array("a", "b", "c") or ["a", "b", "c"] will cause a 3-element array to be allocated to hold the contents of the javascript array. eval and new function avoid calling eval when possible. calls to eval are slow because the script being executed must be compiled. constructing a new function object can be slow for the same reason, while function expressions are more efficient because the function can be compiled. for example, the code function myobject(a) { this.s = a; this.tostring = new function("return this.s"); } could be written more efficiently as function myobject(a) { this.s = a; ...
Rhino shell
runcommand(command) runcommand(command, arg1, ..., argn) runcommand(command, arg1, ..., argn, options) all except the last arguments to runcommand are converted to strings and denote command name and its arguments. if the last argument is a javascript object, it is an option object. otherwise it is converted to string denoting the last argument and options objects assumed to be empty. the following properties of the option object are processed: args - provides an array of additional command arguments env - explicit environment object. all its enumeratable properties define the corresponding environment variable names. input - the process input. if it is not java.io.inputstream, it is converted to string and sent to the process as its input. if not specified, no input is provided to ...
...ts to the script itself. $ java org.mozilla.javascript.tools.shell.main -e "print('hi')" hi $ java org.mozilla.javascript.tools.shell.main js> print('hi') hi js> 6*7 42 js> function f() { return a; } js> var a = 34; js> f() 34 js> quit() $ cat echo.js for (i in arguments) { print(arguments[i]) } $ java org.mozilla.javascript.tools.shell.main echo.js foo bar foo bar $ spawn and sync the following example creates 2 threads via spawn and uses sync to create a synchronized version of the function test. js> function test(x) { print("entry"); java.lang.thread.sleep(x*1000); print("exit"); } js> var o = { f : sync(test) }; js> spawn(function() {o.f(5);}); thread[thread-0,5,main] entry js> spawn(function() {o.f(5);}); thread[thread-1,5,main] js> exit entry exit runcommand here are a...
SpiderMonkey compartments
with arbitrary other javascript objects from other origins. such cross-origin objects are used together very infrequently, which reduces the number of cache hits we get. in the new model most objects touched by a website are tightly packed next to each other in memory, with no cross-origin objects in between. javascript objects (including javascript functions, which are objects also) are only allowed to touch objects in the same compartment. this invariant is very useful for security purposes. the javascript engine enforces this requirement at a very low level. it means that a "google.com" object can never accidentally leak into an untrusted website such as "evil.com". only a special object type can cross the compartment boundaries. we call these objects cross-compartment wrappers. spidermo...
... never accidentally leak into an untrusted website such as "evil.com". only a special object type can cross the compartment boundaries. we call these objects cross-compartment wrappers. spidermonkey tracks the creation of these cross-compartment wrappers and thus it knows at all times what objects from a compartment are kept alive by outside references (through cross-compartment wrappers). this allows the garbage collecting of individual compartments, in addition to global collection. spidermonkey simply assumes that all objects referenced from outside the compartment are live, and then walks the object graph inside the compartment. objects that are found to be disconnected from the graph are discarded. with this new per-compartment garbage collection we shortcut having to walk unrelated heap...
Creating JavaScript tests
.js before they run, which creates a ton of functions. read more advice on jstests here. jit-test new jit-test files should be put in js/src/jit-test/tests/basic or one of the other appropriate subdirectories of jit-test/tests. jit-tests run only in the shell. jit-tests do not load extra test functionality automatically. writing a new test file have a look at the existing files and follow what they do. all tests, in both suite, can use the asserteq function. asserteq(v1, 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 atte...
...ardware 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 will also show up as infrequent oranges on our heavily loaded test machines, lowering the value of our test suite for everyone. just don't do it, it's never worth it. do not add performance tests to the test suite. it is not generally even possible to tell if the speed of any particular feature is going to be important in the real world without running a real-world benchmark. it is very hard to write a good real-world benchmark. for this reason, the best place to find out i...
Statistics API
ontent.level = 0, otherwise the content process will crash. the browser preference javascript.options.mem.log controls dumping of human-readable gc stats messages to the developer console. the browser preference javascript.options.mem.notify controls emission of json encoded gc stats to an observer interface. json api addons can obtain the complete data in json format via an observer. the following adds an observer using the jetpack framework. var prefs = require("api-utils/preferences-service"); components.utils.import('resource://gre/modules/services.jsm'); function observer(subject, topic, json) { var data = json.parse(json); // process the data } prefs.set("javascript.options.mem.notify", true); services.obs.addobserver(observer, "garbage-collection-statistics", false); t...
...compartments phases and so on. the times object gives how much time was spent in each phase of the gc, in milliseconds. additionally, an incremental gc is divided into a series of slices (the division into slices is completely separate from the division into phases; neither one is a refinment of the other). a little bit of gc work is done in each slice. in between slices, other browser code is allowed to run. the slices array describes how long each slice took and what work was done during the slice. each element of the slices array is an object with these fields: slice: integer - the slice index, starting at 0. pause: number (milliseconds) - the slice duration. when: number (milliseconds) - the time this slice started, relative to the first slice's start time. reason: string - a strin...
SpiderMonkey Internals: Thread Safety
time data structures are serialized with a few mutexes. the treatment of gc requires more explanation. making gc thread-safe with js_threadsafe, the api changes slightly. the program must group jsapi calls into "requests": js_setcontextthread(cx); js_beginrequest(cx); /* ... do stuff ... */ js_endrequest(cx); js_clearcontextthread(cx); it isn't a bottleneck; multiple threads are allowed to be in requests on the same jsruntime at once. see js_beginrequest. the most obvious effect of a request is: at any given moment there can either be multiple threads in active requests, or one thread doing gc and all requests suspended. a call to js_gc() will block until the latter becomes possible. in other words, gc waits until each other thread is either outside jsapi (in which case we don...
...e we don't care what it's doing) or else in jsapi, but blocked, waiting for gc to finish. threads must not do anything that would affect gc while outside a request. and obviously you shouldn't block or otherwise dilly-dally while in a request; it prohibits gc. as an optimization, each thread has its own size-classified freelists containing chunks of gc-managed memory ready to be allocated. this allows allocation to avoid locking most of the time (a significant speed win). a thread needs to lock on allocation only when the relevant per-thread freelist is empty. when this happens, the thread also refills that freelist from the jsruntime-wide gc allocator while it's in the lock. ...
Self-hosted builtins in SpiderMonkey
self-hosted code is strict, so self-hosted functions invoked in a null or undefined scope won't be run in the scope of the global object. self-hosted code has access to some functionality that's not available to normal js code. most importantly, it's possible to invoke any function within the scope of any object using the syntax callfunction(fun, receiver, ...args) (or callcontentfunction, see below), which causes fun to be called within the scope of receiver with ...args as its arguments. in contrast to function.prototype.call, this syntax makes it impossible for other code to interfere and gets compiled to bytecode that doesn't have any overhead compared to a normal function invocation. otoh, normal method calls are forbidden in self-hosted code. so instead of receiver.fun(arg1, ..., argn...
...ted functions have direct access to each other and can rely on references being stable, i.e. not changeable by client js code. otoh, self-hosted code doesn't have access to most of the c++-implemented builtins. you can not, for example, use function.prototype.apply directly. a select set of c++-implemented builtins is installed via the intrinsic_functions array in selfhosting.cpp, as described below. using the same mechanism, c++-implemented helper functions are made available to self-hosted code. some general-purpose functions provided in this way are: the abstract operations toobject, tointeger, and iscallable specified in the ecmascript language specification. throwtypeerror, throwrangeerror, throwsyntaxerror, which self-hosted code should use instead of throw so that the error messag...
JIT Optimization Outcomes
for fast program execution are property accesses and function calls. this page documents the meaning of different optimization outcomes. general outcomes general outcomes shared between various optimization strategies. genericfailure the optimization attempt failed, and the reason was not recorded. genericsuccess optimization succeeded. disabled the optimization has been explicitly disallowed. notypeinfo optimization failed because there was no type information associated with an object containing the property. this failure mode is unlikely and occurs if the target object is obtained in some roundabout way. noanalysisinfo todo noshapeinfo the baseline compiler recorded no usable shape information for this operation. unknownobject the type of the object is not known. this can...
...cts which are used in this operation. protoindexedprops the object being accessed has indexed properties that are exotic (for example, defined as a property on a prototype object and left as a hole in the underlying object). arraybadflags the array being accessed may have flags that the optimization strategy cannot handle. for example, if the array has sparse indexes, or has indexes that overflow the array's length, the optimization strategy may fail. arraydoubleconversion the type-system indicates that some arrays at this site should be converted to packed arrays of doubles while others should not. the optimization strategy fails for this condition. arrayrange could not accurately calculate the range attributes of an inline array creation. arrayseennegativeindex arrays at this elem...
INT_FITS_IN_JSVAL
e 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 c/c++ compiler does not enforce type safety here. if i is an unsigned or 64-bit value, int_fi...
...till convert i to a jsval using js_newnumbervalue. warning: the type of the argument i must be jsint, but the c/c++ compiler does not enforce type safety here. if i is an unsigned or 64-bit value, int_fits_in_jsval can silently give the wrong answer. starting in spidermonkey 1.8.5, jsval can store a full 32-bit integer, so this check isn't needed any longer for 32-bit integers. example the following code snippet illustrates how a c variable, item, is conditionally tested in an if statement to see if it is a legal jsval integer value. if (int_fits_in_jsval(item)) { /* ... */ } else { js_reporterror(cx, "integer out of range: %d", item); } see also int_to_jsval changeset - 52750:05bd86e3559a ...
JS::PersistentRooted
on. these roots can be used in heap-allocated data structures, so they are not associated with any particular jscontext or stack. they are registered with the jsruntime itself, without locking, so they require a full jscontext to be initialized, not one of its more restricted superclasses. initialization may take place on construction, or in two phases if the no-argument constructor is called followed by init(). note that you must not use an persistentrooted in an object owned by a js object: whenever one object whose lifetime is decided by the gc refers to another such object, that edge must be traced only if the owning js object is traced. this applies not only to js objects (which obviously are managed by the gc) but also to c++ objects owned by js objects. if you put a persistentroote...
... // to use maybe. #include <mozilla/maybe.h> // declare global variable. // [spidermonkey 31] js::persistentrootedvalue itself cannot be a global variable. mozilla::maybe<js::persistentrootedvalue> persistentval; // you can also declare it just as a pointer, instead of using maybe. ...
JS::Value
semantics (ignoring performance). the number mutators attempt to use int32_t representation for compatible input values, returning true when int32 could be used and false when double representation was required. any double value may be stored in a js::value, in one of these two representations. the only exception is that only a single nan value can be represented. (note that both -0 and +0 are allowed, and the latter may sometimes be stored using the int32_t representation.) js::value further provides these methods combining various aspects of the above methods: js::objectornullvalue(jsobject*) returns an object value corresponding to the given non-null pointer, or a null value if the pointer is null. val.setobjectornull(jsobject *) sets the given value to the specified object, or to nu...
... issues to be aware of when using js::value. js::value is not inherently type-safe it is an error to call any accessor method on a value of a non-matching type: val.toint32() must only be called if val.isint32(), val.tostring() must only be called if val.isstring(), and so on. in particular, note that it is an error to call val.toobject() when val.isnull(). the now-deprecated jsval methods allowed jsval_to_object(val) when jsval_is_null(val), but this was a source of constant bugs. val.toobject() is only permitted when val.isobject(). an assertion is thrown in the case that the type is not correct (val.isx() is called for each val.tox(), where x is the type). it is highly recommended that you develop and test with an --enable-debug build to detect most js::value misuse. debug builds wil...
JSClass.flags
if this flag is set, each instance of the class has a field for private data. the field can be accessed using js_getprivate and js_setprivate. mxr id search for jsclass_has_private jsclass_private_is_nsisupports mozilla extension. the private field of each object of this class points to an xpcom object (see nsisupports). ...
...e_is_nsisupports jsclass_is_domjsclass added in spidermonkey 17 objects are dom. mxr id search for jsclass_is_domjsclass jsclass_emulates_undefined added in spidermonkey 24 causes objects which have this class to emulate undefined in certain circumstances. ...
JSDeletePropertyOp
and returns true, then property delete is unaffected. it proceeds as normal. this callback may veto the ongoing property operation by optionally reporting an error or raising an exception and then returning false. the operation then fails, and the error is propagated to the caller. otherwise the callback must return true, and the property operation proceeds. jsclass hooks jsclass offers the following hook: jsclass.delproperty is called during most property deletions, even when obj has no property named id. if an error occurred, return false as per normal jsapi error practice. if no error occurred, but the deletion attempt wasn't allowed (perhaps because the property was non-configurable), set *succeeded to false and return true. this will cause delete obj[id] to evaluate to fal...
...error occurred, return false as per normal jsapi error practice. if no error occurred, but the deletion attempt wasn't allowed (perhaps because the property was non-configurable), set *succeeded to false and return true. this will cause delete obj[id] to evaluate to false in non-strict mode code, and to throw a typeerror in strict mode code. if no error occurred and the deletion wasn't disallowed (this is *not* the same as saying that a deletion actually occurred -- deleting a non-existent property, or an inherited property, is allowed -- it's just pointless), set *succeeded to true and return true. this hook is not called when the target property is jsprop_permanent and is an own property of the target object. an attempt to delete such a property fails early, returning false, before...
JSErrorReport
filename const char * indicates the source file or url that produced the error condition. if null, the error is local to the script in the current html page. lineno unsigned line number in the source that caused the error. column unsigned zero-based column index in line in the source that caused the error. ismuted bool 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 that script errors should be sanitized ("muted") whe...
...e 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: jsreport_warning this "error" is really only a warning. it will not cause the current operation to fail. jsreport_exception an exception is being raised. a jserrorreporter might choose to ignore a jserrorreport that has this flag set, since the exception may be caught and handled by javascript code. jsreport_strict ...
JSGetObjectOps
given class. all native objects have a jsclass, which is stored as a private (int-tagged) pointer in object slots. in contrast, all native and host objects have a jsobjectmap at obj->map, which may be shared among a number of objects, and which contains the jsobjectops *ops pointer used to dispatch object operations from api calls. thus jsclass (which pre-dates jsobjectops in the api) provides a low-level interface to class-specific code and data, while jsobjectops allows for a higher level of operation, which does not use the object's class except to find the class's jsobjectops struct, by calling clasp->getobjectops, and to finalize the object. if this seems backwards, that's because it is! api compatibility requires a jsclass *clasp parameter to js_newobject, etc. most host objects do not...
...js_newobject, etc. most host objects do not need to implement the larger jsobjectops, and can share the common jsscope code and data used by the native (js_objectops, see jsobj.c) ops. further extension to preserve api compatibility: if this function returns a pointer to jsxmlobjectops.base, not to jsobjectops, then the engine calls extended hooks needed for e4x. jsclass hooks jsclass offerd following hook: the jsclass.getobjectops hook is called each time an object is created. it returns a pointer to a jsobjectops which is then used as a virtual table for operations on the new object. see also mxr id search for jshasinstanceop jsclass js_hasinstance bug 571789 ...
JSNative
call js_beginrequest()). argc unsigned the number of arguments supplied to the function by the caller (as opposed to, say, the number of arguments the function is specified to take in its jsfunctionspec). vp js::value * the arguments, the this argument, the return-value slot, and the callee function object are accessible through this pointer using macros described below. description jsnative is the type of native implementations of javascript functions. full documentation of how to define a jsnative (or a jsfastnative, the equivalent typedef which preceded it) is available in the api header "js/callargs.h" added in spidermonkey 24. this header is new, but the semantics it describes are applicable to all recent spidermonkey releases. the preferred way ...
...l (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_frameiterator and js_stackframeprincipals, must take extra care, as the native function's principals will be missing from...
JSObjectOps.getProperty
or details. jsobjectops.getproperty, setproperty, and deleteproperty are high-level callbacks that implement object property accesses. each of these callbacks is responsible for everything involved with an individual property access operation, including: any locking necessary for thread safety; security checks; finding the property, including walking the prototype chain if needed; calling the lower-level jsclass hooks; calling getters or setters; and actually getting, setting, or deleting the property once it is found. contrast jsclass.getproperty, jsclass.setproperty, and jsclass.delproperty, which are hooks called during property accesses and don't have to implement any of that. syntax typedef jsbool (*jspropertyidop)( jscontext *cx, jsobject *obj, jsid id, jsval *vp); ...
...yidop)( jscontext *cx, jsobject *obj, jsid id, jsval *vp); name type description cx jscontext * pointer to the js context in which the property access is happening. obj jsobject * the object to be accessed. id jsid the name or index of the property to access. vp jsval * in/out parameter. see the description section below. description get, set, or delete obj[id], returning js_false on error or exception, js_true on success. if getting or setting, the new value is returned in *vp on success. if deleting without error, *vp will be jsval_false if obj[id] is permanent, and jsval_true if id named a direct property of obj that was in fact deleted, or if id names no direct property of obj (id could name a proper...
JSPropertyOp
dex of the property being accessed. this is either a string (unicode property identifier) or an integer (element index). strict bool (jsstrictpropertyop only) if strict is true, treating the assignment as strict mode code. vp js::mutablehandlevalue in/out parameter. points to a js::value variable. the meaning of this variable is different for each of the hooks; see below. description jspropertyop and jsstrictpropertyop callbacks are hooks that applications may install to be called at some point during property access. a jspropertyop may be installed on an individual property as a getter or setter; or it may be installed on a jsclass to hook property gets, sets, or adds. these different cases are described in more detail in the sections below. if a jsprop...
...e that in javascript, an object can inherit properties from its prototype. getters (and sometimes setters; see js_setproperty for details) are called even when the property being accessed is found on a prototype and not on obj itself. in this case obj points to the object from which the property is being accessed, not the object on which the property was defined. jsclass hooks jsclass offers following hooks: jspropertyop jsclass.addproperty is called just after a new property is added to an object. this happens when a program sets a property that isn't already an own property of the target object. it also happens in jsapi functions such as js_defineproperty. on entry, *vp contains the value provided by the code defining or setting the property. the callback may modify *vp. on success...
JS_AddFinalizeCallback
ize_group_start, jsfinalize_group_end, jsfinalize_collection_end } jsfinalizestatus; typedef void (* jsfinalizecallback)(jsfreeop *fop, jsfinalizestatus status, bool iscompartment, void *data); name type description fop jsfreeop * a pointer to an instance of jsfreeop. status jsfinalizestatus one of the jsfinalizestatus constants, described below, indicating the stage of finalize. iscompartment bool false if all compartments are being collected, true if a compartment is being collected. data void * data parameter specified in js_addfinalizecallback. added in spidermonkey 38 name description jsfinalize_group_start called when preparing to sweep a group of compartments, before any...
...back function which the garbage collector calls at several points during garbage collection. rt is the runtime in which you specify the callback. cb is a pointer to the callback function to add. js_removefinalizecallback removes the previously added callback function. obsolete since jsapi 32 js_setfinalizecallback sets a new callback function. it was replaced with js_addfinalizecallback, to allow adding multiple callback functions. see also mxr id search for js_addfinalizecallback mxr id search for js_removefinalizecallback mxr id search for jsfinalizestatus mxr id search for jsfinalize_group_start mxr id search for jsfinalize_group_end mxr id search for jsfinalize_collection_end mxr id search for jsfinalizecallback jsfreeop js_setgccallback bug 723286 - separated from js_se...
JS_CheckAccess
ter. 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 check for permission to read obj's parent. (this is redundant with passing the string id "__parent__" as id.) jsacc_import check for permission to import the property. jsac...
...id.) jsacc_import check for permission to import the property. jsacc_watch check for permission to place a watchpoint on the property. jsacc_read check for permission to get the property's value. jsacc_write when bitwise-ored with one of the above values, check for permission to write the property, not read it. the access check proceeds as follows. if obj has custom jsobjectops, the access check is delegated to the jsobjectops.checkaccess callback. otherwise, if obj's class has a non-null jsclass.checkaccess callback, then it is called to perform the check. otherwise, if a runtime-wide check-object-access callback has been installed by calling js_setcheckobjectaccesscallback, then that is called to perform the check. otherwise, access is ...
JS_GetSecurityCallbacks
_setruntimesecuritycallbacks(jsruntime *rt, jssecuritycallbacks *callbacks); name type description rt jsruntime * a runtime to get/set the security callbacks. callbacks const jssecuritycallbacks * a pointer to the new callbacks for the runtime. ...
...ermonkey 1.8.5 jssubsumesop subsumes; // added in spidermonkey 31 jscheckaccessop checkobjectaccess; // obsolete since jsapi 29 jsprincipalstranscoder principalstranscoder; // obsolete since jsapi 13 jsobjectprincipalsfinder findobjectprincipals; // obsolete since jsapi 13 }; name type description contentsecuritypolicyallows jscspevalchecker a pointer to the function which checks if a csp instance wants to disable eval() and friends. use null is not needed. subsumes jssubsumesop a pointe to the function which returns whether the first principal subsumes the second. use null is not needed. description js_setsecuritycallbacks sets the runtime's security callbacks to callbacks. it allows the ...
JS_PushArguments
f 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 described in format. the type va_list is a standard feature of th...
...es 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 indicates the js type into which to convert the next c/c++ argument. ...
JS_ReportOutOfMemory
reports a memory allocation error. syntax void js_reportoutofmemory(jscontext *cx); void js_reportallocationoverflow(jscontext *cx); // added in spidermonkey 1.8 name type description cx jscontext * the context in which to report the error. description call js_reportoutofmemory to report that an operation failed because the system is out of memory. when the javascript engine tries to allocate memory and allocation fails, it reports an error as though by calling this function. call js_reportallocationoverflow if an operation fails because it tries to use more memory (or more of some other resource) than the application is designed to handle. when a script tries to grow an array beyond 230-1 elements, for example, or concatenate strings such that t...
...grow an array beyond 230-1 elements, for example, or concatenate strings such that the result is more than 229-1 characters long, the javascript engine reports an error as though by calling this function. see js_reporterror and js_seterrorreporter for more information about error handling in the jsapi. see also mxr id search for js_reportoutofmemory mxr id search for js_reportallocationoverflow bug 422348 ...
JS_SetProperty
ev 29 9.5.9) is performed. if obj is a native object with custom setgeneric op, the op is called with (cx, obj, id, &v, false)). otherwise, [[set]] internal method defined in es2015 (rev 29 9.1.9) is performed. if the lookup found no property with the given name, or if it found that obj inherits such a property from a non-native object, then a new own property is added to obj, as described below. the new property is jsprop_enumerate. otherwise, if the lookup found a read-only property or obj non-extensible, nothing happens, but this is not an error. in strict mode, a warning is issued. otherwise, if obj has an own property with the given name, then the existing property's value is set as described below. creation of new properties one of the cases above involves creating a new own p...
...perty is added, the jsclass.addproperty hook is called with the arguments (cx, obj, id, &v). this hook may assign to v. if the hook succeeds and the property has a stored value, then the value left in v by the addproperty hook becomes the stored value of the property. setting the value. two of the cases above can involve setting the value of a new or existing property of obj. this is done as follows. if the property has a javascript setter, it is called; otherwise, if it has a javascript getter, then an error is reported; otherwise the property's setter is called, passing the arguments (cx, obj, id, &v). if the setter succeeds and the property has a stored value, then the value left in v becomes the stored value of the property. on success, js_setproperty returns true, and the value in v i...
JS_SuspendRequest
lete since jsapi 18this 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. 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 ...
...aded 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 that were suspended. it may be 0. js_resumerequest resumes the previously suspended requests. the savedepth argument must be the value returned by the matching js_suspendrequest call. if savedepth is nonzero and garb...
JS_YieldRequest
syntax void js_yieldrequest(jscontext *cx); name type description cx jscontext * the jscontext that is currently in a request on the calling thread. requires request. ...
...er must be in a request on this jscontext. description for more information about thread safety and requests, see js_threadsafe. js_yieldrequest momentarily suspends the current request. a program can call this function periodically to ensure that a long-running request does not block garbage collection indefinitely. the effect is the same as a call to js_suspendrequest immediately followed by a call to js_resumerequest. jsapi 1.7 and earlier js_yieldrequest did not cause cx to relinquish objects it created to other threads that are blocked waiting for them. this bug (bug 402898) will be fixed in spidermonkey 1.8. jsapi 1.7 and earlier js_yieldrequest is available only in js_threadsafe builds. in spidermonkey 1.8 and later, this function will be present, but will do nothing, in ...
SpiderMonkey 1.8
e the release of spidermonkey 1.8 release candidate 1. you can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/js-1.8.0-rc1.tar.gz (md5 checksum: eaad8815dcc66a717ddb87e9724d964e). spidermonkey 1.8 is the javascript engine that shipped in firefox 3.0. it is much faster than spidermonkey 1.7 and contains a few new language features and api features, described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. or, file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. —9 march 2009 known issues spidermonkey 1.8 has one known significant regression from 1.7. in js_threadsafe builds, some objects are not safe to be shared among threads. this includes...
...rings 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_getstringbytes that returns a newly allocated, writable buffer which the application must js_free. js_reportallocationoverflow can be used (instead of js_reportoutofmemory) to indicate that the script is trying to do something that would require more memory than the implementation is designed to handle. the main difference is that js_reportallocationoverflow throws an exception which the application may catch. js_throwstopiteration throws the appropriate stopiteration exception object for the given context. two new con...
Setting up CDT to work on SpiderMonkey
g up cdt to work with the mozilla codebase, but it does not cover setting things up for just spidermonkey instead of the whole mozilla codebase. hence, here is a short-ish guide for doing just that. step 1 - preparing a spidermonkey build for cdt to index all code, spidermonkey has to be built with debug information. the full process of and requisites for doing so are described here. please follow those instructions up until the point of invoking configure. the initial build was in clang, so the modified build commands look like this: mkdir _dbg.obj cd _dbg.obj cc='clang -qunused-arguments -fcolor-diagnostics' cxx='clang++ -qunused-arguments -fcolor-diagnostics' \ ../configure --enable-debug --disable-optimize --enable-debug-symbols note: if you want to use ccache, you can enable i...
...j cd _dbg.obj cc='clang -qunused-arguments -fcolor-diagnostics' cxx='clang++ -qunused-arguments -fcolor-diagnostics' \ ../configure --enable-debug --disable-optimize --enable-debug-symbols note: if you want to use ccache, you can enable it by adding --with-ccache to the arguments list. due to a bug in cdt, you have to make a small change to cdt's build configuration as explained in step 3 below for that to work, though. step 2 - installing eclipse and setting up the project the following run-down is a condensed and updated version of what is explained in much more detail for the entire mozilla codebase. luckily, improvements in cdt have reduced the basic process to manageable five steps: download and extract "eclipse ide for c/c++ developers" from the eclipse downloads page. start...
TPS Formdata Lists
a formdata asset list is an array of objects, each with the following properties: fieldname: required. value: required. date: the date the form data was used, expressed in hours from the present, so 0 means now, and -24 means 24 hours ago. optional, defaults to 0. ...
...e form data was used, expressed in hours from the present, so 0 means now, and -24 means 24 hours ago. optional, defaults to 0. for example: var formdata1 = [ { fieldname: "testing", value: "success", date: -1 }, { fieldname: "testing", value: "failure", date: -2 }, { fieldname: "username", value: "joe" } ]; formdata lists and phase actions you can use the following functions in phase actions for formdata lists: formdata.add formdata.delete formdata.verify formdata.verifynot for an example, see the tps formdata unittest: http://hg.mozilla.org/services/tps/f...st_formdata.js notes note 1, tps supports the delete action for formdata, but sync currently does not correctly sync deleted form data, see bug 564296. note 2, sync currently does not syn...
TPS Password Lists
required. submiturl: the submit url for the password. optional. used for passwords in form fields. realm: the http realm for the password. optional. used for http authentication passwords. username: required. password: required. usernamefield: the username field for a form password. optional. passwordfield: the password field for a form pas...
...he http realm for the password. optional. used for http authentication passwords. username: required. password: required. usernamefield: the username field for a form password. optional. ...
Zest tools
it is being developed alongside zest and can be expected to showcase the latest zest features. ...
... it is being developed alongside zest and can be expected to showcase the latest zest features. ...
Browser security
...
...a bug reports will be handled.pinning violation reportsif a site makes use of key pinning, and your browser sees a certificate chain for that site which does not match the pin, firefox will reject the connection and display an error page. secure development guidelinesthe following content will likely see significant revision, though can be used as a reference for security best practices to follow when developing code for mozilla.security and the jar protocolthis article discusses security concerns with the jar: protocol, which only firefox has ever implemented for web content. ...
Setting up an update server
te/win64/firefox-69.0b9.complete.mar. building a mar building a mar locally is more complicated. part of the problem is that mars are signed by mozilla and so you cannot really build an "official" mar yourself. this is a security measure designed to prevent anyone from serving malicious updates. if you want to use a locally-built mar, the copy of firefox being updated will need to be built to allow un-signed mars. see building firefox for more information on building firefox locally. these changes will need to be made in order to use the locally built mar: put this line in the mozconfig file in root of the build directory (create it if it does not exist): ac_add_options --disable-verify-mar several files contain a line that must be uncommented. open them and find this line: #defines['di...
...36-29-mozilla-central/firefox-71.0a1.en-us.win64.complete.mar, the file https://archive.mozilla.org/pub/firefox/nightly/2019/09/2019-09-17-09-36-29-mozilla-central/firefox-71.0a1.en-us.win64.checksums contains the sha512 for that file as well as for all the other win64 files that are part of that nightly release). if you've built your own mar, you can obtain its sha512 checksum by running the following command, which should work in linux, macos, or windows in the mozillabuild environment: shasum --algorithm 512 <filename> on windows, you can get the exact file size in bytes for your mar by right clicking on it in the file explorer and selecting properties. you'll find the correct size in bytes at the end of the line that begins "size", not the one that begins "size on disk". be sure to rem...
Gecko states
applied 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. ...
... applied 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. ...
Using the Places annotation service
se 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); annotationservice.setpageannotation(uri, "my_extension/some_annotation", "this is the annotation value", 0, 0); retrieving annotations there are corresponding getters for the ...
...nnotations(asourceuri, adesturi, aoverwritedest); copyitemannotations(asourceitemid, adestitemid, aoverwritedest); copies all the annotations from one page/item to another. you can specify whether you want to preserve or replace the destination annotations in case of collisions. the annotation protocol the annotation service provides a protocol handler for the "moz-anno:" protocol. this allows you to link directly to data stored in the annotation service. you can get an annotation uri for a given uri/name pair by calling: getannotationuri(auri, aname); in order for the annotation protocol to work, the annotation in question must have been declared with a mime type. annotations with no mime type will not work. the annotation service also provides special-case handling of favicons...
Preferences API
many applications including firefox and thunderbird have an additional tool for power users, about:config, which can be used to tweak the preferences without ui. interfaces the preferences api is exposed as a set of xpcom components and interfaces: nsiprefservice, nsiprefbranch. ... ...
...many applications including firefox and thunderbird have an additional tool for power users, about:config, which can be used to tweak the preferences without ui. interfaces the preferences api is exposed as a set of xpcom components and interfaces: nsiprefservice, nsiprefbranch. ... ...
extIApplication
erbird 3 the extiapplication is defined in toolkit/components/exthelper/extiapplication.idl. implemented via xpcom service for extiapplication: see the instructions on the fuel (firefox), steel (thunderbird) and smile (seamonkey) pages. method overview boolean quit() boolean restart() void getextensions(extiextensionscallback acallback) attributes the following interfaces are available to all applications: attribute type description id readonly attribute astring the id of the application. name readonly attribute astring the name of the application. version readonly attribute astring the version number of the application. console readonly attribute exticonsole the console obje...
...0 prefs readonly attribute extipreferencebranch the preferences object for the application. defaults to an empty root branch. storage readonly attribute extisessionstorage the storage object for the application. events readonly attribute extievents the events object for the application. supports: "load", "ready", "quit", "unload" the following interfaces are only available to firefox: attribute type description bookmarks readonly attribute fuelibookmarkroots the root bookmarks object for the application. windows readonly attribute nsivariant an array of browser windows within the application. activewindow readonly attribute fueliwindow the currently active browser window. ...
Generating GUIDs
mat of both c++ and idl style. sfink's update-uuids will change the uuid for a given interface and all of its descendants, updating all *.idl files within a directory tree. nsiuuidgenerator a uuid can be generated from privileged mozilla code using nsiuuidgenerator. see the linked page for details. com/xpcom format when #define-ing iids and cids in mozilla c++ code, you generally use the following format: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx #define ns_...id \ { 0xxxxxxxxx, 0xxxxx, 0xxxxx, \ { 0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx } } you can generate code in this format using one of the following tools. online tools http://mozilla.pettay.fi/cgi-bin/mozuuid.pl guidgen guidgen.exe, part of microsoft visual studio, can generate uuids in this format. bash you can p...
...: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx #define ns_...id \ { 0xxxxxxxxx, 0xxxxx, 0xxxxx, \ { 0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx } } you can generate code in this format using one of the following tools. online tools http://mozilla.pettay.fi/cgi-bin/mozuuid.pl guidgen guidgen.exe, part of microsoft visual studio, can generate uuids in this format. ...
Generic factory
al factory object. ...
...umes that the xpcom repository is available as an interface (which it soon will be). background (this is based on my original news posting <beard-2402991733140001@h-198-93-95-151.mcom.com>.) we seem to be creating a huge number of different factory implementations. it seems to me that we can cut down on code size (all those queryinterface, addref, release implementations) if we just use the following class for all of the simple factories: // idea: why not create a generic factory facility so we can avoid // duplication of so much nsifactory code? all we need is an allocator // function, the rest of the implementation is exactly the same. #include "nsifactory.h" class nsgenericfactory : public nsifactory { public: typedef nsresult (*creatorprocptr) (nsisupports *aouter, ...
Creating XPCOM components
this guide is about gecko, and about creating xpcom components for gecko-based applications. though the emphasis is on the practical steps you take to make your c++ code into a component that can be used in gecko, we hope that these steps will also give us an occasion to discuss all of the tools, techniques, and technologies that make up xpcom. accordingly, the book is arranged so that you can follow along and create your own components or learn about different xpcom topics individually, as in a reference work. for example, the introduction includes a discussion of components and what they are, and the first chapter - in which you compile the basic code and register it with mozilla - prompts a discussion of the relationship between components and modules, of xpcom interfaces, and of the regis...
...of the registration process in general. note: in general, you should try to avoid having to create xpcom components. add-ons should try to use the new add-on sdk as much as possible; however, there may be cases when it's unavoidable. note:this article describes a method that uses xpidl but you should use webidl instead. ...
Components.Constructor
omponents.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 object from base principles, as demonstrated below. (this benefit is also partly a result of having to travel through the layer between the javascript engine and xpcom fewer times.) the behavior of functions returned by components.constructor() varies depending upon the arguments given to components.constructor() when called. if only one argument is given, that argument is the contract id of the xpcom component to create. the component is then r...
... .createinstance(components.interfaces.nsibinaryinputstream); bis.setinputstream(someinputstream); // assumes binaryinputstream was initialized previously var bis = new binaryinputstream(someinputstream); components.constructor() is purely syntactic sugar (albeit speedy and pretty syntactic sugar) for actions that can be accomplished using other common methods. ...
Components.classes
ill be the javascript value undefined. you should use the in operator to test for the element before trying to access it: if (!("@some/bogus/class;1" in components.classes)) // do something... the properties of the components.classes object can be enumerated using a for...in loop. usage in order to retrieve the object for a given contractid, you can query the components.classes array as follows: var clazz0 = components.classes["@mozilla.org/messenger;1"]; clazz0 is the class object for the contractid @mozilla.org/messenger;1, which is not usually used by itself, but whose createinstance and getservice methods can be used to create a new instance of the component or to access the singleton instance, if the contract id represents a service. a new xpcom component instance can be creat...
...zilla.org/messenger;1"]; clazz0 is the class object for the contractid @mozilla.org/messenger;1, which is not usually used by itself, but whose createinstance and getservice methods can be used to create a new instance of the component or to access the singleton instance, if the contract id represents a service. ...
Components.isSuccessCode
ents.issuccesscode() may be used to determine whether an xpcom return code (an nsresult) indicates success or 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. components.issuccesscode() is functionally equivalent to the following javascript: function issuccesscode(returncode) { return (returncode & 0x80000000) === 0; } since failure error codes are turned into exceptions when encountered in javascript, this function usually is not necessary. however, if you are using asynchronous apis, it may be essential. for example, if you ask a component or service to asynchronously perform some task, you must usually pass in ...
...ly 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: nsiasyncstreamcopier.init() has changed in gecko 1.9.2, omit last 2 boolean parameters if you're using gecko 1.9.1 and earlier. const cc = components.classes; const ci = components.interfaces; const cr = components.results; /...
JavaXPCOM
javaxpcom is not actively maintained. with javaxpcom, a developer can talk to xpcom or embed gecko from a java application. javaxpcom is very similar to xpconnect (javascript-xpcom bridge), and uses xpidl. note: javaxpcom was included in xulrunner up through version 1.9.2. it has been removed in xulrunner 2, and is not actively maintained. documentation javaxpcom development how to get and build the source, as well as how to view and report bugs. ...
...lopment how to get and build the source, as well as how to view and report bugs. sample code there are several java test applications checked in to the tree that give examples on how to embed gecko or init xpcom from within java. embedding mozilla in a java application using javaxpcom xulrunner ships with the javaxpcom component, which allows java code to interact with xpcom objects. as you will see in this article, working with xpcom objects in java is not that much different than doing so in c++. view all... community view mozilla embedding forums... mailing list newsgroup rss feed related topics xpcom, embedding mozilla ...
HOWTO
async network requests problem you want to make network requests or do other asynchronous work in xpcshell. however, when you start your script, it exits immediately, before the network request returns. solution 1. put the following at the end of your script: // do async processing // from <https://developer.mozilla.org/en/xpconnect/xpcshell/howto> print("doing async work"); gscriptdone = false; var gthreadmanager = cc["@mozilla.org/thread-manager;1"] .getservice(ci.nsithreadmanager); var mainthread = gthreadmanager.currentthread; while (!gscriptdone) mainthread.processnextevent(true); while (mainthread.haspendingevents()) mainthread.processnextevent(true); 2. in all callbacks where your script is finished, i.e. both success and error callbacks, put: gscriptdone = true; if y...
...t: "0x80040111 (ns_error_not_available)" location: "js frame :: file.js :: <top_level> :: line 12" data: no] solution 1 var loader = components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getservice(components.interfaces.mozijssubscriptloader); loader.loadsubscript("chrome://myall/content/file.jsm"); see: http://mxr.mozilla.org/comm-central/...figutils.js#54 solution 2 append the following at the top of your js file which you want to run in xpcshell { // <https://developer.mozilla.org/en/xpconnect/xpcshell/howto> // <https://bugzilla.mozilla.org/show_bug.cgi?id=546628> let cc = components.classes; let ci = components.interfaces; // register resource://app/ uri let ios = cc["@mozilla.org/network/io-service;1"] .getservice(ci.nsiioservice); let reshandler = ios.
NS_InitXPCOM3
parameter may be nsnull. astaticmodules [in] an array of nsstaticmoduleinfo objects. passing null causes the default (built-in) static modules to be registered, if present. astaticmodulecount [in] the number of elements in astaticmodules. return values the ns_initxpcom3 function returns ns_ok if successful. otherwise, it returns an error code. some of the possible errors are documented below: ns_error_not_initialized indicates that static globals were not yet initialized, which may happen if this method is called before xpcom's static initialization code executes. this error may also occur if xpcom is being initialized after ns_shutdownxpcom has been called. remarks you must call ns_initxpcom3 (or ns_initxpcom2) before proceeding to use xpcom in a process. the one exception is ...
...nitxpcom2) before proceeding to use xpcom in a process. the one exception is that you may call ns_newlocalfile or ns_newnativelocalfile to create a nsifile needed for the abindirectory parameter to ns_initxpcom3. many of the xpcom glue functions and classes are also available prior to xpcom initialization, including for example nsembedcstring and nscomptr. initializing xpcom with static modules allows the application to easily define modules that are linked into the application's executable. this can be a performance improvement over dynamically loaded xpcom modules. history this function was finalized for mozilla 1.8. see bug 296561 for details. see also ns_initxpcom2, ns_shutdownxpcom ...
NS_OVERRIDE
if there is no base class method with the same signature, a compiler with static-checking enabled will fail to compile. ns_override is declared in nscore.h, beginning with gecko 2.0. it was introduced in bug 500870. ...
... ...
operator=
« xpcom api reference summary this operator is a shortcut for the inherited nsacstring::assign family of functions. self_type& operator=( const self_type& astring ); parameters astring [in] a nsembedcstring to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator=( const abstract_string_type& astring ); parameters astring [in] a nsacstring to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. return values this operator returns a reference back to the object bei...
...tring ); parameters astring [in] a nsacstring to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator=( char_type achar ); parameters achar [in] a character to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. see also nsacstring::assign ...
operator=
« xpcom api reference summary this operator is a shortcut for the inherited nsastring::assign family of functions. self_type& operator=( const self_type& astring ); parameters astring [in] a nsembedstring to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator=( const abstract_string_type& astring ); parameters astring [in] a nsastring to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. return values this operator returns a reference back to the object being ...
...string ); parameters astring [in] a nsastring to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator=( char_type achar ); parameters achar [in] a character to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. see also nsastring::assign ...
XPCOM glue classes
if there is no base class method with the same signature, a compiler with static-checking enabled will fail to compile.ns_postconditionmacrons_preconditionmacronsacstringthe nsacstring abstract class represents a character string composed of single-byte storage units. this class is typically used to represe...
...s null-terminated storage.nsembedstringthe nsembedstring concrete class provides a way to construct a nsastring object that allocates null-terminated storage.nsfixedcstringclass declarationnsfixedstringclass declarationnsliteralcstring (external)class declarationnsliteralstring (external)class declarationnsmemorythe nsmemory class provides static helper routines to manage memory. these routines allow easy access to xpcom's global nsimemory implementation without having to go through the service manager to get it.nspromiseflatcstringclass declarationnspromiseflatstringclass declarationnsrefptrrefptr (formerly known as nsrefptr, see bug 1207245) is a general class to implement reference counting pointers for objects. it is similar to nscomptr, but does not require that the type be an xpcom inte...
IAccessible2
n the object, but is cached in the accessible object for use when it would be helpful to access the window handle in cases where an event isn't fired on this object. a use case is when a screen reader is grabbing an entire web page on a page load. ...
...iserviceprovider *pservice = null; hr = pacc->queryinterface(iid_iserviceprovider, (void **)&pservice); if(succeeded(hr)) { iaccessible2 *pia2 = null; hr = pservice->queryservice(iid_iaccessible, iid_iaccessible2, (void**)&pia2); if (succeeded(hr) && pia2) { // the control supports iaccessible2. ...
amIWebInstaller
toolkit/mozapps/extensions/amiwebinstaller.idlscriptable this interface is used to allow web pages to start installing add-ons. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) method overview boolean installaddonsfromwebpage(in astring amimetype, in nsidomwindow awindow, in nsiuri areferer, [array, size_is(ainstallcount)] in wstring auris, [array, size_is(ainstallcount)] in wstring ahashes, [array, size_is(ainstallcount)] in wstring anames, [array, size_is(ainstallcount)] in wstring aicons, [optional] in amiinstallcallback acallback, [optional] in pruint32 ainstallcount); boolean isinstallenabled(in astring amimetype, in nsiuri areferer); note: pri...
...g the number of add-ons to install. return value true if the installation was successfully started. isinstallenabled() checks if installation is enabled for a web page. boolean isinstallenabled( in astring amimetype, in nsiuri areferer ); parameters amimetype the mime type for the add-on to be installed. areferer the uri of the web page for which to see if installation is allowed. return value true if installation is enabled. ...
imgIEncoder
h pixel is bgra (this is used by canvas to match it's internal representation) pre-multiplied alpha is used (that is, 50% transparent red is 0x80800000, not 0x80ff0000) possible values for outputoptions. multiple values are semicolon-separated. png: ---- transparency=[yes|no|none] -- default: "yes" overrides default from input format. "no" and "none" are equivalent. apng: ----- the following options can be used with startimageencode(): transparency=[yes|no|none] -- default: "yes" overrides default from input format. "no" and "none" are equivalent. skipfirstframe=[yes|no] -- default: "no" controls display of the first frame in animations. png-only clients always display the first frame (and only that frame). frames=# -- default: "1" total number of frames in the ...
...[yes|no] -- default: "no" controls display of the first frame in animations. png-only clients always display the first frame (and only that frame). frames=# -- default: "1" total number of frames in the image. the first frame, even if skipped, is always included in the count. plays=# -- default: "0" number of times to play the animation sequence. "0" will repeat forever. the following options can be used for each frame, with addimageframe(): transparency=[yes|no|none] -- default: "yes" overrides default from input format. "no" and "none" are equivalent. delay=# -- default: "500" number of milliseconds to display the frame, before moving to the next frame. dispose=[none|background|previous] -- default: "none" what to do with the image's canvas before rende...
mozIStorageAggregateFunction
an aggregate function is a function that returns one value from a series of values. there are a number of already defined aggregate functions provided by sqlite. objects implementing this interface can be registered with mozistorageconnection.createaggregatefunction(). storage/public/mozistorageaggregatefunction.idlscriptable please add a summary to this article. ...
...async() this callback will run on a different thread from the rest of your code. likewise, if you execute sql on a different thread, this callback will be executed on that thread. this callback should be reentrant if any of the above applies to your use of the storage apis! nsivariant onfinal() return value an nsivariant this is the return value of the function. sample code both of the following code samples assume that the variable dbconn is an opened mozistorageconnection. javascript // first, create our object that will represent our function. var standarddeviationfunc = { _numbers: [], onstep: function(aarguments) { this._numbers.push(aarguments.getint32(0)); }, onfinal: function() { let total = 0; let ilength = this._numbers.length; this._numbers.foreach...
mozIStorageConnection
abase. sqlite database page size constant constant value description default_page_size 32768 the default size for sqlite database pages. this is used by the storage api when creating new databases, and must match the sqlite_default_page_size configured in db/sqlite3/src/makefile.in. methods asyncclose() asynchronously closes a database connection, allowing all pending asynchronous statements to complete first. void asyncclose( in mozistoragecompletioncallback acallback optional ); parameters acallback optional an optional callback handler to be executed when the connection is successfully closed. that object's mozistoragecompletioncallback.complete() routine will be called once the connection is closed. exceptions thrown ns_error_u...
...o execute. additionally, the system will be able to inform you if you erroneously attempt to execute it synchronously. createtable() this method creates a table with the given table name and schema. void createtable( in string atablename, in string atableschema ); parameters atablename the name of the table to create; table names may consist of the letters a-z in either upper or lower case, the underscore, and the digits 0-9. the first character must be a letter. atableschema the table's schema. this should be specified using the same syntax the create table statement uses. for example: "foo integer, bar string". exceptions thrown ns_error_failure table already exists or the requested table couldn't be created. executeasync() asynchronously executes an array of qu...
mozIStorageFunction
there are a number of already defined functions provided by sqlite. objects implementing this interface can be registered with mozistorageconnection.createfunction(). storage/public/mozistoragefunction.idlscriptable please add a summary to this article. last changed in gecko 1.9.1.4 (firefox 3.5.4) inherits from: nsisupports method overview nsivariant onfunctioncall(in mozistoragevaluearray afunctionarguments); methods onfunctioncall() the implementation of the function. ...
... that thread. this callback should be reentrant if any of the above applies to your use of the storage apis! nsivariant onfunctioncall( in mozistoragevaluearray afunctionarguments ); parameters afunctionarguments a mozistoragevaluearray holding the arguments passed in to the function. return value an nsivariant this is the return value of the function. sample code both of the following code samples assume that the variable dbconn is an opened mozistorageconnection. javascript starting in gecko 1.9.1.4 (firefox 3.0.15), you can directly pass your function into the mozistorageconnection method mozistorageconnection, like this: dbconn.createfunction("square", 1, function(aarguments) { let value = aarguments.getint32(0); return value * value; }); // run some query th...
mozIThirdPartyUtil
nkey 2.1) method overview boolean isthirdpartychannel(in nsichannel achannel, [optional] in nsiuri auri); boolean isthirdpartyuri(in nsiuri afirsturi, in nsiuri aseconduri); boolean isthirdpartywindow(in nsidomwindow awindow, [optional] in nsiuri auri); methods isthirdpartychannel() determine whether the given channel and its content window hierarchy is third party. this is done as follows: if achannel is an nsihttpchannel and has the 'forceallowthirdpartycookie' property set, then: if auri is null, return false. otherwise, find the uri of the channel, determine whether it is foreign with respect to auri, and return. find the uri of the channel and determine whether it is third party with respect to the uri of the channel. if so, return. obtain the bottommost nsidomwindow, and...
....google.com/", but "http://mail.yahoo.com/" and "http://192.168.1.1/" are. boolean isthirdpartyuri( in nsiuri afirsturi, in nsiuri aseconduri ); parameters afirsturi missing description aseconduri missing description return value true if afirsturi is third party with respect to aseconduri. isthirdpartywindow() determine whether the given window hierarchy is third party. this is done as follows: obtain the uri of the principal associated with awindow. call this the 'bottom uri'. if auri is provided, determine if it is third party with respect to the bottom uri. if so, return. find the same-type parent window, if there is one, and its uri. determine whether it is third party with respect to the bottom uri. if so, return. therefore, each level in the window hierarchy is tested. (this m...
nsIAppStartup
ted boolean true if the startup process was interrupted by an interactive prompt. this can be used, for example, when doing performance testing of the startup process to discount numbers for tests that were interrupted by a user prompt. nativeappsupport nsinativeappsupport getter for "native application support." read only. obsolete since gecko 1.9.1 constants the following flags may be passed as the amode parameter to the quit() method. one and only one of the "quit" flags must be specified. the erestart flag may be bit-wise combined with one of the "quit" flags to cause the application to restart after it quits. constant value description econsiderquit 0x01 attempt to quit if all windows are closed. eattemptquit 0x02 ...
...ws will be closed but we don't want to take this as a signal to quit the application. bracket the code where the last window could close with these. void exitlastwindowclosingsurvivalarea(); parameters none. getstartupinfo() returns a javascript object with events from startup and the timestamps indicating when they occurred. parameters none. return value a javascript object with the following fields. keys are the event names and their values are the times. events that didn't occur are not in the object. event identifier (key) description main time at which main application core was loaded. note: only available with libxul builds. firstpaint time the first paint occurred. note: only available with libxul builds. ...
nsIBrowserSearchService
y 2.1) implemented by: @mozilla.org/browser/search-service;1. to access this service, use: var browsersearchservice = components.classes["@mozilla.org/browser/search-service;1"] .getservice(components.interfaces.nsibrowsersearchservice); attempting to use any method or attribute of this interface before init() has completed will force the service to fall back to a slower, synchronous, initialization. this is not an issue if your code is executed in reaction to a user interaction, as initialization is complete by then, but this is an issue if your code is executed during startup. if you need to write code that is executed during startup and makes use of nsibrowsersearchservice, you should make sure that this code is executed from the callback to init(). metho...
... enginecount the number of hidden installed search engines. engines an array of the hidden installed nsisearchengines. init() initialize the service, or if the service is already initialized, do nothing. this method was introduced in firefox 16. attempting to call any method of this interface before init() has completed will force the service to fall back to a slower, synchronous, initialization. if your code requires nsibrowsersearchservice and is executed during startup, you should make sure that this code is executed from the callback to init(). void init( [optional] in nsibrowsersearchinitobserver observer ); parameters observer if specified, a callback called once initialization is complete, or immediately, if the service has alrea...
nsICachingChannel
in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface provides: support for "stream as file" semantics (for jar and plugins). support for "pinning" cached data in the cache (for printing and save-as). support for uniquely identifying cached data in cases when the url is insufficient. for example a http form submission. a channel may optionally implement this interface to allow clients to affect its behavior with respect to how it uses the cache service. method overview boolean isfromcache(); obsolete since gecko 2.0 attributes attribute type description cacheasfile boolean specifies whether or not the data should be cached to a file. this may fail if the disk cache is not present. the value of this attribute is usually only settable during the processing of ...
...tisfy 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 whether or not this channel's data is being loaded from the cache. boolean isfromcache(); parameters none. return value returns true if this channel's data is being loaded from the cache, otherwise returns false. this value is undefin...
nsIChromeFrameMessageManager
content/base/public/nsimessagemanager.idlscriptable handles loading of content in a remote chrome frame. ...
...ts from: nsiframemessagemanager last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void loadframescript(in astring aurl, in boolean aallowdelayedload); void removedelayedframescript(in astring aurl); methods loadframescript() loads a script into the remote frame. void loadframescript( in astring aurl, in boolean aallowdelayedload ); parameters aurl the url of the script to load into the frame; this must be an absolute url, but data: urls are supported. aallowdelayedload if true, the script will be loaded when the remote frame becomes available; otherwise, the script will only be loaded if the frame is already available. removedelayedframescript() removes a script from the list of ...
nsIChromeRegistry
full 2 methods canonify() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) note: this method is obsolete; use convertchromeurl() instead. converts a chrome url into a canonical representation by ensuring that the filename portion of the url is included, as in chrome://package/provider/file. this is useful because chrome urls are allowed to be specified in "shorthand", leaving the "file" portion off. in that case, the url is expanded to chrome://package/provider/package.ext. the extension, ext, is one of: xul for a "content" package. css for a "skin" package. dtd for a "locale" package. void canonify( in nsiuri achromeurl ); parameters achromeurl the url that is to be canonified. checkfo...
...g for new packages and so forth. void checkfornewchrome(); parameters none. convertchromeurl() resolves a chrome url to an loadable uri using the information in the registry. a new nsiuri is returned; the original is left unmodified. this lets you take a non-canonical chrome uri, such as chrome://package/provider/file, and convert it into a canonical one. this is useful because chrome urls are allowed to be specified in "shorthand", leaving the "file" portion off. in that case, the url is expanded to chrome://package/provider/package.ext. the extension, ext, is one of: xul for a "content" package. css for a "skin" package. dtd for a "locale" package. nsiuri convertchromeurl( in nsiuri achromeurl ); parameters achromeurl the url that is to be converted.
nsIConsoleService
e script. void getmessagearray( [optional] out pruint32 count, [retval, array, size_is(count)] out nsiconsolemessage messages ); parameters count the number of messages in the array. if no messages are logged, this function will return a count of 0, but allocating a placeholder word for messages, showing as a 0-length array when called from the script. note: see the code samples below for how to call getmessagearray. logmessage() void logmessage( in nsiconsolemessage message ); parameters message the nsiconsolemessage to log. logstringmessage() a convenient method for logging simple messages. void logstringmessage( in wstring message ); parameters message the string to log. registerlistener() registers a listener, to notify when an error is logged. no...
.... logmessage() void logmessage( in nsiconsolemessage message ); parameters message the nsiconsolemessage to log. logstringmessage() a convenient method for logging simple messages. void logstringmessage( in wstring message ); parameters message the string to log. registerlistener() registers a listener, to notify when an error is logged. note: to guard against stack overflows from listeners which could log messages (this could be done inadvertently through listeners implemented in javascript), we do not call any listeners when another error is already being logged. void registerlistener( in nsiconsolelistener listener ); parameters listener the nsiconsolelistener to add. reset() to clear the message buffer (for example, for privacy reasons): void reset()...
nsIContentPrefService2
dom/interfaces/base/nsicontentprefservice2.idlscriptable asynchronous api for content preferences 1.0 66 introduced gecko 20.0 inherits from: nsisupports last changed in gecko 20.0 (firefox 20.0 / thunderbird 20.0 / seamonkey 2.17) description content preferences allow the application to associate arbitrary data, or "preferences", with specific domains, or web "content". ...
...fox 20.0 / thunderbird 20.0 / seamonkey 2.17) description content preferences allow the application to associate arbitrary data, or "preferences", with specific domains, or web "content". specifically, a content preference is a structure with three values: a domain with which the preference is associated, a name that identifies the preference within its domain, and a value. (see nsicontentpref below.) for example, if you want to remember the user's preference for a certain zoom level on www.mozilla.org pages, you might store a preference whose domain is "www.mozilla.org", whose name is "zoomlevel", and whose value is the numeric zoom level. a preference need not have a domain, and in that case the preference is called a "global" preference. this interface doesn't impart any special significa...
nsICookieService
rits from: nsisupports last changed in gecko 1.9 (firefox 3) see nsicookiemanager and nsicookiemanager2 for methods to manipulate the cookie database directly. this separation of interface is mainly historical. var cookiesvc = components.classes["@mozilla.org/cookieservice;1"] .getservice(components.interfaces.nsicookieservice); notifications this service broadcasts the following notifications when the cookie list is changed, or a cookie is rejected: topic subject data cookie-changed broadcast whenever the cookie list changes in some way. there are four possible data strings for this notification; one notification will be broadcast for each change. depending on the data value, either an nsicookie2 interface pointer representing...
...tiate the load of the document referenced by auri. achannel the channel used to load the document. this parameter may be null, but it is strongly recommended that a non-null value be provided to ensure that the cookie privacy preferences are honored. return value returns the resulting cookie string. setcookiestring() set the cookie string associated with the uri. note: should be able to allow null aprompt, since nsiprompt can be queried from achannel. void setcookiestring( in nsiuri auri, in nsiprompt aprompt, in string acookie, in nsichannel achannel ); parameters auri the uri of the document for which cookies are being queried. aprompt the prompt to use for all user-level cookie notifications. acookie the cookie string to set. achannel the channel used to ...
nsICryptoHash
uested amount of data to be calculated into the hash is not available. ns_error_not_initialized indicates that init() or initwithstring() has not been called. example computing the hash of a file you can easily compute the hash of a file using nsicryptohash. you will need to create an instance of nsicryptohash, open an input stream from a file, and then update the hash with the file. ...
...her common operation is computing the hash value of a string. since hash functions are computed over bytes, you will first need to convert the string to a series of bytes using nsiscriptableunicodeconverter and a unicode encoding that you specify. note: different encodings will produce different hash values! you should always use the same encoding if you intend to compare results. the example below shows how to convert a string to bytes in the utf-8 encoding, and then compute the sha256 hash of it. the result is computed as a hex string as in the previous example. in this example, we use the update() method to pass an array of bytes to be hashed. as in the previous example, we convert the binary result to a hex string. var str = "hello world"; var converter = components.classes["@mozill...
nsIDOMMozNetworkStatsManager
tatsmanager = components.classes["@mozilla.org/networkstatsmanager;1"] .createinstance(components.interfaces.nsidomnetworkstatsmanager); furthermore, the networkstatsmanager is published through a moznetworkstats child object within the navigator object. if the object exists, you can use the network statistics service. ...
...to be saved in the database. nsidomdomrequest getavailableservicetypes(); parameters none. return value an nsidomdomrequest object. if successful, the result field of the domrequest holds an array of the currently available service types. networkstatsalarmoptions networkstatsalarmoptions is a dictionary object used to filter an alarm request made when calling addalarm(). it contains the following fields: starttime a date object representing the start time. data a date object representing the date of data. networkstatsgetoptions networkstatsgetoptions is a dictionary object used to filter a network statistics request made when calling getsamples(). it contains the following fields: appmanifesturl a string used to filter network stats by app. servicetype a string used to f...
nsIDOMParser
note: if you're a web developer, please refer to the domparser documentation instead. creating a domparser to create a domparser object from a web page or a chrome script running in a window, simply use new domparser(). when you create a domparser from a privileged script, you can pass parameters to the constructor, more on that below. to create a domparser when the constructor is not available (e.g., from a js xpcom component, a js module, or an xpcshell test), use: var parser = components.classes["@mozilla.org/xmlextras/domparser;1"] .createinstance(components.interfaces.nsidomparser); // optionally, call parser.init(principal, documenturi, baseuri); principals, document and base uri note: this section covers changes introduced to domparser in gecko 1.9. (this section ...
..., 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 instantiated by calling ne...
nsIDOMXULElement
x 3) method overview void blur(); void click(); void docommand(); void focus(); nsidomnodelist getelementsbyattribute(in domstring name, in domstring value); nsidomnodelist getelementsbyattributens(in domstring namespaceuri, in domstring name, in domstring value); attributes attribute type description align domstring gets/sets the value of the element's align attribute. ...
...id click(); void docommand(); void focus(); nsidomnodelist getelementsbyattribute(in domstring name, in domstring value); nsidomnodelist getelementsbyattributens(in domstring namespaceuri, in domstring name, in domstring value); attributes attribute type description align domstring gets/sets the value of the element's align attribute. allowevents boolean true if the element's allowevents attribute is the string "true", otherwise false. removes the attribute if you set it to false. boxobject nsiboxobject read only. gets or creates a box object for the element; browser, editor, iframe, listbox, menu, menupopup, scrollbox, tooltip and tree elements receive specialized box objects allowing access to additional properties not normally available from script. builder nsixultem...
nsIEditor
void switchtextdirection(); output methods astring outputtostring(in astring formattype, in unsigned long flags); example: // flags are declared in base/public/nsidocumentencoder.idl // outputselectiononly = 1, outputformatted = 2, // outputraw = 4, outputbodyonly = 8, // outputpreformatted = 16, outputwrap = 32, // outputformatflowed = 64, outputabsolutelinks = 258, // outputencodew3centities = 256, outputcrlinebreak = 512, // outputlflinebreak = 1024, outputnoscriptcontent = 2048, // outputnoframescontent = 4096, outputnoformattinginpre = 8192, // outputencodebasicentities=16384, outputencodelatin1entities=32768, // outputencodehtmlentities=65536, outputpersistnbsp=131072 editorapi.outputtostring('tex...
...tnoscriptcontent = 2048, // outputnoframescontent = 4096, outputnoformattinginpre = 8192, // outputencodebasicentities=16384, outputencodelatin1entities=32768, // outputencodehtmlentities=65536, outputpersistnbsp=131072 editorapi.outputtostring('text/html', 2); editorapi.outputtostring('text/plain', 4); // output the body tag, body children and the html end tag (</html>). // tag name are in lower case with <br>. editorapi.outputtostring('text/html', 8); // xml: all in xml with _moz_dirty="" in new tags, html tags are in upper case // application/xhtml+xml format do the same editorapi.outputtostring('text/xml', 2); // the body is not recognized, everything is printed void outputtostream(in nsioutputstream astream, in astring formattype, in acstring charsetoverride, in uns...
nsIEditorSpellCheck
added to the personal dictionary. returns an empty string when there are no more words. wstring getpersonaldictionaryword(); parameters none. return value the next word in the personal dictionary. getsuggestedword() used to get suggestions for the last word that was checked and was misspelled. the first call returns the first (best) suggestion. subsequent calls iterate through all suggestions, allowing you to build a list. when there are no more suggestions, an empty string (not a null pointer) is returned. wstring getsuggestedword(); parameters none. return value the next best suggestion for the last word that was checked and was misspelled, or an empty string if there are no remaining suggestions. ignorewordalloccurrences() tells the spell checker to ignore all occurrences of the specifie...
...since gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6)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. saves the currently selected dictionary as the default. the function uninitspellchecker() will also do this, but that function may not be called in some situations. this function allows the caller to force the default immediately. note: this method was removed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6). since spelling dictionaries can now be selected per-site, this method is no longer needed. void savedefaultdictionary(); parameters none. setcurrentdictionary() selects the main dictionary to use. void setcurrentdictionary( in astring dictionary ); parame...
nsIEventListenerInfo
vice.getlistenerinfofor, which provides a list of all the listeners to a given event target. 1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) method overview nsisupports getdebugobject(); astring tosource(); attributes attribute type description allowsuntrusted boolean indicates whether or not the event listener allows untrusted events. read only. capturing boolean indicates whether or not the event listener is in capture mode. read only. insystemeventgroup boolean indicates whether or not the event listener is in the system event group. read only. type astring the type of the event for which ...
...ns the debugger object if the debug service is active. nsisupports getdebugobject(); parameters none. return value if jsdidebuggerservice is active and the listener is implemented in js, this returns the listener as a jsdivalue. otherwise null. this is the method you should use if you want to get access to the actual listener, but the debugger service must be already active, which significantly slows down script execution. accordingly, this should probably only be used by real debuggers. this approach is necessary because event listeners added with addeventlistener won't necessarily be nsieventlisteners; the dom code will fix up ordinary javascript functions to act as listeners. tosource() tries to serialize the event listener to a string. astring tosource(); parameters none. return value r...
nsIFileInputStream
inherits from: nsiinputstream last changed in gecko 1.7 method overview void init(in nsifile file, in long ioflags, in long perm, in long behaviorflags); constants constant value description delete_on_close 1<<1 if this is set, the file will be deleted by the time the stream is closed. it may be removed before the stream is closed if it is possible to delete it and still read from it. if open_on_read is defined, and the file was recreated after the first delete, the file will be deleted again when it is closed again. ...
...is is set, the file will be reopened whenever seek(0) occurs. if the file is already open and the seek occurs, it will happen naturally. (the file will only be reopened if it is closed for some reason.) defer_open 1<<4 if this is set, the file will be opened (i.e., a call to pr_open() done) only when we do an actual operation on the stream, or more specifically, when one of the following is called: seek() tell() available() read() readline() defer_open is useful if we use the stream on a background thread, so that the opening and possible stating of the file happens there as well. note: using this flag results in the file not being opened during the call to init. this means that any errors that might happen when this flag is not set...
nsIFocusManager
ndow); void elementisfocusable(in nsidomelement aelement, in unsigned long aflags); nsidomelement movefocus(in nsidomwindow awindow, in nsidomelement astartelement, in unsigned long atype, in unsigned long aflags); void setfocus(in nsidomelement aelement, in unsigned long aflags); void windowhidden(in nsidomwindow awindow); native code only! void windowlowered(in nsidomwindow awindow); native code only! void windowraised(in nsidomwindow awindow); native code only! void windowshown(in nsidomwindow awindow, in prbool aneedsfocus); native code only! attributes attribute type description activewindow nsidomwindow the most active (frontmost) window, or null if no window that is part of the applicatio...
... within the window containing aelement to aelement. void setfocus( in nsidomelement aelement, in unsigned long aflags ); parameters aelement aflags native code only!windowhidden called when a document in a window has been hidden or otherwise can no longer accept focus. void windowhidden( in nsidomwindow awindow ); parameters awindow native code only!windowlowered called when a window has been lowered. void windowlowered( in nsidomwindow awindow ); parameters awindow native code only!windowraised called when a window has been raised. void windowraised( in nsidomwindow awindow ); parameters awindow native code only!windowshown called when a new document in a window is shown. void windowshown( in nsidomwindow awindow, in...
nsILoginManagerStorage
); parameters oldlogin the login to be modified. newlogindata the login information to replace the oldlogin with. this may be specified as either an nsilogininfo or an nsipropertybag2 object. removealllogins() implement this method to remove all logins from the login store. this is called by the browser sanitization feature when the user asks to clear all stored passwords. the user interface allows this to be done without getting each login first (which might require knowing the master password). no password should be required in order to remove all logins. void removealllogins(); parameters none. removelogin() implement this method to remove the specified login from the login store. gecko 1.9.1 note the values of any nsiloginmetainfo properties are ignored. void removelogin( in n...
... for logins in the login manager's data store, returning an array of matching logins. if there are no matching logins, return an empty array. void searchlogins( out unsigned long count, in nsipropertybag matchdata, [retval, array, size_is(count)] out nsilogininfo logins ); parameters count the number of elements in the logins array. matchdata the data used for the search. this does not follow the same requirements as findlogins() for those fields; wildcard matches are not specified. logins an array of matching nsilogininfo objects. setloginsavingenabled() implement this method to enable or disable login saving for the specified host. when login saving is disabled for a host, the login manager will not propt the user for permission to store logins for that host. existing logins for th...
nsIMIMEInputStream
inherits from: nsiinputstream last changed in gecko 1.3 implemented by: @mozilla.org/network/mime-input-stream;1. ...
...oid setdata(in nsiinputstream stream); attributes attribute type description addcontentlength boolean when true a "content-length" header is automatically added to the stream. the value of the content-length is automatically calculated using the available() method on the data stream. the value is recalculated every time the stream is rewound to the start. not allowed to be changed once the stream has been started to be read. methods addheader() adds an additional header to the stream on the form "name: value". may not be called once the stream has been started to be read. void addheader( in string name, in string value ); parameters name name of the header. value value of the header. setdata() sets data-stream. may not be called...
nsIMacDockSupport
adds two menu items to the dock menu. the menu items are "new window" and "new private window". if permanent private browsing mode is enabled then the "new private window" menu item is hidden. this is created by using the dockmenu attribute of nsimacdocksupport here: http://mxr.mozilla.org/mozilla-release/source/browser/base/content/browser.js#1562 this is seen here: if you were to copy and follow that example you would replace the default native menu. this can be done like this: var docksupport = cc['@mozilla.org/widget/macdocksupport;1'].getservice(ci.nsimacdocksupport); console.log('docksupport:', docksupport); var win = services.wm.getmostrecentwindow('navigator:browser'); var macmenu = win.document.createelementns('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menu...
...nativemenu;1"].createinstance(ci.nsistandalonenativemenu); console.log('dockmenuelement:', dockmenuelement); nativemenu.init(dockmenuelement); docksupport.dockmenu = nativemenu; this replaces the default menu with this one menuitem that says "show most recent window". notice the activateapplication(true), if this is not done then firefox will not be activated. the result of this code is shown below. notice how the "new window" and "new private window" menuitem's are missing. therefore, if you would like to add or remove items to the menu it is recommended to manipulate the default menu item which is on the hidden window of firefox. note: the hidden window of firefox (services.appshel.hiddendomwindow) loads on browser startup, so if you would like to access it on startup of the browser make...
nsIMarkupDocumentViewer
ell/base/nsimarkupdocumentviewer.idlscriptable describes the properties of a content viewer for an html or xml markup document. inherits from: nsisupports last changed in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) method overview void scrolltonode(in nsidomnode node); void sizetocontent(); attributes attribute type description allowplugins boolean if true, plugins are allowed within the doc shell. default = true. obsolete since gecko 1.8 authorstyledisabled boolean disable entire author style level (including html presentation hints) bidicharacterset octet whether to force the user's character set 1 - use the document character set 2 - use the character set chosen by the user. obsolete si...
... 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. methods scrolltonode() scroll the make the spec...
Building an Account Manager Extension
ly shown for imap accounts... if (server.type == \"imap\") return true; return false; }, queryinterface: xpcomutils.generateqi([ components.interfaces.nsimsgaccountmanagerextension ]) } step 2: building a component we convert the interface to a xpcom component and register it in the component manager as account manager extension. therefore we add the following code to the previous. the javascript file has to be saved either in the extension's or thunderbird's component directory. // define the contract information needed for this component... // ... the unique component identifier (change it if you copied this example!)... devmoaccountmanagerextension.prototype.classid = components.id("{659ce960-9dfb-11dd-ad8b-0800200c9a55}"); // ... the descript...
...x 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, accountvalues) { } function oninit(pageid, serverid) { } function onaccepteditor() { } function onsave() { } function updatepage() {} step5: putting it all together // todo build an demo extension for this tutorial... how to build an xpcom component in javascript ...
nsIMsgCompFields
(bug 68784) messageid char * needtocheckcharset prbool indicates whether we need to check if the ...
... emailaddressonly ); void convertbodytoplaintext ( ); attachment handling methods void addattachment ( in nsimsgattachment attachment ); void removeattachment ( in nsimsgattachment attachment ); void removeattachments ( ); header methods void setheader(char* name, char* value); references this interface is the type of the following properties: nsimsgcompose.compfields, nsimsgcomposeparams.composefields this interface is passed as an argument to the following methods: nsimsgcomposesecure.begincryptoencapsulation, nsimsgcomposesecure.requirescryptoencapsulation, nsimsgsend.createandsendmessage, nsimsgsend.sendmessagefile, nsismimejshelper.getnocertaddresses, nsismimejshelper.getrecipientcertsinfo ...
nsIMsgDatabase
nextfakeofflinemsgkey nsmsgkey readonly: for saving "fake" offline msg hdrs. defaultviewflags nsmsgviewflagstypevalue readonly: defaultsorttype nsmsgviewsorttypevalue readonly: defaultsortorder nsmsgviewsortordervalue readonly: msghdrcachesize unsigned ...
... void removeheadermdbrow(in nsimsgdbhdr msghdr); undodelete() void undodelete(in nsimsgdbhdr msghdr); markmarked() void markmarked(in nsmsgkey key, in boolean mark, in nsidbchangelistener instigator); markoffline() void markoffline(in nsmsgkey key, in ...
nsIMsgFilterCustomAction
otherwise, be careful * that the action does correct notifications to maintain counts, and correct * manipulations of both imap and local non...
...ed message to display if invalid * set to null if the actionvalue is valid */ autf8string validateactionvalue(in autf8string actionvalue, in nsimsgfolder actionfolder, in nsmsgfiltertypetype filtertype); /* allow duplicate actions in the same filter list? default no. */ attribute boolean allowduplicates; /* * the custom action itself * * generally for the apply method, folder-based methods give correct * results and are preferred if available. otherwise, be careful * that the action does correct notifications to maintain counts, and correct * manipulations of both imap and local non-database storage of message * metadata. */ /** * apply the custom actio...
nsIMsgSearchCustomTerm
*/ readonly attribute acstring id; name /// name to display in term list. this should be localized. ...
... */ readonly attribute acstring id; name /// name to display in term list. this should be localized. ...
nsIMutableArray
oid clear(); parameters none. insertelementat() insert an element at the given position, moving the element currently located in that position, and all elements in higher position, up by one. void insertelementat( in nsisupports element, in unsigned long index, in boolean weak ); parameters element the element to insert. index the position in the array: if the position is lower than the current length of the array, the elements at that position and onwards are bumped one position up. if the position is equal to the current length of the array, the new element is appended. an index lower than 0 or higher than the current length of the array is invalid and will be ignored. weak whether or not to store the element using a weak reference. exceptions thrown n...
...call removeelementat. void removeelementat( in unsigned long index ); parameters index the position of the item. replaceelementat() replace the element at the given position. void replaceelementat( in nsisupports element, in unsigned long index, in boolean weak ); parameters element the new element to insert. index the position in the array. if the position is lower than the current length of the array, an existing element will be replaced. if the position is equal to the current length of the array, the new element is appended. if the position is higher than the current length of the array, empty elements are appended followed by the new element at the specified position. an index lower than 0 is invalid and will be ignored. weak whether or not to...
nsINavHistoryContainerResultNode
avhistoryresultnode anode); attributes attribute type description childcount unsigned long the number of child nodes; accessing this throws an ns_error_not_available exception of containeropen is false. read only. ...
...when closed, attempting to call getchild() or access childcount results in an error. when you're done reading the container's children, set this to false. for host and day groupings, doing this has no performance cost since the children have already been computed. ...
nsINavHistoryQuery
don't currently support >1 annotation name per query. if annotationisnot is true, we test for the non-existance of the specified annotation. testing for not annotation will do the same thing as a normal query and remove everything that doesn't have that annotation. asking for things that do have a given annotation is a little different. it also includes things that have never been visited. this allows place queries to be returned (which might include bookmark folders -- use the bookmark service's getfolderuri) as well as anything else that may have been tagged with an annotation. this will only work for results_as_uri since there will be no visits for these items. begintime prtime begin time range for results (inclusive). begintimereference long one of the constants time_relative_* which ...
...y: 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. tags nsivariant a li...
nsINavHistoryResultObserver
o a result as the result updates itself according to bookmark and history system events. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8) note: in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1), this interface replaced the older nsinavhistoryresultviewer interface, which only allowed one client at a time. method overview void batching(in boolean atogglemode); void containerclosed(in nsinavhistorycontainerresultnode acontainernode); deprecated since gecko 2.0 obsolete since gecko 11.0 void containeropened(in nsinavhistorycontainerresultnode acontainernode); deprecated since gecko 2.0 obsolete since gecko 11.0 void containerstatechanged(in nsinavhistorycontainerresul...
...nd time for the node. anewaccesscount the new access count value for the node. nodeiconchanged() called right after a node's icon property has changed. void nodeiconchanged( in nsinavhistoryresultnode anode ); parameters anode the node whose icon has changed. nodeinserted() called when an item is inserted into a container. the item previously at the specified index (if any) and everything below it is shifted down by one. void nodeinserted( in nsinavhistorycontainerresultnode aparent, in nsinavhistoryresultnode anode, in unsigned long anewindex ); parameters aparent the container into which to insert the item. anode the node to insert into the container; it may be either a leaf or another container. anewindex the index at which to insert the item. nodekeywordchanged() calle...
nsINavHistoryResultViewer
toolkit/components/places/public/nsinavhistoryservice.idlscriptable lets nsinavhistoryresult instances notify places views of changes in the results. removed in gecko 2.0 and replaced with the nsinavhistoryresultobserver interface, which is similar but allows multiple clients to observe the result at once. 1.0 66 introduced gecko 1.9 obsolete gecko 2.0 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. note: most methods in this interface were renamed in gecko 1.9.2,...
...ontainerresultnode aparent, in nsinavhistoryresultnode anode, in unsigned long anewindex ); parameters aparent the container into which to insert the item. anode the node to insert into the container; it may be either a leaf or another container. anewindex the index at which to insert the item. remarks the item previously at the specified index (if any) as well as everything below it, is shifted down by one. sortingchanged() called when the sorting order is changed to a particular mode. for trees, this would update the column headers to reflect the altered sorting. void sortingchanged( in unsigned short sortingmode ); parameters sortingmode one of the nsinavhistoryqueryoptions.sort_by_* constants, indicating the softing mode. remarks this method is only ca...
nsIPermission
read only. ...
...xample cookies, images) from certain sites based on user preferences. netwerk/base/public/nsipermission.idlscriptable please add a summary to this article. last changed in gecko 2 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) inherits from: nsisupports attributes attribute type description capability pruint32 the 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 t...
Component; nsIPrefBranch
root on which this branch is based, such as "browser.startup." read only. constants constant value description pref_invalid 0 long pref_string 32 long data type. pref_int 64 long data type. pref_bool 128 long data type. methods addobserver() adds a preference change observer. on preference changes, the following arguments will be passed to nsiobserver.observe(): asubject - the nsiprefbranch object (this). atopic - the string defined by ns_prefbranch_prefchange_topic_id adata - the name of the preference which has changed, relative to the "root" of the asubject branch. asubject.get*pref(adata) will get the new value of the modified preference. for example, if your observer is registered with addobs...
...h to set the complex preference value. setintpref() called to set the state of an individual integer preference. void setintpref( in string aprefname, in long avalue ); parameters aprefname the integer preference to set the value of. avalue the integer value to set the preference to. unlockpref() called to unlock a specific preference. unlocking a previously locked preference allows the preference service to once again return the user set value of the preference. note: this method can be called on either a default or user branch but, in effect, always operates on the default branch. void unlockpref( in string aprefname ); parameters aprefname the preference to be unlocked. remarks registering as a preference observer can open an object to potential cyclical ref...
nsIProtocolProxyService
t 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 filter is already registered, then its position will be updated. ...
...filters register for the same position, then the filters will be visited in the order in which they were registered. if the filter is already registered, then its position will be updated. after filters have been run, any disabled or disallowed proxies will be removed from the list. a proxy is disabled if it had previously failed-over to another proxy (see getfailoverforproxy()). a proxy is disallowed, for example, if it is a http proxy and the nsiprotocolhandler for the queried uri does not permit proxying via http. if a nsiprotocolhandler disallows all proxying, then filters will never have a chance to intercept proxy requests for such urls. note: it is possible to construct filters that compete with one another in undesirable ways. this api does not attempt to protect against such probl...
nsISHEntry
key contenttype owner docshellid dynamiccreation violates the xpcom interface guidelines forgeteditordata() gets the owning pointer to the editor data assosicated with this shistory entry. this forgets its pointer, so free it when you're done. nsdocshelleditordataptr forgeteditordata(); parameters none. return value getanycontentviewer() return any content viewer present in or below this node in the nsshentry tree. this will differ from contentviewer in the case where a child nsshentry has the content viewer for this tree. nsicontentviewer getanycontentviewer( out nsishentry ownerentry ); parameters ownerentry return value getscrollposition() void getscrollposition( out long x, out long y ); parameters x y native code only!getviewerbounds saved position and ...
...tries. void setuniquedocidentifier(); parameters none. seturi() uri for the document. void seturi( in nsiuri auri ); parameters auri native code only!setviewerbounds void setviewerbounds( in nsintrect bounds ); parameters bounds syncpresentationstate() ensure that the cached presentation members are self-consistent. if either contentviewer or windowstate are null, then all of the following members are cleared/reset: contentviewer, sticky, windowstate, viewerbounds, childshells, refreshurilist. void syncpresentationstate(); parameters none. example see nssessionstore.js for a real example. ...
nsIStreamConverter
netwerk/streamconv/public/nsistreamconverter.idlscriptable provides an interface to implement when you have code that converts data from one type to another. inherits from: nsistreamlistener last changed in gecko 1.7 suppose you had code that converted plain text into html. you could implement this interface to allow everyone else to use your conversion logic using a standard api. stream converter users there are currently two ways to use a stream converter: synchronous: stream to stream. you can supply the service with a stream of type x and it will convert it to your desired output type and return a converted (blocking) stream to you. asynchronous: nsistreamlistener to nsistreamlistener. you can supply data directly to the converter by calling it's nsistreamlistener.ondat...
...ur desired output type and return converted data to you via the nsistreamlistener you passed in by calling its nsistreamlistener.ondataavailable() method. stream converter suppliers registering a stream converter: stream converter registration is a two step process. first of all the stream converter implementation must register itself with the component manager using a contractid in the format below. second, the stream converter must add the contractid to the registry. stream converter contractid format (the stream converter root key is defined in this file): @mozilla.org/streamconv;1?from=from_mime_type&to=to_mime_type method overview void asyncconvertdata(in string afromtype, in string atotype, in nsistreamlistener alistener, in nsisupports actxt); nsiinputstream convert...
nsIStyleSheetService
layout/base/nsistylesheetservice.idlscriptable please add a summary to this article. last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsisupports implemented by: @mozilla.org/content/style-sheet-service;1. ...
... agent_sheet 0 user_sheet 1 author_sheet 2 methods loadandregistersheet() synchronously loads a style sheet from sheeturi and adds it to the list of user or agent style sheets. a user sheet loaded via this api will come before usercontent.css and userchrome.css in the cascade (so the rules in it will have lower precedence than rules in those sheets). an agent sheet loaded via this api will come after ua.css in the cascade (so the rules in it will have higher precedence than rules in ua.css). the relative ordering of two user or two agent sheets loaded via this api is undefined. sheets added via this api take effect on all documents, including already-loaded ones, immediately. void loadandregistersheet...
nsIUTF8ConverterService
arset, in boolean askipcheck); autf8string converturispectoutf8(in acstring aspec, in string acharset); methods convertstringtoutf8() ensure that astring is encoded in utf-8. if not, convert to utf-8 assuming it's encoded in acharset and return the converted string in utf-8. autf8string convertstringtoutf8( in acstring astring, in string acharset, in boolean askipcheck, in boolean aallowsubstitution ); parameters astring a string to ensure its utf8ness. acharset the charset to convert from if astring is not in utf-8. askipcheck determines whether or not to skip 'asciiness' and 'utf8ness' check. 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 ...
...ess' check. 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. the most common case is the input is in 7bit non-ascii character sets like iso-2022-jp, hz or utf-7 (in its original form or a modified form used in imap folder names). aallowsubstitution when true, allow the 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 u...
nsIUpdateTimerManager
the values are: contractid the component's contract id. method the method used to instantiate the interface; this should be either getservice or createinstance, depending on your component. id the id that id...
...he values are: contractid the component's contract id. method the method used to instantiate the interface; this should be either getservice or createinstance, depending on your component. id the id that identifies the interval; this is the same id you would pass into registertimer(). preference the preference for the timer interval; this allows a preference to override the default interval. this can be an empty string if the default interval should not be overridden. interval the same interval that would be passed into registertimer(). see also nsiupdate nsiupdatechecklistener nsiupdatechecker nsiupdatepatch nsiapplicationupdateservice nsiupdatemanager nsiupdateprompt ...
NS_CStringContainerInit2
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_container_init_depend data passed into ns_cstringcontainerinit2 is not copied. instead, the string references the passed in data pointer directly. the caller must ensure that the data is valid for the lifetime of the string container. this flag should not be combined with ns_cstring_container_ini...
...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_cstringcontainerfinish ...
XPCOM ABI
d 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++ compiler ibmc - ibm c++ compiler for example: firefox built with the gnu c++ compiler 4.0.0 for the intel pentium processor would have xpcom abi of x86-gcc3 the xpcom abi string can be retrieved programmatically by using the nsixulruntime interface. to retrieve the abi of your firefox or thunderbird, open the error console (accessible through tools | error console) and evaluate the following javascript code: components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulruntime) .xpcomabi if either the cpu architecture or the c++ compiler are unknown, the application wouldn't have an xpcom abi string and attempts to get it will result in error ns_error_not_available. it would still be a distinct abi, but we just wouldn't have a nam...
Filelink Providers
staller/package-manifest.in. if the nsimsgcloudfileprovider is being created as part of an add-on, the add-on must register the component in chrome.manifest. also, you must add the component's contract id to the "cloud-file" category. see cloudfile/cloudfilecomponents.manifest for an example, as well as this document on chrome.manifest files. the account setup dialog the account setup dialog allows the user to select what account type they would like to create from a menulist. some providers require thunderbird to do very little in order to connect a user to their account. other providers however may require the user to fill in additional details in order to connect to the service. hightail, for example, requires a username and password. other services may require the user to fill in a ...
...ferences is handled automatically by the dialog code. providers need only provide an extraargs function in the iframe content which returns an object specifying the name, type, and value to save. the format for the returned object is: { field_name: {type: field_type, value: field_value} } where field_type is "int", "bool", or "char". for example, the hightail implementation provides the following function: function extraargs() { var usernamevalue = document.getelementbyid("username").value; return { "username": {type: "char", value: usernamevalue}, }; } in this example, the username value is read from the input, and then the specially-crafted object is returned. once this is done, the field is accessible from within the implementation via the preferences api using the key...
Mail event system
d. if the object wants to know about all notifications on all folders, then it should register with the mail session. nsimsgmailsession.idl is a service that acts as a broadcaster for folder notifications. the mail session receives all notifications from all folders, and then forwards it on to any nsifolderlisteners that have registered themselves. the nsimsgmailsession interface actually only allows adding and removal of listeners - the notifications happen through the nsifolderlistener interface as well. methods each event type has a two methods associated with it: notify*<event> - in the nsifolder interface, and nsimsgmailsession interface. onitem*<event> - in the nsifolderlistener interface. the mail session implements this interface. where <event> is the type of event, such a...
...gh the nsifolderlistener interface as well. methods each event type has a two methods associated with it: notify*<event> - in the nsifolder interface, and nsimsgmailsession interface. onitem*<event> - in the nsifolderlistener interface. the mail session implements this interface. where <event> is the type of event, such as boolpropertychanged or the generic event . sample control flow here is an example of a possible flow of control when a new message is added to a folder. in this example, there is a dialog open that shows properties for this folder including the message count. this dialog is a listener on this particular folder. a message is added to an nsimapmailfolder containing 4 messages. because the number of messages in the folder have increased, this change in tot...
Mailnews and Mail code review requirements
is obtained at an early stage in the patch development process. getting early ui-reviews this reduces the chance that work is rejected due to needing further user experience changes, and hence is aimed at saving time for the developer and reviewers. all patches that affect user experience or interfaces on thunderbird should have ui-review on those patches in addition to the reviews required below. to obtained a ui-review on an attachment, set ui-review to '?' and enter :bwinton (for blake winton) as the requestee. mike conley (:mconley) can also provide useful feedback, but blake is the current ultimate decider for ui choices in thunderbird. rules for all patches affecting mailnews/ and mail/ wherever possible, significant patches in a certain area should be reviewed by o...
... code is running automatically. certain build-config or tooling bugs which don't affect the actual product cannot be usefully tested. these bugs should have the in-testsuite- flag set. rubber-stamp approvals for intermittently failing ("orange") test fixes/debugging in order to make it easier to debug and fix tests that fail intermittently ("intermittent orange" tests), we have created the following two rubber-stamps based on this proposal on the tb-planning mailing list. the procedure to use these is to be sure to: include "rs=simple-orange-fix" or "rs=orange-debugging" in the first line of the commit message paste a link to the pushed commit with the rubber stamp in the bug make sure you pasted a link to any try-server pushes of the patch in the bug rs=simple-orange-fix require...
Thunderbird Binaries
releases thunderbird releases have been extensively tested and are made available for anyone to download and use it. ...
... releases thunderbird releases have been extensively tested and are made available for anyone to download and use it. ...
Building a Thunderbird extension 2: extension file layout
e code that makes your extension actually do something. ...
...you can find information about the locale/ and defaults/ folders in the more general "building an extension" documentation. ...
Building a Thunderbird extension 6: Adding JavaScript
no longer be relevant. see developer.thunderbird.net for newer information. in this step we will create a small piece of javascript code that inserts the current date into our statusbar widget. the statusbar is usually displayed at the bottom of the thunderbird 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...
...e current date, which it converts into a string that has the format of yyyy.mm.dd. 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. « pr...
Finding the code for a feature
tags are applied using the message database property "keyword". ...
...tags are applied using the message database property "keyword". ...
Activity Manager examples
.js file. if activity developers would like to extend the default ui representation of the activity types, they can provide their own xbl elements for their own activity types. all custom activity xbl elements should inherit from "activity-base" binding. for xbl samples please see activity.xml and activitybinding.css files. showing a user-defined activity in the activity manager window the following sample will show a process and an event for junk processing in the activity manager window. // step 1: adding 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"].getse...
... // 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]; .... // assuming that the initiator has some way to cancel // the...
Filter Incoming Mail
ing 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. ...
...// 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. ...
Folders and message lists
getting the current nsimsgfolder the nsimsgfolder interface contains many methods and attributes for working with folders. to get the nsimsgfolder instance for the currently-displayed folder, just use gfolderdisplay.displayedfolder. ...
...the currently-selected message(s), depending on what exactly you're trying to do: gfolderdisplay.selectedcount: returns the number of messages currently selected. gfolderdisplay.selectedmessage: returns the first currently-selected message. when using this, be sure that there's only one selected message (or that you only care about the first one). otherwise, use one of the methods described below. gfolderdisplay.selectedmessages: returns an array of nsimsgdbhdrs for the selected messages. if a collapsed thread is in there and working with collapsed threads is enabled, this will include the headers for the messages in that collapsed thread. gfolderdisplay.selectedmessageuris: returns an array of the uris corresponding to the selected messages. like selectedmessages, this also includes me...
Toolkit version format
this document is a reference for the version format, as used in firefox 1.5 (xulrunner 1.8) and later. this format is used by the extension manager, software update, and other parts of the platform. versions in at least the following places must conform to this format: addon's and target application's version in install and update manifests. the following preferences: app.extensions.version, extensions.lastappversion versions returned by nsixulappinfo. application.ini in xulrunner applications appversion flag in chrome manifests. you can use nsiversioncomparator to compare versions from your application. see older version formats below for description of the older version format used in firefox/thunderbird 1.0. version format a version string consists of one or more versio...
...on parts are compared left to right. an empty or missing version part is equivalent to 0. if at some point a version part of one version string is greater than the corresponding version part of another version string, then the first version string is greater than the other one. otherwise, the version strings are equal. note, that since missing version parts are treated as if they were 0, the following version strings are equal: 1, 1.0, 1.0., 1.0.0, and even 1.0... comparing version parts version parts are also compared left to right, parts a and c are compared as numbers, while parts b and d are compared byte-wise. a string-part that exists is always less than a string-part that doesn't exist (1.6a is less than 1.6). examples 1.-1 < 1 == 1. == 1.0 == 1.0.0 < 1.1a < 1.1aa < 1.1ab < 1.1b ...
Using the Mozilla source server
using the mozilla source server is now even more feature-packed. ...
...once the symbol path is set you must now enable source server. using the source server in windbg in the windbg command line, type .srcfix and hit enter. this enables source server support. now, when you click on a frame in the "calls" window, windbg will prompt you about running cvs to download the associated source code. if you click ...
Add to iPhoto
let's take a look at a few of the key apis we declare for core foundation, to see how it's done. cfrange cfrange is a structure that identifies a range; that is, it identifies an offset to an item in a list and a number of items. in c, the declaration looks like this: typedef struct { cfindex location; cfindex length; } cfrange; to declare this for use with js-ctypes, we use the following code: this.cfrange = new ctypes.structtype("cfrange", [ {'location': ctypes.int32_t}, {'length': ctypes.int32_t}]); this defines corefoundation.cfrange to represent this data type, comprised of two 32-bit integer fields called location and length. generic cftype routines all core foundation data types are based upon a core cftype data type. basic ...
...a constructor, created for you by js-ctypes, that creates and fills out the structure, specifying the values of all of the parameters. to specify a pointer to the fsref indicating the application to launch, we pass ref.address(), which obtains the actual memory address of the c data structure. note that so far, we haven't actually obtained a value for the fsref in question. we do that next by following these steps: create a cfstring referring to file:///applications/iphoto.app, which is iphoto's default path, using cfstringcreatewithcharacters(). create the corresponding cfurl object by calling cfurlcreatewithstring(). release the string using cfrelease(), since we're done with it. call cfurlgetfsref() to fill out the fsref structure to reference the same file as the cfurl. if that f...
Using C struct and pointers
of field descriptors. each field descriptor contains the name and field type of the corresponding field of the c struct. the call to structtype() returns a ctype object, and we then apply the new operator to it to create a specific instance of this newly defined type - a javascript representation of the c struct. using c strings with js-ctypes a pointer to char in javascript is declared as follows: var str = ctypes.pointertype(ctypes.char); now imagine you call a c function that returns a c string and you want to modify the contents of this string. in the js-ctypes context, you can only operate on buffers of known capacity. therefore, the size of the buffer must be specified. additionally, the js-ctypes pointer must be casted to reflect the size of the buffer: var ptr = ctypes.cast( st...
...nown capacity. therefore, the size of the buffer must be specified. additionally, the js-ctypes pointer must be casted to reflect the size of the buffer: var ptr = ctypes.cast( str, ctypes.arraytype( ctypes.char, buff_size ).ptr ); here buff_size is of type ctypes.size_t. once we have a ctypes char pointer that points to a buffer of known size, we modiify the contents of the memory block as follows: ptr.contents = string("hello world from javascript!!!"); string() adds the '\0' character. references this example is based on code found here. ...
Debugging Tips
printing cdata and ctype currently console.log doesn't show type information of cdata. running the following code shows only partial value information. let { ctypes } = components.utils.import("resource://gre/modules/ctypes.jsm", {}); let i = ctypes.int32_t(10); console.log(i); let point = ctypes.structtype("point", [{ x: ctypes.int32_t }, { y: ctypes.int32_t }]) let p = point(10, 20); console.log(p); let pp = p.address(); console.log(pp); the result will be as following: cdata { value: 10 } cdata { x: 10, y: 20 } cdata { contents: cdata } to see more descriptive information, you can use .tosource(). let { ctypes } = components.utils.import("resource://gre/modules/ctypes.jsm", {}); let i = ctypes.int32_t(10); console.log(i.tosource()); let point = ctypes.structtype("point", [{ ...
...e. ...
Declaring and Using Callbacks
warning: callbacks must be invoked on the same thread with which they were registered. there is no concurrency logic in js-ctypes, so invoking callbacks on other threads will cause things to crash. prerequiste understanding abi functiontype declaring callbacks a callback is declared by using ctypes.functiontype. ...
...callback() { return undefined; // as the return of the functiontype was ctypes.void_t we must return undefined or dont return at all otherwise js-ctypes will throw an error saying unexpected type } var myccallback = myfunctypedeclaration.ptr(myjscallback); using callbacks since callbacks are function pointers in c, js-ctypes has special handling for function pointer types. consider the following code: function myjscallback(foo, bar) { .... }; var functype = ctypes.functiontype(...); var funcptrtype = functype.ptr; var regularfuncptr = funcptrtype(); var callback = funcptrtype(myjscallback); js-ctypes detects that funcptrtype is a type of function pointer, and adds a special case to its constructor. in the ordinary case, invoking the type object creates a regular cdata object contai...
Declaring types
as a packed structure; that is, using #pragma pack. field descriptors each field descriptor is comprised of a field name and its data type, represented as a string and a ctype object, respectively. the format, then, looks like this: [ { field1: type1 }, { field2: type2 }, ... ...
...ttype('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 files on disk): const file = new ctypes.s...
PKCS #11 Netscape Trust Objects - Network Security Services
of trust to a certificate. examples of trust assertions are certificate authority root certificates. this document outlines the way in which nss stores trust objects via pkcs#11. this is not a new design, but documentation of the method already in use. trust objects a trust object describes a level of trust in a certificate for a given usage or purpose. conceptually a trust object contains the following: certificate reference purpose + level of trust (multiple) purpose + level of trust a trust object ultimately denotes a level of trust in a certificate. 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: unt...
...ficate. certificates in a trust chain whose issuer is trusted are referred to by the der value of the issuer field, and the serial number. pkcs#11 representation trust objects are stored as objects on a pkcs#11 token. although these are specific to a certificate, they do not need to be stored on the same token as the certificate. trust objects are of the class cko_netscape_trust and have the following attributes. trust object attributes. attribute type description cka_class ck_object_class cko_netscape_trust cka_issuer byte array der-encoding of the certificate issuer name. required for non-trust anchor objects. cka_subject byte array der-encoding of the certificate subject name. optional. cka_serial_numbe...
Browser Side Plug-in API - Plugins
_forceredraw forces a paint message for a windowless plug-in. npn_getauthenticationinfo this function is called by plug-ins to get http authentication information from the browser. npn_geturl asks the browser 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 plug-in which is associated with a given url, for example the cookies or preferred proxy. npn_invalidaterect invalidates specified drawing area prior to repainting or refreshing a windowless plug-in. npn_invalidateregion invalidates specified drawing region prior to repainting or refreshing a wi...
...n_posturl posts data to a url. npn_posturlnotify posts data to a url, and receives notification of the result. npn_pushpopupsenabledstate pushes the popups-enabled state. npn_reloadplugins reloads all plug-ins in the plugins directory. npn_requestread requests a range of bytes for a seekable stream. npn_setvalue sets windowless plug-in as transparent or opaque. npn_setvalueforurl allows a plug-in to change the stored information associated with a url, in particular its cookies. npn_status displays a message on the status line of the browser window. npn_useragent returns the browser's user agent field. npn_version returns version information for the plug-in api. npn_write pushes data into a stream produced by the plug-in and consumed by the browser. ...
Gecko Plugin API Reference - Plugins
n_forceredraw forces a paint message for a windowless plug-in. npn_getauthenticationinfo this function is called by plug-ins to get http authentication information from the browser. npn_geturl asks the browser 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 plug-in which is associated with a given url, for example the cookies or preferred proxy. npn_invalidaterect invalidates specified drawing area prior to repainting or refreshing a windowless plug-in. npn_invalidateregion invalidates specified drawing region prior to repainting or refreshing a win...
...npn_posturl posts data to a url. npn_posturlnotify posts data to a url, and receives notification of the result. npn_pushpopupsenabledstate pushes the popups-enabled state. npn_reloadplugins reloads all plug-ins in the plugins directory. npn_requestread requests a range of bytes for a seekable stream. npn_setvalue sets windowless plug-in as transparent or opaque. npn_setvalueforurl allows a plug-in to change the stored information associated with a url, in particular its cookies. npn_status displays a message on the status line of the browser window. npn_useragent returns the browser's user agent field. npn_version returns version information for the plug-in api. npn_write pushes data into a stream produced by the plug-in and consumed by the browser. scripting plugins...
Plugin Roadmap for Firefox - Plugins
ins are a security and performance problem for firefox users. npapi plugins are an obsolete technology, and mozilla has been moving toward a web which doesn't need plugins. the last remaining npapi plugin, adobe flash, has announced an end-of-life plan. to support the transition away from flash, firefox is working with other browsers to progressively and carefully make flash usage less common. below is the roadmap of past and future support for plugins in firefox. schedule june 2016 starting with firefox 47 in june 2016, all plugins other than adobe flash are click-to-activate. users choose which sites are allowed to activate each plugin. in addition, the 64-bit firefox for windows only supports the flash plugin. march 2017 starting with firefox 52 in march 2017, plugins other than ad...
...te each plugin. in addition, the 64-bit firefox for windows only supports the flash plugin. march 2017 starting with firefox 52 in march 2017, plugins other than adobe flash are no longer supported in firefox. firefox extended support release 52 will continue to support non-flash plugins until early 2018. august 2017 starting with firefox 55 in august 2017, users must choose which sites are allowed to activate the flash plugin. users will have the choice to remember the flash setting per-site. this change will be rolled out progressively during august and september 2017. in order to improve security and performance, mozilla will maintain a list of sites which cannot use any plugins. september 2017 starting with firefox 56 in september 2017, firefox for android will remove all support...
DOM Inspector - Firefox Developer Tools
this tool is an add-on for xul-based applications such as firefox and thunderbird. if you are looking for the dom inspector that's built into firefox, see the documentation for the page inspector. ...
...ector from source. getting dom inspector firefox & thunderbird you may download and install the dom inspector from the amo web site. (thunderbird users browsing amo in firefox should save the installation link, or visit the dom inspector for thunderbird page.) thunderbird 2 dom inspector for thunderbird 2 is available from thunderbird add-ons. or, build thunderbird yourself with the following options: ac_add_options --enable-extensions="default inspector" ac_add_options --enable-inspector-apis mozilla suite and seamonkey select tools > web development > dom inspector. you can install the sidebar panel via edit > preferences > advanced > dom inspector, then simply open up the inspector panel and visit a website. report a bug in dom inspector use the conveniently named "dom...
Inspecting web app manifests - Firefox Developer Tools
in this article we will look at inspecting app manifests using the firefox devtools application panel. when you open the application panel’s manifest view on a page that doesn't have an app manifest successfully deployed, you'll get the following output shown: deploying a manifest to get a manifest deployed successfully, you need to include a <link> element in the <head> of your document that points to your .webmanifest file: <link rel="manifest" href="/manifest.webmanifest"> the .webmanifest extension is recommended in the spec, and should be served with an application/manifest+json mime type, although browsers generally tend to support manifests with other appropriate extensions like .json (mime type: application/json). you also need to make sure the json inside the file is of th...
...anifest+json mime type, although browsers generally tend to support manifests with other appropriate extensions like .json (mime type: application/json). you also need to make sure the json inside the file is of the correct format. you can test this using the web manifest validator. inspecting your manifest if your manifest is deployed successfully, you should end up with a display like the following on the manifest view: from here, you can inspect all the information in the manifest in an easy-to-digest way, making sure that it is all correct. it provides a link to the manifest file at the top which when clicked on brings up the json in a new tab. it also loads all the icon files into the view, so you can see the relative size of them all, and any other information associated with the...
Examine, modify, and watch variables - Firefox Developer Tools
r the variables that are displayed, either by using the "*" modifier in the script filter, or by typing into the filter variables box, if you have enabled this in the debugger settings. if a variable exists in the source but has been optimized away by the javascript engine, then it is shown in the variables view, but is given the value (optimized away), and is not editable. 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 exp...
...ugh code. then start running your code. the watch expression does nothing until you begin to step through your code, so nothing happens until you reach a breakpoint. at that point, a box showing your active watch expressions and their current values will appear: you can step through your code, watching the value of the expression as it changes; each time it does, the box will flash briefly yellow. you can remove a watch expression by clicking the "x" icon next to it, and, of course, you can have more than one watch expression at a time. ...
Using the Debugger map scopes feature - Firefox Developer Tools
this feature is useful when debugging source-mapped code. it enables you to see the variables from the original source. it’s also possible to inspect variables from the generated scopes (e.g., a bundle file with all concatenated module files). let's take a look at how this works. if you want to follow along, use this example. open the example page and then open the debugger using tools > web developer > debugger (or press ctrl + i and then select the debugger). ...
.... open the example page and then open the debugger using tools > web developer > debugger (or press ctrl + i and then select the debugger). select the "bundle.js" file in the sources panel on the left and then set a breakpoint at line 102 in the increment function. when you click the increment button on the page and hit the breakpoint, an additional section is added to the right-hand panel below the call stack to display variables mapped from the original scope, like this: as useful as this is, it would be even nicer if you could view the original code (before it was packages into the "bundle.js" file. right-click on the source code and the context menu now includes an option to jump to original location as shown below. click jump to original location. the debugger opens ...
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
the devtools.chrome.enabled preference to true: setting the 'devtools.chrome.enabled' preference open a developer scratchpad (menu button > developer > scratchpad), and select "browser" from the "environment" menu. (this menu will not be present unless you have changed the preference as explained above.) selecting the 'browser' context in the scratchpad enter the following code in the scratchpad: // this simply defines the 'debugger' constructor in this // scratchpad; it doesn't actually start debugging anything. components.utils.import('resource://gre/modules/jsdebugger.jsm'); adddebuggertoglobal(window); (function () { // the debugger we'll use to observe a tab's allocation. var dbg; // start measuring the selected tab's main window's memory // co...
...andchildren] of children) walk(child, grandchildren, indent + ' '); } walk(null, rootchildren, ''); } })(); in the scratchpad, ensure that no text is selected, and press the "run" button. (if you get an error complaining that components.utils is not defined, be sure you've selected browser from the scratchpad's environment menu, as described in step 2.) save the following html text to a file, and visit the file in your browser. make sure the current browser tab is displaying this page. <div onclick="dodivsandspans()"> click here to make the page do some allocations. </div> <script> function makefactory(type) { return function factory(content) { var elt = document.createelement(type); elt.textcontent = content; return elt; }; ...
Tutorial: Set a breakpoint - Firefox Developer Tools
, open the firefox developer tools, click on the options gear at the upper right of the toolbox, and make sure that both “enable browser chrome and add-on debugging toolboxes” and “enable remote debugging” are checked. these are located at the bottom right of the options panel; you may need to scroll to see them. once they’re checked, you can close the developer tools. save the following text to an html file: <div onclick="report('the best div');">click me!</div> <div onclick="report('another great div');">or me!</div> <script> function report(what) { console.log('clicked: ' + what); } </script> visit the html file in your browser, and open the browser content toolbox by opening the firefox menu, choosing “web developer”, and then “browser content toolbox”. ...
...nel, which is not enabled by default. to enable it, click on the options gear at the upper right of the browser content toolbox, and make sure the “scratchpad” box in the “default developer tools” section the left is checked. the scratchpad panel should appear at the top of the toolbox alongside the console, debugger, and memory panels. click on the scratchpad panel and enter the following code: components.utils.import("resource://gre/modules/jsdebugger.jsm"); components.utils.import("resource://gre/modules/console.jsm"); // this simply defines 'debugger' in this scratchpad; // it doesn't actually start debugging anything. adddebuggertoglobal(this); // create a 'debugger' instance. var dbg = new debugger; // make the tab's top window a debuggee, and get a // debugger.objec...
Debugger-API - Firefox Developer Tools
e objects and primitives, but also stack frames, environments, scripts, and compilation units, which are not normally accessible as objects in their own right. here is a javascript program in the process of running a timer callback function: a running javascript program and its debugger shadows this diagram shows the various types of shadow objects that make up the debugger api (which all follow some general conventions): a debugger.object represents a debuggee object, offering a reflection-oriented api that protects the debugger from accidentally invoking getters, setters, proxy traps, and so on. a debugger.script represents a block of javascript code—either a function body or a top-level script. given a debugger.script, one can set breakpoints, translate between source po...
...a debugger.source can furnish a full copy of its source code, and explain how the code entered the system, whether via a call to eval, a <script> element, or otherwise. a debugger.script points to the debugger.source from which it is derived. also omitted is the debugger’s debugger.memory instance, which holds methods and accessors for observing the debuggee’s memory use. all these types follow some general conventions, which you should look through before drilling down into any particular type’s specification. all shadow objects are unique per debugger and per referent. for a given debugger, there is exactly one debugger.object that refers to a particular debuggee object; exactly one debugger.frame for a particular stack frame; and so on. thus, a tool can store metadata about a shad...
Aggregate view - Firefox Developer Tools
nts: such as htmlspanelement or window strings: listed as "strings" javascript sources: listed as "jsscript" internal objects: such as "js::shape". these are prefixed with "js::". each type gets a row in the table, and rows are ordered by the amount of memory occupied by objects of that type. for example, in the screenshot above you can see that javascript objects account for most memory, followed by strings. the "total count" column shows you the number of objects of each category that are currently allocated. the "total bytes" column shows you the number of bytes occupied by objects in each category, and that number as a percentage of the whole heap size for that tab. the screenshots in this section are taken from a snapshot of the monster example page. for example, in the scr...
...t account for 15% of the total heap. next to the type's name, there's an icon that contains three stars arranged in a triangle: click this to see every instance of that type. for example, the entry for array tells us that there are four array objects in the snapshot. if we click the star-triangle, we'll see all four array instances: for each instance, you can see the retained size and shallow size of that instance. in this case, you can see that the first three arrays have a fairly large shallow size (5% of the total heap usage) and a much larger retained size (26% of the total). on the right-hand side is a pane that just says "select an item to view its retaining paths". if you select an item, you'll see the retaining paths panel for that item: call stack the call stack show...
Dominators - Firefox Developer Tools
these concepts matter in memory analysis, because often an object may itself be small, but may hold references to other much larger objects, and by doing this will prevent the garbage collector from freeing that extra memory. you can see the dominators in a page using the dominators view in the memory tool. with a garbage-collected language, like javascript, the programmer doesn't generally have to worry about deallocating memory. ...
...reachable, and can be deallocated. so when an object becomes unreachable (for example, because it is only referenced by a single local variable which goes out of scope) then any objects it references also become unreachable, as long as no other objects reference them: conversely, this means that objects are kept alive as long as some other reachable object is holding a reference to them. shallow and retained size this gives rise to a distinction between two ways to look at the size of an object: shallow size: the size of the object itself retained size: the size of the object itself, plus the size of other objects that are kept alive by this object often, objects will have a small shallow size but a much larger retained size, through the references they contain to other objects. r...
Throttling - Firefox Developer Tools
the network monitor allows you to throttle your network speed to emulate various 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. 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. the speeds are expressed in multiples of bits per second. sele...
...gprs 50 kbps 20 kbps 500 regular 2g 250 kbps 50 kbps 300 good 2g 450 kbps 150 kbps 150 regular 3g 750 kbps 250 kbps 100 good 3g 1.5 mbps 750 kbps 40 regular 4g/lte 4 mbps 3 mbps 20 dsl 2 mbps 1 mbps 5 wi-fi 30 mbps 15 mbps 2 network monitor features the following articles cover different aspects of using the network monitor: toolbar network request list network request details network traffic recording performance analysis ...
Network monitor toolbar - Firefox Developer Tools
the network monitor provides two toolbar areas, one above the main section, and another below. toolbar the toolbar is at the top of the main network monitor window. (prior to firefox 77, this toolbar was arranged somewhat differently.) it provides: an icon to clear the network request list. a box enabling you to filter requests by url and by properties. a set of tool icons: pause (or resume) recording network log search the log request blocking an array of buttons to filter the network request list by type: by the content type of the response xhr requests websocket upgrades and messages (labeled ws) other requests a checkbox that allows you to disable caching. throttling menu, to simulate various connection types a menu of other actions: ...
... of the network log as a har file with the extension .har. copy all as har copies the current contents of the network log to the clipboard in har format. ...
Network monitor recording - Firefox Developer Tools
the pause button. pausing and resume network traffic recording the network monitor has a button that pauses and resumes recording of the current page's network traffic. this is useful in situations where, for example, you are trying to get a stable view of a page for debugging purposes, but under normal circumstances the view keeps evolving due to persistent network requests. ...
...istent network requests. the pause button allows you to look at a certain snapshot. the button can be found at the far left of the main network monitor toolbar, and looks like a typical pause button — . you can see it here in context: once pressed, the button changes to a play icon, and you can toggle network traffic recording back on by pressing it again. ...
CSS Flexbox Inspector: Examine Flexbox layouts - Firefox Developer Tools
the flexbox inspector allows you to examine css flexbox layouts using the firefox devtools, which is useful for discovering flex containers on a page, examining and modifying them, debugging layout issues, and more. 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. in the infobar when you hover over an element in the html pane, you will see a tooltip that gives you more information about the el...
...e "flex container" section. if you expand the section without selecting a flexbox container, it will only display the message, "select a flex container or item to continue". once you select an element whose display is defined as flex, the panel will include a number of options for viewing details about the flex container and flex items within it. you can find out more about those in the section below. note: the layout view can be found underneath the layout tab on the right-hand pane of the page inspector. the above and below screenshots should give you further hints on how to get to this. flex container options the flex container section of the layout view looks like this: there are two settings you can change in the flex container section: you can control the color of the overlay...
Use the Inspector API - Firefox Developer Tools
attributes and functions: .selection - information about the inspector's selection: .isnode() - returns true if selection is node. .node - returns the actual element from the page .window - the window object of the frame the selection is in. .markdirty() - marks that the page has been changed by the inspector - a warning will be shown when leaving the page, since changes made through the inspector are rewritten on reload. bindable events using on: markuploaded called when the left panel has been refreshed, after page change. ...
....markdirty() - marks that the page has been changed by the inspector - a warning will be shown when leaving the page, since changes made through the inspector are rewritten on reload. bindable events using on: markuploaded called when the left panel has been refreshed, after page change. ready called on first markuploaded. pseudoclass called after toggle of a pseudoclass. layout-change "low-priority change event for things like paint and resize." ...
Work with animations - Firefox Developer Tools
hronized along a timeline, with a draggable widget you can use to move to any point in the timeline and see the page at that point. 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. the box below contains a grayscale icon, representing firefox developer edition. if you click the icon, it enlarges and changes to color, and the name of the browser appears. click the icon again to reverse the effect. these animations are made using the web animations api. let's use the animation inspector to see what's going on in this example. right-click in the box and select "inspect element" make...
...con, to indicate that only some of the relevant properties are being optimized by the compositor. the bar tooltip also includes this information, as a further reminder. you'll get a message of "some animation properties are optimized." properties whose animation is not being optimized, but could be if you improved your code, are now given a dotted underline — see transform in the screenshot below. hovering over this gives you a tooltip that explains why. in this case, the message is "animations of 'transform' cannot be run on the compositor when geometric properties are animated on the same element at the same time." edit @keyframes any @keyframes rules associated with the currently selected element are displayed in the rules view and are editable: edit timing functions when you ...
UI Tour - Firefox Developer Tools
way you can select an element for inspection: note that it's actually part of the main toolbox toolbar, so it's immediately accessible from any tool, not just the inspector. to learn how to select an element, see the guide to selecting an element. html pane the inspector is split into two or three sections, depending on your settings. you can toggle the 3-pane view of the inspector. ...
...e sections, depending on your settings. you can toggle the 3-pane view of the inspector. the following image shows the 2-pane layout: in 2-pane mode, the inspector includes the html pane, and the css pane, which can contain one of six tools: rules view layout view computed view changes view compatibility view (firefox developer edition 77 and later) fonts view animations view the following image shows the 3-pane mode (available from firefox 62 onwards) which moves the css rules view 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 al...
Call Tree - Firefox Developer Tools
he number of samples taken in which we were executing a particular function corresponds to the amount of time the browser spent executing it. in this article, we'll use the output of a simple program as an example. if you want to get the program to experiment with your profile, you can find it here. you can find the specific profile we discuss here - just import it to the performance tool to follow along. there's a short page describing the structure of this program here. note that we use the same program - the same profile, in fact - in the documentation page for the flame chart. the screenshot below shows the output of a program that compares three sorting algorithms - bubble sort, selection sort, and quicksort. to do this, it generates some arrays filled with random integers and sort...
...o this, it generates some arrays filled with random integers and sorts them using each algorithm in turn. we've zoomed into the part of the recording that shows a long javascript marker: the call tree presents the results in a table. each row represents a function in which at least one sample was taken, and the rows are ordered by the number of samples taken while in that function, highest to lowest. samples is the number of samples that were taken when we were executing this particular function, including its children (the other functions called by this particular function). total time is that number translated into milliseconds, based on the total amount of time covered by the selected portion of the recording. these numbers should roughly be the same as the number of samples. total ...
Sorting algorithms comparison - Firefox Developer Tools
iteratively (200 iterations) generates a randomized array and calls sort(). ...
...of course, you can generate your own profile, too, but the numbers will be a little different. ...
Intensive JavaScript - Firefox Developer Tools
this means that long-running javascript functions can block the thread, leading to an unresponsive page and a bad user experience. you can use the frame rate and waterfall tools to see when javascript is causing performance problems, and to single out the particular functions that need attention. in this article we'll take an example site whose long-running javascript causes responsiveness problems, and apply two different approaches to fixing them. ...
...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 collapses completely whenever we press the bu...
UI Tour - Firefox Developer Tools
corded operations are color-coded using the same scheme as in the main waterfall view. frame rate graph the frame rate gives you 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. ...
...to switch to a different tool, use the buttons in the toolbar. ...
IndexedDB - Firefox Developer Tools
when you select an origin inside the indexed db storage type in the storage tree of the storage inspector, a table lists the details of all the databases present for that origin. note: the data shown in an indexeddb database is a snapshot of the data as it was when you opened the storage inspector tool. databases have the following details: database name — the name of the database. storage — the storage type specified for the database. ...
...ils: database name — the name of the database. storage — the storage type specified for the database. origin — the origin of the database. version — the database version. object stores — the number of object stores in the database. when an indexeddb database is selected in the storage tree, details about all the object stores are listed in the table. any object store has the following details: object store name — the name of the object store. key — the keypath property of the object store. auto increment — is automatic incrementation of the keys enabled? indexes — array of indexes present in the object store as shown below. when an object store is selected in the storage tree, all the items in that object store are listed in the table. all items have a key...
Storage Inspector - Firefox Developer Tools
cookies — all the cookies created by the page or any iframes inside of the page. cookies created as a part of response of network calls are also listed, but only for calls that happened while the tool is open. indexeddb — all indexeddb databases created by the page or any iframes inside the page, their object stores and the items stored in these object stores. ...
...oo": "bar"}' is shown as the origin json: {foo: "bar"}. a string containing a key separated value, like "1~2~3~4" or "1=2=3=4" is shown like an array: [1, 2, 3, 4]. ...
Taking screenshots - Firefox Developer Tools
e taking the screenshot, or specify your own file name, starting in firefox 62 you can use the :screenshot helper function in the web console. type :screenshot in the web console to create a screenshot of the current page. by default, the image file will be named screen shot yyy-mm-dd at hh.mm.ss.png. tip: you could type :s and then hit tab to autocomplete :screenshot. the command has the following optional parameters: command type description --clipboard boolean when present, this parameter will cause the screenshot to be copied to the clipboard. prevents saving to a file unless you use the --file option to force file writing. --delay number the number of seconds to delay before taking the screenshot; you can use an interger or floating poin...
...n to force file writing. --delay number the number of seconds to delay before taking the screenshot; you can use an interger or floating point number. this is useful if you want to pop open a menu or invoke a hover state for the screenshot. --dpr number the device pixel ratio to use when taking the screenshot. values above 1 yield "zoomed-in" images, whereas values below 1 create "zoomed-out" images. --file boolean when present, the screenshot will be saved to a file, even if other options (e.g. --clipboard) are included. --filename string the name to use in saving the file. the file should have a ".png" extension. --fullpage boolean if included, the full webpage will be saved. with this parameter, even the parts of th...
Toolbox - Firefox Developer Tools
a particular tool, to dock/float the window, and to close the window. node picker on the far left there's a button to activate the node picker. this lets you select a page element for inspection. see "selecting elements". toolbox-hosted tools then there is an array of labeled buttons which enables you to switch between the different tools hosted by the toolbox. ...
...not the firefox instance that launched the window, not all the hosted tools will be shown). extra tools next there's an array of buttons that can be added or removed in the developer tool settings. by default this array includes: toggle split console responsive design mode select a frame as the currently targeted document (this is only included by default from firefox 41 onwards). ...
Validators - Firefox Developer Tools
. tune-up wizard links back to devedge if you're writing new code that isn't validating immediately, see the available standards-compliant authoring and development tools. firefox extensions for validation quick reference sidebar tabs install devedge toolbox sidebars for quick access to web development references. checky checky adds a submenu to your netscape or mozilla context menu that allows you to run whatever page you're on through one of (currently) 18 different online validaton and analysis services. applications and services devedge web tune-up wizard this interface to w3c services guides beginning-to-intermediate web authors through the process of updating content to support netscape 7.x, mozilla and other browsers that support w3c standards. w3c html validator the w3c ht...
...at web pages for better reading. (some authoring software, such as html-kit, builds in html tidy which makes validation quick and easy.) html validator pro this is an automated html5 checker using the same validator as the w3c. provide a starting url and the tool will find and validate all pages in a website. accessibility services lynx viewer checks a web page using lynx visualization and allows validation of accessibility features original document information last updated date: august 16th, 2002 copyright © 2001-2003 netscape. ...
Rich output - Firefox Developer Tools
ects, 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 triangle, and the object will be exp...
...e messages to clipboard: this will copy all of the output to the clipboard. then you can paste it into a document. the output will look something like this: console.log(todolist) array(4) [ {…}, {…}, {…}, {…} ] debugger eval code:1:9 undefined if you expand objects, such as arrays, you get slightly different content. ...
about:debugging (before Firefox 68) - Firefox Developer Tools
nwards, the reload button is only enabled for temporary add-ons. it will be disabled for all other add-ons. tabs in firefox 49 onwards, a tabs page is available in about:debugging — this provides a complete list of all the debuggable tabs open in the current firefox instance. each tab entry has a debug button next to it — when clicked, this will open up a toolbox specific to that tab, allowing you to debug that tab's contents. note that this feature isn't that immediately useful to debugging desktop tabs — you can open up a toolbox to debug a tab easily enough already — but this will become far more useful when about:debugging starts to support remote debugging, and this page can begin to list tabs available for debugging on mobile device browsers, simulators, etc. see bug 1...
...gging desktop tabs — you can open up a toolbox to debug a tab easily enough already — but this will become far more useful when about:debugging starts to support remote debugging, and this page can begin to list tabs available for debugging on mobile device browsers, simulators, etc. see bug 1212802 for the latest on this work. workers the workers page shows your workers, categorised as follows: all registered service workers all registered shared workers other 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 from firefox 52, the list of service workers shows the state of the service worker in its lifecycle. three states are distinguished: "regis...
AbortController.abort() - Web APIs
the abort() method of the abortcontroller interface aborts a dom request (e.g. a fetch request) before it has completed. this is able to abort fetch requests, consumption of any response body, and streams. syntax controller.abort(); parameters none. return value void. examples in the following snippet, we aim to download a video using the fetch api. ...
...lue void. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvide...
AbortController.signal - Web APIs
the signal read-only property of the abortcontroller interface returns an abortsignal object instance, which can be used to communicate with/abort a dom request as desired. syntax var signal = abortcontroller.signal; value an abortsignal object instance. examples in the following snippet, we aim to download a video using the fetch api. ...
... instance. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvide...
AbortController - Web APIs
the abortcontroller interface represents a controller object that allows you to abort one or more web requests as and when desired. you can create a new abortcontroller object using the abortcontroller.abortcontroller() constructor. communicating with a dom request is done using an abortsignal object. constructor abortcontroller() creates a new abortcontroller object instance. properties abortcontroller.signal read only returns a abortsignal object instance, which can be used to communicate with/abort a dom request. methods abortcontroller.abort() aborts a dom request before it has completed. this is able to abort fetch requests, consumption of any response body, and streams. examples in the following snippet, we aim to download a video using the fetch api. w...
... streams. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvide...
Animation.finish() - Web APIs
Web › API › Animation › finish
gth of the animation sequence, and if the animation is playing in reverse (having had its reverse() method called), it sets the playback time to 0. syntax animation.finish(); parameters none. return value none. exceptions invalidstate the player's playback rate is 0 or the animation's playback rate is greater than 0 and the end time of the animation is infinity. ...
... elem.getanimations().foreach( function(animation){ return animation.finish(); } ); specifications specification status comment web animationsthe definition of 'finish()' in that specification. ...
Animation.playbackRate - Web APIs
cking on the cake causes her to "grow," playing alicechange forwards again: var growalice = function() { alicechange.playbackrate = 1; alicechange.play(); } // on tap or click, alice will grow. ...
...ce = function() { alicechange.playbackrate = 1; alicechange.play(); } // on tap or click, alice will grow. ...
Animation.updatePlaybackRate() - Web APIs
rent playback position, ensuring that the resulting change in speed does not produce a sharp jump. after calling updateplaybackrate() the animation's playbackrate is not immediately updated. it will be updated once the animation's ready promise is resolved. syntax animation.updateplaybackrate(2); parameters playbackrate the new speed to set. ...
... syntax animation.updateplaybackrate(2); parameters playbackrate the new speed to set. this may be a positive number (to speed up or slow down the animation), a negative number (to make it play backwards), or zero (to effectively pause the animation). return value none. examples a speed selector component would benefit from smooth updating of updateplaybackrate(), as demonstrated below: speedselector.addeventlistener('input', evt => { cartoon.updateplaybackrate(parsefloat(evt.target.value)); cartoon.ready.then(() => { console.log(`playback rate set to ${cartoon.playbackrate}`); }); }); specifications specification status comment web animationsthe definition of 'updateplaybackrate()' in that specification. 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...
...ring 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 multiplied by the iteration count. localtime the c...
Attr.localName - Web APIs
Web › API › Attr › localName
the attr.localname read-only property returns the local part of the qualified name of an attribute. in previous dom specifications this api was defined within the node interface. syntax name = attribute.localname return value a domstring representing the local part of the attribute's qualified name. example the following example shows "id" in an alert dialog. html content <button id="example">click me</button> javascript content const element = document.queryselector("#example"); element.addeventlistener("click", function() { const attribute = element.attributes[0]; alert(attribute.localname); }); notes the local name of an attribute is the part of the attribute's qualified name that comes after the colon. qualified names are typically used in xml as part of the namesp...
...n. qualified names are typically used in xml as part of the namespace(s) of the particular xml documents. note: in gecko 1.9.2 and earlier, the property returns the upper-cased version of the local name for html attributes in html doms (as opposed to xhtml attributes in xml doms). in later versions, in compliance with html5, the property returns in the case of the internal dom storage, which is lower case for both html attributes in html doms and xhtml attributes in xml doms. specifications specification status comment domthe definition of 'attr.localname' in that specification. living standard initial definition ...
AudioBuffer() - Web APIs
the audiobuffer constructor of the web audio api creates a new audiobuffer object. syntax var audiobuffer = new audiobuffer(options); parameters inherits parameters from the audionodeoptions dictionary. options options are as follows: length: the size of the audio buffer in sample-frames. to determine the length to use for a specific number of seconds of audio, use numseconds * samplerate. numberofchannels: the number of channels for the buffer. the default is 1, and all user agents are required to support at least 32 channels. ...
...f audio, use numseconds * samplerate. numberofchannels: the number of channels for the buffer. the default is 1, and all user agents are required to support at least 32 channels. samplerate: the sample rate in hz for the buffer. the default is the sample rate of the context used in constructing this object. user agents are required to support sample rates from 8,000 hz to 96,000 hz (but are allowed 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 nomi...
AudioBuffer - Web APIs
odeaudiodata() method, or from raw data using audiocontext.createbuffer(). 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 fl...
...a float32array containing the pcm data associated with the channel, defined by the channel parameter (with 0 representing the first channel). audiobuffer.copyfromchannel() copies the samples from the specified channel of the audiobuffer to the destination array. audiobuffer.copytochannel() copies the samples to the specified channel of the audiobuffer, from the source array. example the following simple example shows how to create an audiobuffer and fill it with random white noise. you can find the full source code at our webaudio-examples repository; a running live version is also available. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create an empty three-second stereo buffer at the sample rate of the audiocontext var myarraybuffer = audioctx.createb...
AudioBufferSourceNode.start() - Web APIs
e time within the audio buffer that playback should begin. for example, to start playback halfway through a 10-second audio clip, offset should be 5. the default value, 0, will begin playback at the beginning of the audio buffer, and offsets past the end of the audio which will be played (based on the audio buffer's duration and/or the loopend property) are silently clamped to the maximum value allowed. the computation of the offset into the sound is performed using the sound buffer's natural sample rate, rather than the current playback rate, so even if the sound is playing at twice its normal speed, the midway point through a 10-second audio buffer is still 5. duration optional the duration of the sound to be played, specified in seconds. if this parameter isn't specified, the sound plays...
...e time parameters. please don't attempt to tamper with the laws of temporal physics. invalidstateerror start() has already been called. you can only call this function once during the lifetime of an audiobuffersourcenode. examples the most simple example just starts the audio buffer playing from the beginning — you don't need to specify any parameters in this case: source.start(); the following more complex example will, 1 second from now, start playing 10 seconds worth of sound starting 3 seconds into the audio buffer. source.start(audioctx.currenttime + 1,3,10); for a more complete example showing start() in use, check out our audiocontext.decodeaudiodata() example, you can also run the code example live, or view the source. specifications specification status ...
AudioBufferSourceNode - Web APIs
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. ...
...al audiobuffers can be reused for multiple plays of the sound. indeed, you can use these nodes in a "fire and forget" manner: create the node, call start() to begin playing the sound, and don't even bother to hold a reference to it. it will automatically be garbage-collected at an appropriate time, which won't be until sometime after the sound has finished playing. multiple calls to stop() are allowed. the most recent call replaces the previous one, if the audiobuffersourcenode has not already reached the end of the buffer. number of inputs 0 number of outputs 1 channel count defined by the associated audiobuffer constructor audiobuffersourcenode() creates and returns a new audiobuffersourcenode object. an audiobuffersourcenode can be insta...
AudioContext.createMediaStreamTrackSource() - Web APIs
ia() is used to request access 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 = t...
...ntext'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 audiocontext(); let source = audioctx.createmediastreamsource(stream); let biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 3000; biquadfilter.gain.value = 20; source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); }) .catch(function(err) { // handle getusermedia() error }); specifications specification status comment web audio apithe definition of 'createmediastreamtracksource()' in that specification. working draft ...
AudioContextLatencyCategory - Web APIs
the audiocontextlatencycategory type is an enumerated set of strings which are used to select one of a number of default values for acceptable maximum latency of an audio context. by using these strings rather than a numeric value when specifying a latency to a audiocontext, you can allow the user agent to select an appropriate latency for your use case that makes sense on the device on which your content is being used. audiocontextlatencycategory can be used when constructing a new audiocontext by passing one of these values as the latencyhint option in the audiocontext() constructor's options dictionary. values value description "balanced" the user agent should balance audio output latency and power consumption when selecting a latency value. "...
...options dictionary. values value description "balanced" the user agent should balance audio output latency and power consumption when selecting a latency value. "interactive" the audio is involved in interactive 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 specifica...
AudioNode - Web APIs
Web › API › AudioNode
de: an audio source (e.g. an html <audio> or <video> element, an oscillatornode, etc.), the audio destination, intermediate processing module (e.g. ...
...e way channels must be matched between the node's inputs and outputs. audionode.channelinterpretation represents an enumerated value describing the meaning of the channels. this interpretation will define how audio up-mixing and down-mixing will happen. the possible values are "speakers" or "discrete". methods also implements methods from the interface eventtarget. audionode.connect() allows us to connect the output of this node to be input into another node, either as audio data or as the value of an audioparam. audionode.disconnect() allows us to disconnect the current node from another one it is already connected to. example this simple snippet of code shows the creation of some audio nodes, and how the audionode properties and methods can be used. you can find examples of s...
AudioParam.setTargetAtTime() - Web APIs
ards at the given start time. starttime the time that the exponential transition will begin, in the same time coordinate system as audiocontext.currenttime. if it is less than or equal to audiocontext.currenttime, the parameter will start changing immediately. timeconstant the time-constant value, given in seconds, of an exponential approach to the target value. the larger this value is, the slower the transition will be. returns a reference to this audioparam object. some older browser implementations of this interface return void. description the change starts at the time specified in starttime and exponentially moves towards the value given by the target parameter. the decay rate as defined by the timeconstant parameter is exponential; therefore the value will never reach target c...
...t bringing you another 63.2% toward the target value. you don't have to worry about reaching the target value; once you are close enough, any further changes will be imperceptible to a human listener. depending on your use case, getting 95% toward the target value may already be enough; in that case, you could set timeconstant to one third of the desired duration. for more details, check the following table on how the value changes from 0% to 100% as the time progresses. time since starttime value 0 * timeconstant 0% 0.5 * timeconstant 39.3% 1 * timeconstant 63.2% 2 * timeconstant 86.5% 3 * timeconstant 95.0% 4 * timeconstant 98.2% 5 * timeconstant 99.3% n * timeconstant 1-e-n1 -...
AudioProcessingEvent - Web APIs
the web audio api audioprocessingevent represents events that occur when a scriptprocessornode input buffer is ready to be processed. note: as of the august 29 2014 web audio api spec publication, this feature has been marked as deprecated, and is soon to be replaced by audioworklet. properties the list below includes the properties inherited from its parent, event. 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 does the event normally bubble? cancelable read only boolean is it possible to cancel the event? playbacktime read only double the time when the a...
...of the onaudioprocess function. outputbuffer read only audiobuffer the buffer where the output audio data should be written. the number of channels is defined as a parameter, numberofoutputchannels, of the factory method audiocontext.createscriptprocessor(). note the the returned audiobuffer is only valid in the scope of the onaudioprocess function. example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through ea...
AudioWorkletProcessor() - Web APIs
ed code. instead, they are created only internally by the creation of an associated audioworkletnodes. var processor = new audioworkletprocessor(options); parameters options an object that is passed as options parameter to audioworkletnode constructor and passed through the structured clone algorithm. the object is based on audioworkletnodeoptions dictionary. available properties are as follows: numberofinputs optional the value to initialize the numberofinputs property to. defaults to 1. numberofoutputs optional the value to initialize the numberofoutputs property to. defaults to 1. outputchannelcount optional an array defining the number of channels for each output. for example, outputchannelcount: [n, m] specifies the number of channels in the first output to be n and the sec...
...nce under someusefulvariable key. we don't pass numberofinputs and see how it gets its default value. const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('test-processor.js') const testnode = new audioworkletnode(audiocontext, 'test-processor', { processoroptions: { someusefulvariable: new map([[1, 'one'], [2, 'two']]) } }) the console output will be as follows: > 1 // audioworkletnode options.numberofinputs set to default > map(2) {1 => "one", 2 => "two"} // a cloned map under someusefulvariable specifications specification status comment web audio apithe definition of 'audioworkletprocessor()' in that specification. working draft initial definition. ...
BaseAudioContext.createBiquadFilter() - Web APIs
for a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
... working draft ...
BaseAudioContext - Web APIs
audiocontext respectively. you wouldn't use baseaudiocontext directly — you'd use its features via one of these two inheriting interfaces. a baseaudiocontext can be a target of events, therefore it implements the eventtarget interface. ...
...s also implements methods from the interface eventtarget. baseaudiocontext.createanalyser() creates an analysernode, which can be used to expose audio time and frequency data and for example to create data visualisations. baseaudiocontext.createbiquadfilter() creates a biquadfilternode, which represents a second order filter configurable as several different common filter types: high-pass, low-pass, band-pass, etc baseaudiocontext.createbuffer() creates a new, empty audiobuffer object, which can then be populated by data and played via an audiobuffersourcenode. baseaudiocontext.createbuffersource() creates an audiobuffersourcenode, which can be used to play and manipulate audio data contained within an audiobuffer object. audiobuffers are created using audiocontext.createbuffer ...
BasicCardResponse.billingAddress - Web APIs
of the basiccardresponse dictionary contains the billing address of the card used to make the payment. syntax "billingaddress" : paymentaddress value a paymentaddress object representing the billing address of the card. example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. ...
...sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '99...
BasicCardResponse.cardNumber - Web APIs
the cardnumber property of the basiccardresponse dictionary contains the number of the card used to make the payment. syntax "cardnumber" : "number" value a domstring representing the credit card number. example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. ...
...sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '99...
BasicCardResponse.cardSecurityCode - Web APIs
e cardsecuritycode property of the basiccardresponse dictionary contains the security code of the card used to make the payment. syntax "cardsecuritycode" : "number" value a domstring representing the card security code. example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. ...
...sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '99...
BasicCardResponse.cardholderName - Web APIs
er property of the basiccardresponse dictionary contains the cardholder name of the card used to make the payment. syntax name = basiccardresponse.cardholdername; value a domstring indicating the name of the cardholder. example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. ...
...sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '99...
BasicCardResponse.expiryMonth - Web APIs
siccardresponse dictionary contains the expiry month of the card used to make the payment. syntax "expirymonth" : "number" value a domstring representing the card expiry month as a two-digit number in the range 01 to 12. example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. ...
...sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '99...
BasicCardResponse.expiryYear - Web APIs
ccardresponse dictionary contains the expiry year of the card used to make the payment. syntax "expiryyear" : "number" value a domstring representing the card expiry year as a four-digit number in the range 0000 to 9999. example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. ...
...sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '99...
BeforeInstallPromptEvent - Web APIs
the beforeinstallpromptevent is fired at the window.onbeforeinstallprompt handler before a user is prompted to "install" a web site to a home screen on mobile. this interface inherits from the event interface. ...
...llpromptevent() creates a new beforeinstallpromptevent. properties inherits properties from its parent, event. beforeinstallpromptevent.platforms read only returns an array of domstring items containing the platforms on which the event was dispatched. this is provided for user agents that want to present a choice of versions to the user such as, for example, "web" or "play" which would allow the user to chose between a web version or an android version. beforeinstallpromptevent.userchoice read only returns a promise that resolves to a domstring containing either "accepted" or "dismissed". methods beforeinstallpromptevent.prompt() allows a developer to show the install prompt at a time of their own choosing. this method returns a promise. example window.addeventlistener(...
BiquadFilterNode.Q - Web APIs
am, a double representing a q factor, or quality factor. it is a dimensionless value with a default value of 1 and a nominal range of 0.0001 to 1000. 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. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshap...
... working draft ...
BiquadFilterNode.detune - Web APIs
the detune property of the biquadfilternode interface is an a-rate audioparam representing detuning of the frequency in cents. syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.detune.value = 100; 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 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 (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var ...
... working draft ...
BiquadFilterNode.frequency - Web APIs
d in hertz (hz). frequency's default value is 350 with a nominal range of 10 to the nyquist frequency — that is, half of the sample rate. 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. 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 (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshap...
... working draft ...
BiquadFilterNode.gain - Web APIs
eal 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 (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshap...
... working draft ...
BiquadFilterNode.getFrequencyResponse() - Web APIs
in radians for each frequency value in the input frequencyarray. for any frequency in frequencyarray whose value is outside the range 0.0 to samplerate/2 (where samplerate is the sample rate of the audiocontext), the corresponding value in this array is nan. return value undefined exceptions invalidaccesserror the three arrays provided are not all of the same length. example in the following example we are using a biquad filter on a media stream (for the full demo, see our stream-source-buffer demo live, or read the source.) as part of this demo, we get the frequency responses for this biquad filter, for five sample frequencies. we first create the float32arrays we need, one containing the input frequencies, and two to receive the output magnitude and phase values: var myfrequenc...
... function calcfrequencyresponse() { biquadfilter.getfrequencyresponse(myfrequencyarray,magresponseoutput,phaseresponseoutput); for(i = 0; i <= myfrequencyarray.length-1;i++){ var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + myfrequencyarray[i] + 'hz</strong>: magnit...
Blob.type - Web APIs
Web › API › Blob › type
the type property of a blob object returns the mime type of the file. syntax var mimetype = blob.type value a domstring containing the file's mime type, or an empty string if the type could not be determined. 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. ...
...e 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. var i, fileinput, files, allowedfiletypes; // fileinput is a htmlinputelement: <input type="file" multiple id="myfileinput"> fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (simliar to nodelist) files = fileinput.files; // our application only allows gif, png, and jpeg images allowedfiletypes = ["image/png", "image/jpeg", "image/gif"]; for (i = 0; i < files.length; i++) { // test if file.type is an allowed file type. if (allowedfiletypes.indexof(files[i].type) > -1) { // file type matched is one of allowed file types. do something here. } }); specifications specification status comment file apithe defini...
Bluetooth.getAvailability() - Web APIs
the getavailability() method of bluetooth interface of web bluetooth api interface exposes the bluetooth capabilities of the current device. for a returns a boolean which is true if the deveice has a bluetooth adapter and false otherwise (unless user configured user agent not to expose a real value). ...
...getavailability() returned true (navigator.bluetooth.requestdevice() might not resolve with a bluetoothdevice). also, user can configure user agent to return a fixed value instead of a real one. syntax var readerpromise = bluetooth.getavailability(); parameters none. return value a promise that resolves with boolean. exceptions this method doesn't throw any exceptions. ...
BluetoothDevice - Web APIs
the bluetoothdevice interface of the web bluetooth api represents a bluetooth device inside a particular script execution environment. ...
...rties bluetoothdevice.id read only a domstring that uniquely identifies a device. bluetoothdevice.name read only a domstring that provices a human-readable name for the device. bluetoothdevice.gatt read only a reference to the device's bluetoothremotegattserver. bluetoothdevice.uuids read only lists the uuid's of gatt services provided by the device, that the current origin is allowed to access. bluetoothdevice.watchingadvertisements read only if advertisments were activated using bluetoothdevice.watchadvertisements(). non-standard chrome os properties these properties were only implemented on google’s chrome os 45 and removed from chrome 52. bluetoothdevice.addata read only an instance of bluetoothadvertisingdata containing the most recent advertising da...
Body - Web APIs
Web › API › Body
body is implemented by both request and response. this provides these objects with an associated body (a stream), a used flag (initially unset), and a mime type (initially the empty byte sequence). properties body.body read only a simple getter used to expose a readablestream of the body contents. body.bodyused read only a boolean that indicates whether the body has been read. methods body.arraybuffer() takes a response stream and reads it to completion. it returns a promise that resolves with an arraybuffer. ...
...urns a promise that resolves with a formdata object. body.json() takes a response stream and reads it to completion. it returns a promise that resolves with the result of parsing the body text as json. body.text() takes a response stream and reads it to completion. it returns a promise that resolves with a usvstring (text). the response is always decoded using utf-8. examples the example below uses a simple fetch call to grab an image and display it in an <img> tag. you'll notice that since we are requesting an image, we need to run body.blob() (response implements body) to give the response its correct mime type. html content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> js content const myimage = document.queryselector('.my-image'); fetch('...
Broadcast Channel API - Web APIs
note: this feature is available in web workers. by creating a broadcastchannel object, you can receive any messages that are posted to it. you don't have to maintain a reference to the frames or workers you wish to communicate with: they can “subscribe” to a particular channel by constructing their own broadcastchannel with the same name, and have bi-directional communication between all of them. broadcast channel interface creating or joining a channel a client joins a broadcast channel by creating a broadcastchannel object. its constructor takes one single parameter: the name of the channel. ...
...event is dispatched to each broadcastchannel object connected to this channel. a function can be run for this event with the onmessage event handler: // a handler that only logs the event to the console: bc.onmessage = function (ev) { console.log(ev); } disconnecting a channel to leave a channel, call the close() method on the object. this disconnects the object from the underlying channel, allowing garbage collection. // disconnect the channel bc.close(); conclusion the broadcast channel api's self-contained interface allows cross-context communication. it can be used to detect user actions in other tabs within a same origin, like when the user logs in or out. the messaging protocol is not defined and the different browsing contexts need to implement it themselves; there is no negot...
CDATASection - Web APIs
nterface represents a cdata section that can be used within xml to include extended portions of unescaped text. the symbols < and & don’t need escaping as they normally do when inside a cdata section. in xml, a cdata section looks like: <![cdata[ ... ...
...d text.</foo> the only sequence which is not allowed within a cdata section is the closing sequence of a cdata section itself, ]]>: <![cdata[ ]]> will cause an error ]]> note that cdata sections should not be used within html; they only work in xml. ...
CSSCounterStyleRule - Web APIs
the csscounterstylerule interface represents an @counter-style at-rule. ...
... the csscounterstylerule interface represents an @counter-style at-rule. ...
CSSNumericValue - Web APIs
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. ...
...ied 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 constructed directly from a string containing css. specifications specification status comment css typed om level 1the definition of 'cssnumericvalue' in that specification. working draft initial definition. ...
CSSPrimitiveValue - Web APIs
presents a single css value. it may be used to determine the value of a specific style property currently set in a block or to set a specific style property explicitly within the block. 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. conversions are allowed between absolute values (from millimeters to centimeters, from degrees to radians, and so on) but not between relative values. (for example, a pixel value cannot be converted to a centimeter value.) percentage values can't be converted since they are relative to the parent value (or another property value). there is one exception for color percentage values: since a color percentage value is re...
...value (or another property value). there is one exception for color percentage values: since a color percentage value is relative to the range 0-255, a color percentage value can be converted to a number (see also the rgbcolor interface). ...
CSSPseudoElement.type - Web APIs
the type read-only property of the csspseudoelement interface returns the type of the pseudo-element as a string, represented in the form of a css selector. ...
... the type read-only property of the csspseudoelement interface returns the type of the pseudo-element as a string, represented in the form of a css selector. ...
CSSPseudoElement - Web APIs
event or animated using the web animations api. instances of this interface may be obtained by calling element.pseudo(). properties csspseudoelement.element read only returns the originating/parent element of the pseudo-element. csspseudoelement.type read only returns the pseudo-element selector as a cssomstring. methods csspseudoelement extends eventtarget, so it inherits the following methods: eventtarget.addeventlistener() registers an event handler of a specific event type on the pseudo-element. eventtarget.dispatchevent() dispatches an event to this pseudo-element. eventtarget.removeeventlistener() removes an event listener from the pseudo-element. examples basic example using element.pseudo using pseudo-elements, most modern browsers will automatically add q...
...t.dispatchevent() dispatches an event to this pseudo-element. eventtarget.removeeventlistener() removes an event listener from the pseudo-element. examples basic example using element.pseudo using pseudo-elements, most modern browsers will automatically add quotation marks around text inside a <q> element. (a style rule may be needed to add quotation marks in older browsers.) the example below demonstrates the basic properties of the csspseudoelement object representing the opening quotation mark. const element = document.queryselector('q'); const csspseudoelement = element.pseudo('::before'); console.log(csspseudoelement.element); // outputs [object htmlquoteelement] console.log(csspseudoelement.type); // outputs '::before' specifications specification status commen...
CSSStyleDeclaration.removeProperty() - Web APIs
rom a css style declaration object. syntax var oldvalue = style.removeproperty(property); parameters property is a domstring representing the property name to be removed. note that multi-word property names are hyphenated and not camel-cased. return value oldvalue is a domstring equal to the value of the css property before it was removed. ...
...(property); parameters property is a domstring representing the property name to be removed. note that multi-word property names are hyphenated and not camel-cased. return value oldvalue is a domstring equal to the value of the css property before it was removed. exceptions domexception no_modification_allowed_err: if the property or declaration block is read only. example the following javascript code removes the background-color css property from a selector rule: var declaration = document.stylesheets[0].rules[0].style; var oldvalue = declaration.removeproperty('background-color'); specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.removeproperty()' in that specification. working draf...
CSSStyleSheet.insertRule() - Web APIs
rantee a predictable object iteration order, and since css is * order-dependent. ...
..., correct our variables. if (array.isarray(rule[1][0])) { rule = rule[1]; j = 0; } for (var pl = rule.length; j < pl; j++) { var prop = rule[j]; propstr += prop[0] + ': ' + prop[1] + (prop[2] ? ' !important' : '') + ';\n'; } // insert css rule stylesheet.insertrule(selector + '{' + propstr + '}', stylesheet.cssrules.length); } } polyfill the below polyfill will correct the input of the arguments of insertrule() to standardize them in internet explorer 5–8. it supplements insertrule() with a function that separates the selector from the rules before sending the arguments to the default native insertrule(). (function(sheet_proto){ var originalinsertrule = sheet_proto.insertrule; if (originalinsertrule.length === 2){ // 2 mandatory ar...
CSSValueList - Web APIs
the cssvaluelist interface derives from the cssvalue interface and provides the abstraction of an ordered collection of css values. some properties allow an empty list in their syntax. in that case, these properties take the none identifier. so, an empty list means that the property has the value none. the items in the cssvaluelist are accessible via an integral index, starting from 0. ...
...ow an empty list in their syntax. in that case, these properties take the none identifier. so, an empty list means that the property has the value none. the items in the cssvaluelist are accessible via an integral index, starting from 0. ...
Cache.matchAll() - Web APIs
Web › API › Cache › matchAll
the cache object. syntax cache.matchall(request, {options}).then(function(response) { // do something with the response array }); parameters request optional the request for which you are attempting to find responses in the cache. this can be a request object or a url. if this argument is omitted, 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 m...
...: 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 response object having a vary header or not. it defaults to false. return value a promise that resolves to an array of all matching responses in the cache object. note: cache.match() is ...
CanvasRenderingContext2D.addHitRegion() - Web APIs
the canvasrenderingcontext2d method addhitregion() adds a hit region to the bitmap. canvas hit regions make hit detection easy. they let you route events 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...
...(if you don't see the full smiley, check the browser compatibility table to see if your current browser supports hit regions already; you might need to activate a preference.) playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> ...
CanvasRenderingContext2D.clearRect() - Web APIs
re canvas. this is commonly required at the start of each frame in an animation. the dimensions of the cleared area are set to equal the <canvas> element's width and height attributes. ...
... draws a blue triangle on top of a yellowish background. the clearrect() method then erases part of the canvas. html <canvas id="canvas"></canvas> javascript the cleared area is rectangular in shape, with its top-left corner at (10, 10). the cleared area has a width of 120 and a height of 100. ...
CanvasRenderingContext2D.drawWindow() - Web APIs
drawwindow_do_not_flush 0x02 do not flush pending layout notifications that could otherwise be batched up. drawwindow_draw_view 0x04 draw scrollbars and scroll the viewport if they are present. drawwindow_use_widget_layers 0x08 use the widget layer manager if available. this means hardware acceleration may be used, but it might actually be slower or lower quality than normal. it will, however, more accurately reflect the pixels rendered to the screen. drawwindow_async_decode_images 0x10 do not synchronously decode images - draw what we have. example this method draws a snapshot of the contents of a dom window into the canvas. for example, ctx.drawwindow(window, 0, 0, 100, 200, 'rgb(255,255,255)'); ..
... window into the canvas. for example, ctx.drawwindow(window, 0, 0, 100, 200, 'rgb(255,255,255)'); ... would draw the contents of the current window, in the rectangle (0,0,100,200) in pixels relative to the top-left of the viewport, on a white background, into the canvas. by specifying "rgba(255,255,255,0)" as the color, the contents would be drawn with a transparent background (which would be slower). it is usually a bad idea to use any background other than pure white "rgb(255,255,255)" or transparent, as this is what all browsers do, and many websites expect that transparent parts of their interface will be drawn on white background. with this method, it is possible to fill a hidden iframe with arbitrary content (e.g., css-styled html text, or svg) and draw it into a canvas. it will be...
Manipulating video using canvas - Web APIs
by combining the capabilities of the video element with a canvas, you can manipulate video data in real time to incorporate a variety of visual effects to the video being displayed. this tutorial demonstrates how to perform chroma-keying (also known as the "green screen effect") using javascript code. the document content the html document used to render this content is shown below. <!doctype html> <html> <head> <style> body { background: black; color:#cccccc; } #c2 { background-image: url(media/foo.png); background-repeat: no-repeat; } div { float: left; border :1px solid #444444; padding:10px; margin: 10px; background:#3b3b3b; } </style> </head> <body> <div>...
... it calls the computeframe() method, which performs the chroma-keying effect on the current video frame. the last thing the callback does is call settimeout() to schedule itself to be called again as soon as possible. in the real world, you would probably schedule this to be done based on knowledge of the video's frame rate. manipulating the video frame data the computeframe() method, shown below, is responsible for actually fetching a frame of data and performing the chroma-keying effect. processor.computeframe = function computeframe() { this.ctx1.drawimage(this.video, 0, 0, this.width, this.height); let frame = this.ctx1.getimagedata(0, 0, this.width, this.height); let l = frame.data.length / 4; for (let i = 0; i < l; i++) { let r = frame.data[i * 4 + 0]; ...
Compositing and clipping - Web APIs
« previousnext » in all of our previous examples, shapes were always drawn one on top of the other. this is more than adequate for most situations, but it limits the order in which composite shapes are built. we can, however, change this behaviour by setting the globalcompositeoperation property. in addition, the clip property allows us to hide unwanted parts of shapes. globalcompositeoperation we can not only draw new shapes behind existing shapes but we can also use it to mask off certain areas, clear sections from the canvas (not limited to rectangles like the clearrect() method does) and more. globalcompositeoperation = type this sets the type of compositing operation to apply when drawing new shapes, where type is a string identifying which of the twelve compos...
...t we can also use it to mask off certain areas, clear sections from the canvas (not limited to rectangles like the clearrect() method does) and more. globalcompositeoperation = type this sets the type of compositing operation to apply when drawing new shapes, where type is a string identifying which of the twelve compositing operations to use. see compositing examples for the code of the following examples. clipping paths a clipping path is like a normal canvas shape but it acts as a mask to hide unwanted parts of shapes. this is visualized in the image on the right. the red star shape is our clipping path. everything that falls outside of this path won't get drawn on the canvas. if we compare clipping paths to the globalcompositeoperation property we've seen above, we see two comp...
Hit regions and accessibility - Web APIs
fallback content the content inside the <canvas> ... </canvas> tags can be used as a fallback for browsers which don't support canvas rendering. ...
...ith disabilities. you can use aria attributes to describe the behavior and purpose of the canvas element. see aria and aria techniques for more information. <canvas id="button" tabindex="0" role="button" aria-pressed="false" aria-label="start game"></canvas> hit regions whether the mouse coordinates are within a particular area on the canvas, is a common problem to solve. the hit region api allows you to define an area of your canvas and provides another possibility to expose interactive content on a canvas to accessibility tools. it allows you to make hit detection easier and lets you route events to dom elements. the api has the following three methods (which are still experimental in current web browsers; check the browser compatibility tables). canvasrenderingcontext2d.addhitregion...
Transformations - Web APIs
art generating ever more complex drawings. save() saves the entire state of the canvas. restore() restores the most recently saved canvas state. canvas states are stored on a stack. every time the save() method is called, the current drawing state is pushed onto the stack. a drawing state consists of the transformations that have been applied (i.e. translate, rotate and scale – see below). the current values of the following attributes: strokestyle, fillstyle, globalalpha, linewidth, linecap, linejoin, miterlimit, linedashoffset, shadowoffsetx, shadowoffsety, shadowblur, shadowcolor, globalcompositeoperation, font, textalign, textbaseline, direction, imagesmoothingenabled. the current clipping path, which we'll see in the next section. you can call the save() method as many t...
...getelementbyid('canvas').getcontext('2d'); // draw a simple rectangle, but scale it. ctx.save(); ctx.scale(10, 3); ctx.fillrect(1, 10, 10, 10); ctx.restore(); // mirror horizontally ctx.scale(-1, 1); ctx.font = '48px serif'; ctx.filltext('mdn', -135, 120); } <canvas id="canvas" width="150" height="150"></canvas> draw(); screenshotlive sample transforms finally, the following transformation methods allow modifications directly to the transformation matrix. transform(a, b, c, d, e, f) multiplies the current transformation matrix with the matrix described by its arguments. the transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] if any of the arguments are infinity the transformati...
Channel Messaging API - Web APIs
note: this feature is available in web workers. channel messaging concepts and usage a message channel is created using the messagechannel() constructor. ...
... to the original document using messageport.postmessage. when you want to stop sending messages down the channel, you can invoke messageport.close to close the ports. find out more about how to use this api in using channel messaging. channel messaging interfaces messagechannel creates a new message channel to send messages across. messageport controls the ports on the message channel, allowing sending of messages from one port and listening out for them arriving at the other. portcollection an array of messageports; an experimental solution to allow broadcasting of a message to multiple ports simultaneously. examples we have published a channel messaging basic demo on github (run it live too), which shows a really simple single message transfer between a page and an embedded ...
CharacterData - Web APIs
sents a node object that contains characters. this is an abstract interface, meaning there aren't any object of type characterdata: it is implemented by other interfaces, like text, comment, or processinginstruction which aren't abstract. ...
...ts parent, node, and implements the childnode and nondocumenttypechildnode interface. characterdata.data is a domstring representing the textual data contained in this object. characterdata.length read only returns an unsigned long representing the size of the string contained in characterdata.data. nondocumenttypechildnode.nextelementsibling read only returns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list. nondocumenttypechildnode.previouselementsibling read only returns the element immediately prior to the specified one in its parent's children list, or null if the specified element is the first one in the list. methods inherits methods from its parent, node, and implements the c...
ChildNode.replaceWith() - Web APIs
; console.log(parent.outerhtml); // "<div><span></span></div>" childnode.replacewith() is unscopable the replacewith() method is not scoped into the with statement. see symbol.unscopables for more information. ...
...are no arguments parent.removechild(this); while (i--) { // i-- decrements i and returns the value of i before the decrement currentnode = arguments[i]; if (typeof currentnode !== 'object'){ currentnode = this.ownerdocument.createtextnode(currentnode); } else if (currentnode.parentnode){ currentnode.parentnode.removechild(currentnode); } // the value of "i" below is after the decrement if (!i) // if currentnode is the first argument (currentnode === arguments[0]) parent.replacechild(currentnode, this); else // if currentnode isn't the first parent.insertbefore(currentnode, this.nextsibling); } } if (!element.prototype.replacewith) element.prototype.replacewith = replacewithpolyfill; if (!characterdata.prototype.replacewith) c...
Clients.claim() - Web APIs
Web › API › Clients › claim
the claim() method of the clients interface allows an active service worker to set itself as the controller for all clients within its scope. this triggers a "controllerchange" event on navigator.serviceworker in any clients that become controlled by this service worker. when a service worker is initially registered, pages won't use it until they next load. the claim() method causes those pages to be controlled immediately. be aware that this results in your service worker controlling pages that loaded regularly over the network, or possibly via a different service worker. syntax await clients.claim(); parameters none. return value a promise that resolves to undefined. ...
...ally registered, pages won't use it until they next load. the claim() method causes those pages to be controlled immediately. be aware that this results in your service worker controlling pages that loaded regularly over the network, or possibly via a different service worker. syntax await clients.claim(); parameters none. return value a promise that resolves to undefined. example the following example uses claim() inside service worker's "activate" event listener so that clients loaded in the same scope do not need to be reloaded before their fetches will go through this service worker. self.addeventlistener('activate', event => { event.waituntil(clients.claim()); }); specifications specification status comment service workersthe definition of 'claim()' ...
Clipboard.read() - Web APIs
Web › API › Clipboard › read
table before using these methods. syntax var promise = navigator.clipboard.read(); parameters none. return value a promise that resolves with a datatransfer object containing the clipboard's contents. the promise is rejected if permission to access the clipboard is not granted. example after using navigator.permissions.query() to find out if we have (or if the user will be prompted to allow) "clipboard-read" access, this example fetches the data currently on the clipboard. if it's not a png image, an error message is presented. otherwise, an image element referred to using the variable imgelem has its source replaced with the clipboard's contents. // first, ask the permissions api if we have some kind of access to // the "clipboard-read" feature. navigator.permissions.query({name:...
...resented. otherwise, an image element referred to using the variable imgelem has its source replaced with the clipboard's contents. // first, ask the permissions api if we have some kind of access to // the "clipboard-read" feature. navigator.permissions.query({name: "clipboard-read"}).then(result => { // if permission to read the clipboard is granted or if the user will // be prompted to allow it, we proceed. if (result.state == "granted" || result.state == "prompt") { navigator.clipboard.read().then(data => { for (let i=0; i<data.items.length; i++) { if (data.items[i].type != "image/png") { alert("clipboard contains non-image data. unable to access it."); } else { const blob = data.items[i].gettype("image/png"); imgelem.src = ...
console.assert() - Web APIs
Web › API › Console › assert
of javascript objects to output. the string representations of each of these objects are appended together in the order listed and output. msg a javascript string containing zero or more substitution strings. subst1 ... substn javascript objects with which to replace substitution strings within msg. this parameter gives you additional control over the format of the output. ...
...h of these objects are appended together in the order listed and output. msg a javascript string containing zero or more substitution strings. subst1 ... substn javascript objects with which to replace substitution strings within msg. this parameter gives you additional control over the format of the output. ...
ConstantSourceNode - Web APIs
creates and returns a new constantsourcenode instance, optionally specifying an object which establishes initial values for the object's properties. you can also create a constantsourcenode whose properties are initialized to their default values by calling audiocontext.createconstantsource(). properties inherits properties from its parent interface, audioscheduledsourcenode, and adds the following properties: offset an audioparam which specifies the value that this source continuously outputs. the default value is 1.0. event handlers inherits event handlers from its parent interface, audioscheduledsourcenode. some browsers' implementations of this event handler are part of the audioscheduledsourcenode interface. onended fired whenever the constantsourcenode data has stopp...
...s from its parent interface, audioscheduledsourcenode. some browsers' implementations of these methods are part of the audioscheduledsourcenode interface. start() schedules a sound to playback at an exact time. stop() schedules a sound to stop playback at an exact time. example in the article controlling multiple parameters with constantsourcenode, a constantsourcenode is created to allow one slider control to change the gain on two gainnodes. the three nodes are set up like this: gainnode2 = context.creategain(); gainnode3 = context.creategain(); gainnode2.gain.value = gainnode3.gain.value = 0.5; volumeslidercontrol.value = gainnode2.gain.value; constantnode = context.createconstantsource(); constantnode.connect(gainnode2.gain); constantnode.connect(gainnode3.gain); constantnod...
ContentIndex.add() - Web APIs
Web › API › ContentIndex › add
title: a string title for the item. used in user-visible lists of content. title: a string title of the item. used in user-visible lists of content. description: a string description of the item. used in user-visible lists of content. ...
...ists of content. url: a string containing the url of the corresponding html document. needs to be under the scope of the current service worker. category: optional a string defining the category of content. can be: '' an empty string, this is the default. homepage article video audio icons: optional an array of image resources, defined as an object with the following data: src: a url string of the source image. sizes: optional a string representation of the image size. type: optional the mime type of the image. return value returns a promise that resolves with undefined exceptions typeerror if the service worker's registration is not present or the service worker does not contain a fetchevent. if the id, title, descripti...
CredentialsContainer.get() - Web APIs
ects all credentials in the credentialscontainer that meet the necessary criteria (defined in the options argument). from the resulting set of credentials, it then selects the best one. depending on the options, it may display a dialog to the user and ask the user to make the selection. this method collects credentials by calling the "collectfromcredentialstore" method for each credential type allowed by the options argument. for example: if options.password exists, then the passwordcredential.[[collectfromcredentialstore]] is called. this method is restricted to top-level contexts. calls to it within an <iframe> element will resolve without effect. syntax var promise = credentialscontainer.get([options]) parameters options optional an object of type credentialrequestoptions that c...
...llectfromcredentialstore]] is called. this method is restricted to top-level contexts. calls to it within an <iframe> element will resolve without effect. syntax var promise = credentialscontainer.get([options]) parameters options optional an object of type credentialrequestoptions that contains options for the request. the options include criteria that the credentials are required or allowed to have, and options for interacting with the user. it can contain the following properties: password: a boolean indicating that returned credential instances should include user (as opposed to federated) credentials. federated: a federatedcredentialrequestoptions object containing requirements for returned federated credentials. the available options are: providers: an array of ...
CustomElementRegistry.define() - Web APIs
t it is trying to extend is an unknown element. syntaxerror the provided name is not a valid custom element name. typeerror the referenced constructor is not a constructor. note: you'll often get notsupportederrors thrown that seem like define() is failing, but instead it is likely a problem with element.attachshadow(). examples autonomous custom element the following code is taken from our popup-info-box-web-component example (see it live also). // create a class for the element class popupinfo extends htmlelement { constructor() { // always call super first in constructor super(); // create a shadow root var shadow = this.attachshadow({mode: 'open'}); // create spans var wrapper = document.createelement('span'); wrapper.se...
...ent customelements.define('popup-info', popupinfo); <popup-info img="img/alt.png" text="your card validation code (cvc) is an extra security feature — it is the last 3 or 4 numbers on the back of your card."> note: constructors for autonomous custom elements must extend htmlelement. customized built-in element the following code is taken from our word-count-web-component example (see it live also). // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // count words in element's parent element var wcparent = this.parentnode; function countwords(node){ var text = node.innertext || node.textc...
DOMError - Web APIs
Web › API › DOMError
the domerror interface describes an error object that contains an error name. properties domerror.name read only returns a domstring representing one of the error type names (see below). domerror.message read only returns a domstring representing a message or description associated with the given error type name. error types type description indexsizeerror the index is not in the allowed range (e.g. thrown in a range object). hierarchyrequesterror the node tree hierarchy is not correct. wrongdocumenterror the object is in the wrong document. invalidcharactererror the string contains invalid characters. nomodificationallowederror the object can not be modified. notfounderror the object can no...
...e modified. notfounderror the object can not be found here. notsupportederror the operation is not supported invalidstateerror the object is in an invalid state. syntaxerror the string did not match the expected pattern. invalidmodificationerror the object can not be modified in this way. namespaceerror the operation is not allowed by namespaces in xml invalidaccesserror the object does not support the operation or argument. typemismatcherror the type of the object does not match the expected type. securityerror the operation is insecure. networkerror a network error occurred. aborterror the operation was aborted. urlmismatcherror the given url does n...
DOMHighResTimeStamp - Web APIs
he time, given in milliseconds, should be accurate to 5 µs (microseconds), 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 mig...
... 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 confirmed that na...
DOMMatrix - Web APIs
Web › API › DOMMatrix
constructor dommatrix() creates and returns a new dommatrix object. properties this interface inherits properties from dommatrixreadonly, though some of these properties are altered to be mutable. ...
...int values representing each component of a 4×4 matrix, where m11 through m14 are the first column, m21 through m24 are the second column, and so forth. a, b, c, d, e, f double-precision floating-point values representing the components of a 4×4 matrix which are required in order to perform 2d rotations and translations. these are aliases for specific components of a 4×4 matrix, as shown below. 2d 3d equivalent a m11 b m12 c m21 d m22 e m41 f m42 methods this interface includes the following methods, as well as the methods it inherits from dommatrixreadonly. dommatrix.invertself() modifies the matrix by inverting it. if the matrix can't be inverted, ...
DOMPoint - Web APIs
Web › API › DOMPoint
in general, a positive x component represents a position to the right of the origin, a positive y component is downward from the origin, and a positive z component extends outward from the screen (in other words, toward the user). ...
...ties. properties dompoint inherits properties from its parent, dompointreadonly. dompoint.x the x coordinate of the dompoint. dompoint.y the y coordinate of the dompoint. dompoint.z the z coordinate of the dompoint. dompoint.w the perspective value of the dompoint. examples in the webxr device api, dompointreadonly values are used to represent positions and orientations. in the following snippet, the pose of the xr device (such as a vr headset or phone with ar capabilities) can be retrieved by calling using xrframe.getviewerpose() during an xrsession animation frame, then accessing the resulting xrpose's transform property, which contains two dompointreadonly attributes: position as a vector and orientation as a quaternion. function onxrframe(time, xrframe) { let viewerpose...
Binary strings - Web APIs
Web › API › DOMString › Binary
present 65535 different code points. a subset of these strings is represented by utf-16 strings containing only ascii characters (i.e., characters whose code point does not exceed 127). for instance, the string "hello world!" belongs to the ascii subset, while the string "ÀÈÌÒÙ" does not. a binary string is a concept similar to the ascii subset, but instead of limiting the range to 127, it allows code points until 255. its purpose however is not to represent characters, but binary data. the size of the data so represented is twice as big as it would be in normal binary format, however this will not be visible to the final user, since the length of javascript strings is calculated using two bytes as the unit. binary strings are not part of the javascript language design. however at least...
...ion, access to raw data using websockets, and so forth) it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easily manipulate raw binary data. in the past, this had to be simulated by treating the raw data as a string and using the charcodeat() method to read the bytes from the data buffer (i.e., using binary strings). however, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats). javascript typed arrays provide a mechanism for accessing raw binary data much more efficiently. the stringview non native constructor is one level above typed arrays and provides a c-like interface for strings. ...
DOMTokenList.entries() - Web APIs
we when retrieve an iterator containing the key/value pairs using entries(), then iterate through each one using a for...of loop, writing them to the <span>'s node.textcontent. ...
...we when retrieve an iterator containing the key/value pairs using entries(), then iterate through each one using a for...of loop, writing them to the <span>'s node.textcontent. ...
DOMTokenList.keys() - Web APIs
Web › API › DOMTokenList › keys
we when retrieve an iterator containing the keys using values(), then iterate through those keys using a for ... of loop, writing each one to the <span>'s node.textcontent. ...
...we when retrieve an iterator containing the keys using values(), then iterate through those keys using a for ... of loop, writing each one to the <span>'s node.textcontent. ...
DOMTokenList.replace() - Web APIs
e token list. syntax tokenlist.replace(oldtoken, newtoken); parameters oldtoken a domstring representing the token you want to replace. newtoken a domstring representing the token you want to replace oldtoken with. return value a boolean value, which is true if oldtoken was successfully replaced, or false if not. note: in older browsers, replace() returns void. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then replace a token in the list, and write the list into the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; let result = classes.replace("c", "z"); console.log(re...
...nto the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; let result = classes.replace("c", "z"); console.log(result); if (result) { span.textcontent = classes; } else { span.textcontent = 'token not replaced successfully'; } the output looks like this: polyfill the following polyfill will add the replace method to the domtokenlist class. the following code will only work with ie10-11. to use with earlier versions of ie, refer to the polyfill at element.classlist#polyfill domtokenlist.prototype.replace = function (a, b) { if (this.contains(a)) { this.add(b); this.remove(a); return true; } return false; } specifications ...
DOMTokenList.values() - Web APIs
we when retrieve an iterator containing the values using values(), then iterate through those values using a for ... of loop, writing each one to the <span>'s node.textcontent. ...
...we when retrieve an iterator containing the values using values(), then iterate through those values using a for ... of loop, writing each one to the <span>'s node.textcontent. ...
Detecting device orientation - Web APIs
= event.alpha; var beta = event.beta; var gamma = event.gamma; // do stuff with the new orientation data } orientation values explained the value reported for each axis indicates the amount of rotation around a given axis in reference to a standard coordinate frame. these are described in greater detail in the orientation and motion data explained article which is summarized below. the deviceorientationevent.alpha value represents the motion of the device around the z axis, represented in degrees with values ranging from 0 to 360. the deviceorientationevent.beta value represents the motion of the device around the x axis, represented in degrees with values ranging from -180 to 180. this represents a front to back motion of the device. the deviceorientationevent.gamma ...
...ionevent.rotationrate devicemotionevent.interval motion values explained the devicemotionevent objects provide web developers with information about the speed of changes for the device's position and orientation. the changes are provided along three axis (see orientation and motion data explained for details). for acceleration and accelerationincludinggravity, those axes correspond to the following: x: represents the axis from west to east y: represents the axis from south to north z: represents the axis perpendicular to the ground for rotationrate, the situation is a bit different; the information corresponds to the following in each case: alpha: represents a rotation rate along the axis perpendicular to the screen (or keyboard for desktop). beta: represents a rotation rate a...
Document.createElementNS() - Web APIs
he nodename property of the created element is initialized with the value of qualifiedname. optionsoptional an optional elementcreationoptions object containing a single property named is, whose value is the tag name for a custom element previously defined using customelements.define(). for backwards compatibility with previous versions of the custom elements specification, some browsers will allow you to pass a string here instead of an object, where the string's value is the custom element's tag name. see extending native html elements for more information on how to use this parameter. the new element will be given an is attribute whose value is the custom element's tag name. custom elements are an experimental feature only available in some browsers. return value the new element. im...
...this particular example is actually an xul document with embedded xhtml, however, the recommendation still applies. specifications specification status comment domthe definition of 'document.createelementns()' in that specification. living s...
Document.createTouch() - Web APIs
, screeny); parameters note: all parameters are optional. view the window in which the touch occurred. target the eventtarget for the touch. identifier the value for touch.identifier. pagex the value for touch.pagex. pagey the value for touch.pagey. screenx the value for touch.screenx. screeny the value for touch.screeny. note: previous versions of this method included the following additional parameters but those parameters are not included in either of the standards listed below. consequently, these parameters should be considered deprecated and not used. clientx the value for touch.clientx. clienty the value for touch.clienty. radiusx the value for touch.radiusx. radiusy the value for touch.radiusy. rotationangle the value for touch.rotationangle. force t...
... clienty the value for touch.clienty. radiusx the value for touch.radiusx. radiusy the value for touch.radiusy. rotationangle the value for touch.rotationangle. force the value for touch.force. return value touch a touch object configured as described by the input parameters. example this example illustrates using the document.createtouch() method to create touch objects. in following code snippet, two touch objects are created for the target element. var target = document.getelementbyid("target"); var touch1 = document.createtouch(window, target, 1, 15, 20, 35, 40); var touch2 = document.createtouch(window, target, 2, 25, 30, 45, 50); specifications specification status comment touch eventsthe definition of 'document.createtouch()' in that ...
Document: drag event - Web APIs
the drag event is fired every few hundred milliseconds as an element or text selection is being dragged by the user. bubbles yes cancelable yes default action continue the drag & drop operation. interface dragevent event handler property ondrag examples see this code in a jsfiddle demo or interact with it below. html <div class="dropzone"> <div id="draggable" draggable="true" ondragstart="event.datatransfer.setdata('text/plain',null)"> this div is draggable </div> </div> <div class="dropzone"></div> <div class="dropzone"></div> <div class="dropzone"></div> css #draggable { width: 200px; height: 20px; text-align: center; background: white; } .dropzone { width: 200px; height: 20px; background: blue...
...vent) { // store a ref. ...
Document.importNode() - Web APIs
ec! the new default value is false. best practice: though it's still an optional argument, you should always provide the deep argument for backward and forward compatibility. with gecko 28.0 (firefox 28 / thunderbird 28 / seamonkey 2.25 / firefox os 1.3), the console warns developers not to omit the argument. starting with gecko 29.0 (firefox 29 / thunderbird 29 / seamonkey 2.26)), a shallow clone is defaulted instead of a deep clone. return value the copied importednode in the scope of the importing document. note: importednode's node.parentnode is null, since it has not yet been inserted into the document tree! example const iframe = document.queryselector("iframe"); const oldnode = iframe.contentwindow.document.getelementbyid("mynode"); const newnode = document.impo...
...); const newnode = document.importnode(oldnode, true); document.getelementbyid("container").appendchild(newnode); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importnode(); or adopted using document.adoptnode(). best practice: although firefox doesn't currently enforce this rule, we encourage you to follow this rule for improved future compatibility. for more on the node.ownerdocument issues, see the w3c dom faq. specifications specification status comment domthe definition of 'document.importnode()' in that specification. living standard document object model (dom) level 2 core specificationthe definition of 'document.importnode()' in that specificat...
Document.open() - Web APIs
Web › API › Document › open
the document.open() method opens a document for writing. this does come with some side effects. for example: all event listeners currently registered on the document, nodes inside the document, or the document's window are removed. all existing nodes are removed from the document. syntax document.open(); parameters none. return value a document object instance. examples the following simple code opens the document and replaces its content with a number of different html fragments, before closing it again. document.open(); document.write("<p>hello world!</p>"); document.write("<p>i am a fish</p>"); document.write("<p>the number is 42</p>"); document.close(); notes an automatic document.open() call happens when document.write() is called after the page has loaded. for years...
...there is a lesser-known and little-used three-argument version of document.open() , which is an alias of window.open() (see its page for full details). this call, for example opens github.com in a new window, with its opener set to null: document.open('https://www.github.com','', 'noopener=true') two-argument document.open() browsers used to support a two-argument document.open(), with the following signature: document.open(type, replace) where type specified the mime type of the data you are writing (e.g. text/html) and replace if set (i.e. a string of "replace") specified that the history entry for the new document would replace the current history entry of the document being written to. this form is now obsolete; it won't throw an error, but instead just forwards to document.open() ...
Document.querySelector() - Web APIs
xceptions syntax_err the syntax of the specified selectors is invalid. usage notes if the specified selector matches an id that is incorrectly used more than once in the document, the first element with that id is returned. css pseudo-elements will never return any elements, as specified in the selectors api. escaping special characters to match against an id or selectors that do not follow standard css syntax (by using a colon or space inappropriately, for example), you must escape the character with a backslash ("\"). as the backslash is also an escape character in javascript, if you are entering a literal string, you must escape it twice (once for the javascript string, and another time for queryselector()): <div id="foo\bar"></div> <div id="foo:bar"></div> <script> console.l...
...here, the first <input> element with the name "login" (<input name="login"/>) located inside a <div> whose class is "user-panel main" (<div class="user-panel main">) in the document is returned: var el = document.queryselector("div.user-panel.main input[name='login']"); negation as all css selector strings are valid, you can also negate selectors: var el = document.queryselector(...
DocumentFragment.querySelector() - Web APIs
queryselector(selectors); parameters selectors is a domstring containing one or more css selectors separated by commas. ...
...mstring containing one or more css selectors separated by commas. examples basic example in this basic example, the first element in the documentfragment with the class "myclass" is returned: var el = documentfragment.queryselector(".myclass"); css syntax and the method's argument the string argument pass to queryselector must follow the css syntax. ...
Events and the DOM - Web APIs
introduction this chapter describes the dom event model. the event interface itself is described, as well as the interfaces for event registration on nodes in the dom, and event listeners, and several longer examples that show how the various event interfaces relate to one 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...
...n be set per element and per event. accessing event interfaces event handlers may be attached to various objects (including dom elements, document, the window object, etc.). when an event occurs, an event object is created and passed sequentially to the event listeners. the event interface is accessible from within the handler function, via the event object passed as the first argument. the following simple example shows how an event object is passed to the event handler function, and can be used from within one such function. function print(evt) { // the evt parameter is automatically assigned the event object // take care of the differences between console.log & alert console.log('print:', evt) alert(evt) } // any function should have an appropriate name, that's what called sema...
How to create a DOM tree - Web APIs
this page describes how to use the dom core api in javascript to create and modify dom objects. it applies to all gecko-based applications (such as firefox) both in privileged (extensions) and unprivileged (web pages) code. ...
...city", "denver"); addresselem5.setattribute("state", "co"); addresselem5.setattribute("country", "usa"); personelem2.appendchild(addresselem5); peopleelem.appendchild(personelem1); peopleelem.appendchild(personelem2); doc.appendchild(peopleelem); see also the dom chapter of the xul tutorial. ...
Document Object Model (DOM) - Web APIs
ramming languages by representing the structure of a document—such as the html representing a web page—in memory. 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. to learn more about what the dom is and how it represents documents, see our article introduction to the dom. dom interfaces attr cdatasection characterdata childnode ...
...venttarget htmlcollection mutationobserver mutationrecord namednodemap node nodefilter nodeiterator nodelist nondocumenttypechildnode parentnode processinginstruction selection range text textdecoder textencoder timeranges treewalker url window worker xmldocument obsolete dom interfaces the document object model has been highly simplified. to achieve this, the following interfaces present in the different dom level 3 or earlier specifications have been removed. it is uncertain whether some may be reintroduced in the future or not, but for the time being they should be considered obsolete and should be avoided: documenttouch domconfiguration domerrorhandler domimplementationlist domimplementationregistry domimplementationsource domlocator...
DynamicsCompressorNode() - Web APIs
its default value is 0.003. this parameter is k-rate. its nominal range is [0, 1]. ...
...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. ...
DynamicsCompressorNode - Web APIs
this is often used in musical production and game audio. dynamicscompressornode is an audionode that has exactly one input and one output; it is created using the audiocontext.createdynamicscompressor() method. ...
...gnal. dynamicscompressornode.attack read only is a k-rate audioparam representing the amount of time, in seconds, required to reduce the gain by 10 db. dynamicscompressornode.release read only is a k-rate audioparam representing the amount of time, in seconds, required to increase the gain by 10 db. methods no specific methods; inherits methods from its parent, audionode. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynam...
Element.clientTop - Web APIs
Web › API › Element › clientTop
the width of the top border of an element in pixels. it is a read-only, integer property of element. as it happens, all that lies between the two locations (offsettop and client area top) is the element's border. this is because the offsettop indicates the location of the top of the border (not the margin) while the client area starts immediately below the border, (client area includes padding.) therefore, the clienttop value will always equal the integer portion of the .getcomputedstyle() value for "border-top-width". (actually might be math.round(parsefloat()).) for example, if the computed "border-top-width" is zero, then clienttop is also zero. note: this property will round the value to an integer. if you need a fractional value, use element.getboundingclientrect(). gecko-based app...
...op-width" is zero, then clienttop is also zero. note: this property will round the value to an integer. if you need a fractional value, use element.getboundingclientrect(). gecko-based applications support clienttop starting with gecko 1.9 (firefox 3, implemented in bug 111207). this property is not supported in firefox 2 and earlier. syntax var top = element.clienttop; example in the following illustration, the 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 mag...
Element.closest() - Web APIs
Web › API › Element › closest
however, it will only support css 2.1 selectors in ie 8, and it can cause severe lag spikes in production websites. if (window.element && !element.prototype.closest) { element.prototype.closest = function(s) { var matches = (this.document || this.ownerdocument).queryselectorall(s), i, el = this; do { i = mat...
...hesselector; } if (!element.prototype.closest) { element.prototype.closest = function(s) { var el = this; do { if (element.prototype.matches.call(el, s)) return el; el = el.parentelement || el.parentnode; } while (el !== null && el.nodetype === 1); return null; }; } however, if you really do require ie 8 support, then the following polyfill will do the job very slowly, but eventually. however, it will only support css 2.1 selectors in ie 8, and it can cause severe lag spikes in production websites. if (window.element && !element.prototype.closest) { element.prototype.closest = function(s) { var matches = (this.document || this.ownerdocument).queryselectorall(s), i, el = this; do { i = matches.length; while (--i >= 0 && ...
Element.getAnimations() - Web APIs
mixin) returns an array of all animation objects affecting this element or which are scheduled to do so in future. it can optionally return animation objects for descendant elements too. note: this array includes css animations, css transitions, and web animations. syntax const animations = element.getanimations(options); parameters options optional an options object containing the following property: subtree a boolean value which, if true, causes animations that target descendants of element to be returned as well. this includes animations that target any css pseudo-elements attached to element or one of its descendents. defaults to false. return value an array of animation objects, each representing an animation currently targetting the element on which this metho...
...nts of element to be returned as well. this includes animations that target any css pseudo-elements attached to element or one of its descendents. defaults to false. return value an array of animation objects, each representing an animation currently targetting the element on which this method is called, or one of its descendant elements if { subtree: true } is specified. examples the following code snippet will wait for all animations on elem and its descendants to finish before removing the element from the document. promise.all( elem.getanimations({ subtree: true }) .map(animation => animation.finished) ).then(() => elem.remove()); specifications specification status comment web animationsthe definition of 'animatable.getanimations()' in that speci...
Element.getAttribute() - Web APIs
ils. syntax let attribute = element.getattribute(attributename); where attribute is a string containing the value of attributename. attributename is the name of the attribute whose value you want to get. examples const div1 = document.getelementbyid('div1'); const align = div1.getattribute('align'); alert(align); // shows the value of align for the element with id="div1" description lower casing when called on an html element in a dom flagged as an html document, getattribute() lower-cases its argument before proceeding. non-existing attributes essentially all web browsers (firefox, internet explorer, recent versions of opera, safari, konqueror, and icab, as a non-exhaustive list) return null when the specified attribute does not exist on the specified element; this is what t...
...ve list) return null when the specified attribute does not exist on the specified element; this is what the current dom specification draft specifies. the old dom 3 core specification, on the other hand, says that the correct return value in this case is actually the empty string, and some dom implementations implement this behavior. the implementation of getattribute() in xul (gecko) actually follows the dom 3 core specification and returns an empty string. consequently, you should use element.hasattribute() to check for an attribute's existence prior to calling getattribute() if it is possible that the requested attribute does not exist on the specified element. retrieving nonce values for security reasons, csp nonces from non-script sources, such as css selectors, and .getattribute("non...
Element.getAttributeNS() - Web APIs
e of the specified attribute. if the attribute doesn't exist, the result is null. note: earlier versions of the dom specification had this method described as returning an empty string for non-existent attributes, but it was not typically implemented this way since null makes more sense. the dom4 specification now says this method should return null for non-existent attributes. examples the following svg document reads the value of the foo attribute in a custom namespace. <svg xmlns="http://www.w3.org/2000/svg" xmlns:test="http://www.example.com/2014/test" width="40" height="40"> <circle id="target" cx="12" cy="12" r="10" stroke="#444" stroke-width="2" fill="none" test:foo="hello namespaced attribute!"/> <script type="text/javascript"> var ns = 'http://www.example.com/...
...vg> <script type="text/javascript"> var ns = 'http://www.example.com/2014/test'; var circle = document.getelementbyid( 'target' ); console.log('attribute value: ' + circle.getattribute('test:foo')); </script> </body> </html> notes namespaces are only supported in xml documents. html5 documents have to use getattribute() instead. getattributens() differs from getattribute() in that it allows you to further specify the requested attribute as being part of a particular namespace, as in the example above, where the attribute is part of the fictional "specialspace" namespace on mozilla. prior to the dom4 specification, this method was specified to return an empty string rather than null for non-existent attributes. however, most browsers instead returned null. starting with dom4, the s...
Element.getBoundingClientRect() - Web APIs
<div></div> div { width: 400px; height: 200px; padding: 20px; margin: 50px auto; background: purple; } let elem = document.queryselector('div'); let rect = elem.getboundingclientrect(); for (var key in rect) { if(typeof rect[key] !== 'function') { let para = document.createelement('p'); para.textcontent = `${ key } : ${ rect[key] }`; document.body.appendchild(para)...
...clientrect()' in that specification. working draft initial definition notes the returned domrect object can be modified in modern browsers. this was not true with older versions which effectively returned domrectreadonly. with ie and edge, not being able to add missing properties to their returned clientrect, object prevents backfilling x and y. due to compatibility problems (see below), it is safest to rely on only properties left, top, right, and bottom. properties in the returned domrect object are not own properties. while the in operator and for...in will find returned properties, other apis such as object.keys() will fail. moreover, and unexpectedly, the es2015 and newer features such as object.assign() and object rest/spread will fail to copy returned properties. rect ...
Element.getElementsByTagName() - Web APIs
. all descendants of the specified element are searched, but not the element itself. the returned list is live, which means it updates itself with the dom tree automatically. therefore, there is no need to call element.getelementsbytagname() with the same element and arguments repeatedly if the dom changes in between calls. when called on an html element in an html document, getelementsbytagname lower-cases the argument before searching for it. this is undesirable when trying to match camel-cased svg elements (such as <lineargradient>) in an html document. instead, use element.getelementsbytagnamens(), which preserves the capitalization of the tag name. element.getelementsbytagname is similar to document.getelementsbytagname(), except that it only searches for elements that are descendants ...
... elements is a live htmlcollection of elements with a matching tag name, in the order they appear. if no elements are found, the htmlcollection is empty. element is the element from where the search starts. only the element's descendants are included, not the element itself. tagname is the qualified name to look for. the special string "*" represents all elements. for compatibility with xhtml, lower-case should be used. example // check the status of each data cell in a table const table = document.getelementbyid('forecast-table'); const cells = table.getelementsbytagname('td'); for (let cell of cells) { let status = cell.getattribute('data-status'); if (status === 'open') { // grab the data } } specifications specification status comment domthe def...
Element.insertAdjacentText() - Web APIs
'afterbegin': just inside the element, before its first child. ...
...into the form element, then press the insert before and insert after buttons to insert it before or after the existing paragraph text using insertadjacenttext(). note that the existing text node is not added to — further text nodes are created containing the new additions. ...
Element: mousemove event - Web APIs
its functionality is simple: the thickness of the line is set to 1, and the color is always black. ...
...its functionality is simple: the thickness of the line is set to 1, and the color is always black. ...
Element.requestFullscreen() - Web APIs
t value is "auto", which indicates that the browser should decide what to do. return value a promise which is resolved with a value of undefined when the transition to full screen is complete. exceptions rather than throw a traditional exception, the requestfullscreen() procedure announces error conditions by rejecting the promise it has returned. the rejection handler receives one of the following exception values: typeerror the typeerror exception may be delivered in any of the following situations: the document containing the element isn't fully active; that is, it's not the current active document. the element is not contained by a document. the element is not permitted to use the "fullscreen" feature, either because of feature policy configuration or other access control...
...ol features. the element and its document are the same node. usage notes compatible elements an element that you wish to place into full-screen mode has to meet a small 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, y...
Element.scrollLeft - Web APIs
ax getting the value // get the number of pixels scrolled var sleft = element.scrollleft; sleft is an integer representing the number of pixels that element has been scrolled from the left edge. setting the value // set the number of pixels scrolled element.scrollleft = 10; scrollleft can be specified as any integer value. however: if the element can't be scrolled (e.g., it has no overflow), scrollleft is set to 0. if specified as a value less than 0 (greater than 0 for right-to-left elements), scrollleft is set to 0. if specified as a value greater than the maximum that the content can be scrolled, scrollleft is set to the maximum. example html <div id="container"> <div id="content">click the button to slide right!</div> </div> <button id="slide" type="button">slide right...
...ft elements), scrollleft is set to 0. if specified as a value greater than the maximum that the content can be scrolled, scrollleft is set to the maximum. example html <div id="container"> <div id="content">click the button to slide right!</div> </div> <button id="slide" type="button">slide right</button> css #container { width: 100px; height: 100px; border: 1px solid #ccc; overflow-x: scroll; } #content { width: 250px; background-color: #ccc; } javascript const button = document.getelementbyid('slide'); button.onclick = function () { document.getelementbyid('container').scrollleft += 20; }; result specifications specification status comment css object model (cssom) view modulethe definition of 'scrollleft' in that specification. ...
Element.setAttributeNS() - Web APIs
value is the desired string value of the new attribute. ...
... value is the desired string value of the new attribute. ...
Element.toggleAttribute() - Web APIs
the toggleattribute() method of the element interface toggles a boolean attribute (removing 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 va...
...ce 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 used to toggle the readonly attribute of a <input>. html <input value="text"> <button>toggleattribute("readonly")</button> javascript var button = document.queryselector("button"); var input = document.queryselector("input"); button.addeventlistener("click", function(){ input.toggleattribute("readonly"); }); result dom methods dealing with element's at...
Event.cancelable - Web APIs
Web › API › Event › cancelable
gating away from the page, respectively. custom events created by other javascript code control if they can be canceled when they are created. syntax bool = event.cancelable; value the result is a boolean, which is true if the event can be canceled. ...
... to cancel an event, call the preventdefault() method on the event. ...
Event.composed - Web APIs
Web › API › Event › composed
ste, 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 into the element's shadow dom as t...
...lick event is always able to propagate across shadow boundaries. you'll notice a difference in the value of composedpath for the two elements. the <open-shadow> element's composed path is this: array [ p, shadowroot, open-shadow, body, html, htmldocument https://mdn.github.io/web-components-examples/composed-composed-path/, window ] whereas the <closed-shadow> element's composed path is a follows: array [ closed-shadow, body, html, htmldocument https://mdn.github.io/web-components-examples/composed-composed-path/, window ] in the second case, the event listeners only propagate as far as the <closed-shadow> element itself, but not to the nodes inside the shadow boundary. specifications specification status comment domthe definition of 'composed' in that spe...
Event.msConvertURL() - Web APIs
d 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. ...
... targeturl [in, optional] type: url the target url. return value this method does not return a value. ...
Event - Web APIs
Web › API › Event
ested elements, each with its own handler(s), event processing can become very complicated—especially where a parent element receives the very same event as its child elements because "spatially" they overlap so the event technically occurs in both, and the processing order of such events depends on the event bubbling and capture settings of each handler triggered. interfaces based on event below is a list of interfaces which are based on the main event interface, with links to their respective documentation in the mdn api reference. note that all event interfaces have names which end in "event". animationevent audioprocessingevent beforeinputevent beforeunloadevent blobevent clipboardevent closeevent compositionevent cssfontfaceloadevent customevent devicelightevent devic...
...his is the object to which the event is currently slated to be sent. it's possible this has been changed along the way through retargeting. event.deeppath an array of dom nodes through which the event has bubbled. event.defaultprevented read only indicates whether or not the call to event.preventdefault() canceled the event. event.eventphase read only indicates which phase of the event flow is being processed. event.explicitoriginaltarget read only the explicit original target of the event (mozilla-specific.) event.originaltarget read only the original target of the event, before any retargetings. (mozilla-specific.) event.returnvalue a historical property introduced by internet explorer and eventually adopted into the dom specification in order to ensure existing sites ...
EventSource - Web APIs
example, eventsource is a useful approach for handling things like social media status updates, news feeds, or delivering data into a client-side storage mechanism like indexeddb or web storage. when not used over http/2, sse suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is per browser and set to a very low number (6). the issue has been marked as "won't fix" in chrome and firefox. this limit is per browser + domain, so that means that you can open 6 sse connections across all of the tabs to www.example1.com and another 6 sse connections to www.example2.com. (from stackoverflow). when using http/2, the maximum number of simultaneous http streams is negotiated between the server and the client (defau...
...<li> element and writes the message's data into it, then appends the new element to the list element already in the document. note: you can find a full example on github — see simple sse demo using php. to listen to named events, you'll require a listener for each type of event sent. ...
FeaturePolicy - Web APIs
the featurepolicy interface of the feature policy api represents the set of policies applied to the current execution context. featurepolicy methods featurepolicy.allowsfeature returns a boolean that indicates whether or not a particular feature is enabled in the specified context. featurepolicy.features returns a list of names of all features supported by the user agent. feature whose name appears on the list might not be allowed by the feature policy of the current execution context and/or might not be accessible because of user's permissions. featurepolicy.allowedfeatures returns a list of names of all features supported by the user agent and allowed by the feature policy. note that features appearing on this list might still be behind a user permission. featurepolicy.getallo...
... specification specification status comment feature policy editor's draft initial definition. ...
File.getAsBinary() - Web APIs
Web › API › File › getAsBinary
k for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. obsolete since gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4)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. summary the getasbinary method allows to access the file's data in raw binary format. note: this method is obsolete; you should use the filereader method readasbinarystring() or readasarraybuffer() instead. syntax var binary = instanceoffile.getasbinary(); returns a string. example // fileinput is an htmlinputelement: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // f...
...use the filereader method readasbinarystring() or readasarraybuffer() instead. syntax var binary = instanceoffile.getasbinary(); returns a string. ...
FileReaderSync.readAsArrayBuffer() - Web APIs
the readasarraybuffer() method of the filereadersync interface allows to read file or blob objects in a synchronous way into an arraybuffer. this interface is only available in workers as it enables synchronous i/o that could potentially block. syntax arraybuffer readasarraybuffer( in blob blob ); parameters blob the dom file or blob to read into the file or arraybuffer. return value an arraybuffer representing the file's data. exceptions the following exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. ...
...blob blob ); parameters blob the dom file or blob to read into the file or arraybuffer. return value an arraybuffer representing the file's data. exceptions the following exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by the resource is unsafe for a use from the web (like it is a system file). notreadableerror is raised when the resource cannot be read due to a permission problem, like a concurrent lock. encodingerror is raised when the resource is ...
FileReaderSync.readAsBinaryString() - Web APIs
note: this method is deprecated in favor of readasarraybuffer(). the readasbinarystring() method of the filereadersync interface allows to read file or blob objects in a synchronous way into an domstring. this interface is only available in workers as it enables synchronous i/o that could potentially block. syntax readasbinarystring(file); readasbinarystring(blob); parameters blob the dom file or blob to read. return value an domstring representing the input data. exceptions the following exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. ...
...inarystring(file); readasbinarystring(blob); parameters blob the dom file or blob to read. return value an domstring representing the input data. exceptions the following exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by the resource is unsafe for a use from the web (like it is a system file). notreadableerror is raised when the resource cannot be read due to a permission problem, like a concurrent lock. encodingerror is raised when the resource is ...
FileReaderSync.readAsDataURL() - Web APIs
the readasdataurl() method of the filereadersync interface allows to read file or blob objects in a synchronous way into an domstring representing a data url. this interface is only available in workers as it enables synchronous i/o that could potentially block. syntax readasdataurl(file); readasdataurl(blob); parameters blob the dom file or blob to read. return value an domstring representing the input data as a data url. exceptions the following exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. ...
...rl(file); readasdataurl(blob); parameters blob the dom file or blob to read. return value an domstring representing the input data as a data url. exceptions the following exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by the resource is unsafe for a use from the web (like it is a system file). notreadableerror is raised when the resource cannot be read due to a permission problem, like a concurrent lock. encodingerror is raised when the resource is ...
FileReaderSync.readAsText() - Web APIs
the readastext() method of the filereadersync interface allows to read file or blob objects in a synchronous way into an domstring. this interface is only available in workers as it enables synchronous i/o that could potentially block. syntax readastext(file); readastext(blob); readastext(file, encoding); readastext(blob, encoding); parameters blob the dom file or blob to read. encoding the optional parameter specifies encoding to be used (e.g., iso-8859-1 or utf-8). if not present, the method will apply a detection algorithm for it. return value an domstring representing the input data. exceptions the following exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been er...
...(e.g., iso-8859-1 or utf-8). if not present, the method will apply a detection algorithm for it. return value an domstring representing the input data. exceptions the following exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by the resource is unsafe for a use from the web (like it is a system file). notreadableerror is raised when the resource cannot be read due to a permission problem, like a concurrent lock. encodingerror is raised when the resource is ...
File and Directory Entries API support in Firefox - Web APIs
ry filesystemdirectoryentrysync directoryentrysync filesystemdirectoryreader directoryreader filesystemdirectoryreadersync directoryreadersync filesystementry entry filesystementrysync entrysync filesystemfileentry fileentry filesystemfileentrysync fileentrysync be sure to account for this in your code by allowing for both names. hopefully chrome will be updated soon to use the newer names! to ensure your code will work in both chrome and other browsers, you can include code similar to the following: var filesystemdirectoryentry = window.filesystemdirectoryentry || window.directoryentry; var filesystementry = window.filesystementry || window.entry; limitations in firefox next, let's look at limitat...
... work in both chrome and other browsers, you can include code similar to the following: var filesystemdirectoryentry = window.filesystemdirectoryentry || window.directoryentry; var filesystementry = window.filesystementry || window.entry; limitations in firefox next, let's look at limitations of the firefox implementation of the api. in broad strokes, those limitations can be summarized as follows: content scripts can't create file systems or initiate access to a file system. there are only two ways to get access to file system entries at this time: the <input> element, using the htmlinputelement.webkitentries property to access an array of filesystementry objects describing file system entries you can then read. using drag and drop by calling the datatransferitem.getasentry()...
File and Directory Entries API - Web APIs
ped onto the file chooser (bug 1326031). if htmlinputelement.webkitdirectory is true, the <input> element is instead a directory picker, and you get filesystemdirectoryentry objects for each selected directory. asynchronous api the asynchronous api should be used for most operations, to prevent file system accesses from blocking the entire browser if used on the main thread. it includes the following interfaces: filesystem represents a file system. filesystementry the basic interface representing a single entry in a file system. this is implemented by other interfaces which represent files or directories. filesystemfileentry represents a single file in a file system. filesystemdirectoryentry represents a single directory in a file system. filesystemdirectoryreader created by ca...
...they're available on the window object and implemented in localfilesystem: requestfilesystem() and resolvelocalfilesystemurl(). synchronous api the synchronous api is should only be used in workers; these calls block until they're finished executing, and simply return the results instead of using callbacks. using them on the main thread will block the browser, which is naughty. the interfaces below otherwise mirror the ones from the asynchronous api. filesystemsync represents a file system. filesystementrysync the basic interface representing a single entry in a file system. this is implemented by other interfaces which represent files or directories. filesystemfileentrysync represents a single file in a file system. filesystemdirectoryentrysync represents a single directory in a ...
FontFace.display - Web APIs
Web › API › FontFace › display
the display property of the fontface interface determines how a font face is displayed based on whether and when it is downloaded and ready to use. 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. failure period if the font face still is not loaded, the fallback font will b...
...y 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. failure period if the font face still is not loaded, the fallback font will be shown and no swap will occur. syntax var display = fontface.display fontface.display = display value a cssomstring with one of the following values. 'auto': use the font display strategy provided by the user agent. 'block': gives the font face a short block period and an infinite swap period. the spec recommends 3 seconds for the block period, though this may vary from browser to browser. 'fallback': gives the font face a short block period and a short swap period. the spec recommends 100 ms or less for the block period and 3 ...
FormData.get() - Web APIs
Web › API › FormData › get
n a formdata object. if you expect multiple values and want all of them, use the getall() method instead. note: this method is available in web workers. syntax formdata.get(name); parameters name a usvstring representing the name of the key you want to retrieve. return value a formdataentryvalue containing the value. if the key doesn't exist, the method returns null. ...
...ng representing the name of the key you want to retrieve. return value a formdataentryvalue containing the value. if the key doesn't exist, the method returns null. example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following get() function will only return the first username value appended: formdata.get('username'); // returns "chris" specifications specification status comment xmlhttprequestthe definition of 'get()' in that specification. living standard ...
FormData.getAll() - Web APIs
Web › API › FormData › getAll
ted with a given key from within a formdata object. note: this method is available in web workers. syntax formdata.getall(name); parameters name a usvstring representing the name of the key you want to retrieve. returns an array of formdataentryvalues whose key matches the value passed in the name parameter. if the key doesn't exist, the method returns an empty list. ...
...rieve. returns an array of formdataentryvalues whose key matches the value passed in the name parameter. if the key doesn't exist, the method returns an empty list. example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following getall() function will return both username values in an array: formdata.getall('username'); // returns ["chris", "bob"] specifications specification status comment xmlhttprequestthe definition of 'getall()' in that specification. living standard ...
FormData.has() - Web APIs
Web › API › FormData › has
the has() method of the formdata interface returns a boolean stating whether a formdata object contains a certain key. note: this method is available in web workers. syntax formdata.has(name); parameters name a usvstring representing the name of the key you want to test for. returns a boolean. ...
...ethod of the formdata interface returns a boolean stating whether a formdata object contains a certain key. note: this method is available in web workers. syntax formdata.has(name); parameters name a usvstring representing the name of the key you want to test for. returns a boolean. ...
FormData - Web APIs
Web › API › FormData
(var p of myformdata.entries()). note: this feature is available in web workers. constructor formdata() creates a new formdata object. methods formdata.append() appends a new value onto an existing key inside a formdata object, or adds the key if it does not already exist. formdata.delete() deletes a key/value pair from a formdata object. formdata.entries() returns an iterator allowing to go through all key/value pairs contained in this object. formdata.get() returns the first value associated with a given key from within a formdata object. formdata.getall() returns an array of all the values associated with a given key from within a formdata. formdata.has() returns a boolean stating whether a formdata object contains a certain key. formdata.keys() returns an iterato...
...to go through all key/value pairs contained in this object. formdata.get() returns the first value associated with a given key from within a formdata object. formdata.getall() returns an array of all the values associated with a given key from within a formdata. formdata.has() returns a boolean stating whether a formdata object contains a certain key. formdata.keys() returns an iterator allowing to go through all keys of the key/value pairs contained in this object. formdata.set() sets a new value for an existing key inside a formdata object, or adds the key/value if it does not already exist. formdata.values() returns an iterator allowing to go through all values contained in this object. specifications specification status comment xmlhttprequestthe de...
Frame Timing API - Web APIs
w "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. performanceentry.duration set to a timestamp indicating the difference between ...
... set to the document's address. performanceentry.starttime set to the domhighrestimestamp when the frame was started. performanceentry.duration set to a timestamp indicating the difference between the starttimes of two successive frames. this data, particularly the duration timestamp, can be used to help identify performance problems. 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 recorded in the browser's performance timeline, the application is notified of the event via the observer's callback function that was specified when the observer was created. to observe "frame" performance entry types, the application first creates a performanceobserver object with a sp...
Gamepad.buttons - Web APIs
Web › API › Gamepad › buttons
(true) or unpressed (false). the value property is a floating point value used to enable representing analog buttons, such as the triggers on many modern gamepads. the values are normalized to the range 0.0 – 1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed. ...
...mepads needs a webkit prefix and the button values are stores as an array of double values, whereas in firefox navigator.getgamepads doesn't need a prefix, and the button values are stored as an array of gamepadbutton objects; it is the gamepadbutton.value or gamepadbutton.pressed properties of these we need to access, depending on what type of buttons they are. in this simple example i've just allowed either. function gameloop() { if(navigator.webkitgetgamepads) { var gp = navigator.webkitgetgamepads()[0]; if(gp.buttons[0] == 1) { b--; } else if(gp.buttons[1] == 1) { a++; } else if(gp.buttons[2] == 1) { b++; } else if(gp.buttons[3] == 1) { a--; } } else { var gp = navigator.getgamepads()[0]; if(gp.buttons[0].value > 0 || gp.butto...
Gamepad - Web APIs
Web › API › Gamepad
a gamepad object can be returned in one of two ways: via the gamepad property of the gamepadconnected and gamepaddisconnected events, or by grabbing any position in the array returned by the navigator.getgamepads() method. properties gamepad.axes read only an array representing the controls with axes present on the device (e.g. analog thumb sticks). gamepad.buttons read only an array of gamepadbutton objects representing the buttons present on the device. ...
... only an integer that is auto-incremented to be unique for each device currently connected to the system. gamepad.mapping read only a string indicating whether the browser has remapped the controls on the device to a known layout. gamepad.timestamp read only a domhighrestimestamp representing the last time the data for this gamepad was updated. experimental extensions to gamepad the following interfaces are defined in the gamepad extensions specification, and provide access to experimental features like haptic feedback and webvr controller pose information. gamepad.hand read only an enum defining what hand the controller is being held in, or is most likely to be held in. gamepad.hapticactuators read only an array containing gamepadhapticactuator objects, each of which repre...
GeolocationPositionError - Web APIs
the geolocationpositionerror interface represents the reason of an error occurring when using the geolocating device. properties the geolocationpositionerror interface doesn't inherit any property. geolocationpositionerror.code read only secure context returns an unsigned short representing the error code. ...
... value associated constant description 1 permission_denied the acquisition of the geolocation information failed because the page didn't have the permission to do it. 2 position_unavailable the acquisition of the geolocation failed because at least one internal source of position returned an internal error. 3 timeout the time allowed to acquire the geolocation, defined by positionoptions.timeout information was reached before the information was obtained. geolocationpositionerror.message read only secure context returns a human-readable domstring describing the details of the error. specifications note that this is primarily intended for debugging use and not to be shown directly in a user interface. methods...
GlobalEventHandlers.ontransitioncancel - Web APIs
means that the value of transition-delay doesn't affect the value of elapsedtime, which is zero until the delay period ends and the animation begins. example in this example, we use the transitionrun and transitionend events to detect when the transition begins and ends, to cause a text update to occur during the transition. ...
...ct when the transition begins and ends, to cause a text update to occur during the transition. this could also be used to trigger animations or other effects, to allow chaining of reactions. in addition, we also use a click event to make the box dissappear (display: none;), showing how it triggers the transitioncancel event to fire. html this simply creates a <div> which we'll style with css below to make into a box that resizes and changes color and such. <div class="box"></div> css the css below styles the box and applies a transition effect which makes the box's color and size change, and causes the box to rotate, while the mouse cursor hovers over it. .box { margin-left: 70px; margin-top: 30px; border-style: solid; border-width: 1px; display: block; width: 100px; hei...
Audio() - Web APIs
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 current download rate, you should be able to play the audio through to the end without interruption. listen for...
...audio> element when there's enough audio available to begin playback, although interruptions may occur). listen for the canplaythrough event. it is sent when it's estimated that the audio should be able to play to the end without interruption. the event-based approach is best: myaudioelement.addeventlistener("canplaythrough", event => { /* the audio is now playable; play it if permissions allow */ myaudioelement.play(); }); memory usage and management if all references to an audio element created using the audio() constructor are deleted, the element itself won't be removed from memory by the javascript runtime's garbage collection mechanism if playback is currently underway. instead, the audio will keep playing and the object will remain in memory until playback ends or is paused (...
msAudioCategory - Web APIs
luding data type and what it represents. value description 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. ...
... 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. *note that if msaudiocategory is set to communications, msrealtime is automatically set to true. yes foregroundonlymedia games or other sounds designe...
HTMLAudioElement - Web APIs
the htmlaudioelement interface provides access to the properties of <audio> elements, as well as methods to manipulate them. it's based on, and inherits properties and methods from, the htmlmediaelement interface. ...
...turns a new htmlaudioelement object, optionally starting the process of loading an audio file into it if the file url is given. properties no specific properties; inherits properties from its parent, htmlmediaelement, and from htmlelement. methods inherits methods from its parent, htmlmediaelement, and from htmlelement. it offers no methods of its own. obsolete mozilla-only methods the following methods are non-standard and should not be used. mozcurrentsampleoffset() returns the number of samples form the beginning of the stream that have been written so far into the audio stream created by calling mozwriteaudio(). mozsetup() sets up the audio stream to allow writing, given the number of audio channels (1 or 2) and the sample rate in khz. mozwriteaudio() writes a ...
HTMLBRElement - Web APIs
the htmlbrelement interface represents a html line break element (<br>). it inherits from htmlelement. ...
...dde4" stroke-width="2px" /><text x="426" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlbrelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmlbrelement.clear is a domstring indicating the flow of text around floating objects. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlbrelement' in that specification. living standard no change from html5 html5the definition of 'htmlbrelement' in that specification. recommendation no cha...
HTMLBodyElement - Web APIs
the htmlbodyelement interface provides special properties (beyond those inherited from the regular htmlelement interface) for manipulating <body> elements. ...
...nhashchange, onlanguagechange, onload, onmessage, onoffline, ononline, onpopstate, onresize, onstorage, and onunload, have been moved to windoweventhandlers. htmlbodyelement implements this interface. html 5.1the definition of 'htmlbodyelement' in that specification. recommendation html5the definition of 'htmlbodyelement' in that specification. recommendation the following properties are now obsolete: alink, bgcolor, background, link, text, and vlink. the following properties have been added: onafterprint, onbeforeprint, onbeforeunload, onblur, onerror, onfocus, onhashchange, onload, onmessage, onoffline, ononline, onpopstate, onresize, onstorage, and onunload. document object model (dom) level 2 html specificationthe definition of 'htmlbodyelement'...
HTMLCanvasElement.toDataURL() - Web APIs
lue a domstring containing the requested data uri. exceptions securityerror the canvas's bitmap is not origin clean; at least some of its contents have or may have been loaded from a site other than the one from which the document itself was loaded. ...
...color in this example): html <img class="grayscale" src="mypicture.png" alt="description of my picture" /> javascript window.addeventlistener('load', removecolors); function showcolorimg() { th...
HTMLDialogElement.show() - Web APIs
from there you can click the cancel button to close the dialog (via the htmldialogelement.close() method), or submit the form via the submit button. ...
...from there you can click the cancel button to close the dialog (via the htmldialogelement.close() method), or submit the form via the submit button. ...
HTMLFieldSetElement - Web APIs
the htmlfieldsetelement interface provides special properties and methods (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of <fieldset> elements. ...
...t validate. specifications specification status comment html living standardthe definition of 'htmlfieldsetelement' in that specification. living standard html 5.1the definition of 'htmlfieldsetelement' in that specification. recommendation html5the definition of 'htmlfieldsetelement' in that specification. recommendation the following properties have been added: disabled, elements, name, type, valdiationmessage, validity, and willvalidate. the following methods have been added: checkvalidity(), setcustomvalidity(). document object model (dom) level 2 html specificationthe definition of 'htmlfieldsetelement' in that specification. obsolete no change document object model (dom) level 1 specificatio...
HTMLFontElement.color - Web APIs
the obsolete htmlfontelement.color property is a domstring that reflects the color html attribute, containing either a named color or a color specified in the hexadecimal #rrggbb format. ...
... the obsolete htmlfontelement.color property is a domstring that reflects the color html attribute, containing either a named color or a color specified in the hexadecimal #rrggbb format. ...
HTMLFontElement.face - Web APIs
a domstring that reflects the face html attribute, containing a comma-separated list of one or more font names. the document text, in the default style, is rendered as the first font face that the client's browser supports. if no font listed is installed on the local system, the browser typically defaults to the proportional or fixed-width font for that system. ...
...reflects the face html attribute, containing a comma-separated list of one or more font names. the document text, in the default style, is rendered as the first font face that the client's browser supports. if no font listed is installed on the local system, the browser typically defaults to the proportional or fixed-width font for that system. ...
HTMLFontElement.size - Web APIs
the obsolete htmlfontelement.size property is a domstring that reflects the size html attribute. it contains either an integer number in the range of 1-7 or a relative value to increase/decrease the value of the size attribute of the <basefont> element. ...
... the obsolete htmlfontelement.size property is a domstring that reflects the size html attribute. it contains either an integer number in the range of 1-7 or a relative value to increase/decrease the value of the size attribute of the <basefont> element. ...
HTMLFormElement.elements - Web APIs
document's forms property. syntax nodelist = htmlformelement.elements value an htmlformcontrolscollection containing all non-image controls in the form. this is a live collection; if form controls are added to or removed from the form, this collection will update to reflect the change. ...
...ive collection; if form controls are added to or removed from the form, this collection will update to reflect the change. the form controls in the returned collection are in the same order in which they appear in the form by following a preorder, depth-first traversal of the tree. this is called tree order. the elements included by htmlformelement.elements and htmlformelement.length are the following: <button> <fieldset> <input> (with the exception that any whose type is "image" are omitted for historical reasons) <object> <output> <select> <textarea> no other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms. example quick syntax example in this example, we see how to obtain the...
HTMLHRElement - Web APIs
the htmlhrelement interface provides special properties (beyond those of the htmlelement interface it also has available to it by inheritance) for manipulating <hr> elements. ...
...m its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlhrelement' in that specification. living standard the color property has been added, as an obsolete property, to increase compatibility with the existing web. html5the definition of 'htmlhrelement' in that specification. recommendation following properties are now obsolete: align, noshade, size, and width. document object model (dom) level 2 html specificationthe definition of 'htmlhrelement' in that specification. obsolete no change from document object model (dom) level 1 specification. document object model (dom) level 1 specificationthe definition of 'htmlhrelement' in that specification. obsolete ini...
HTMLHeadElement - Web APIs
the htmlheadelement interface contains the descriptive information, or metadata, for a document. this object inherits all of the properties and methods described in the htmlelement interface. ...
...ement. specifications specification status comment html living standardthe definition of 'htmlheadelement' in that specification. living standard html 5.1the definition of 'htmlheadelement' in that specification. recommendation no change from html5. html5the definition of 'htmlheadelement' in that specification. recommendation the following property has been removed: profile. document object model (dom) level 2 html specificationthe definition of 'htmlheadelement' in that specification. obsolete no change document object model (dom) level 1 specificationthe definition of 'htmlheadelement' in that specification. obsolete initial definition ...
HTMLImageElement.border - Web APIs
integer value specifying the thickness of the border that should surround the image, in css pixels. a value of 0, or an empty string, indicates that there should be no border drawn. the default value of border is 0 usage notes do not use border. it is obsolete. instead, use the css border property and its longhand properties to establish borders around images. ...
...hat should surround the image, in css pixels. a value of 0, or an empty string, indicates that there should be no border drawn. the default value of border is 0 usage notes do not use border. it is obsolete. instead, use the css border property and its longhand properties to establish borders around images. ...
HTMLImageElement.complete - Web APIs
the read-only htmlimageelement interface's complete attribute is a boolean value which indicates whether or not the image has completely loaded. syntax let doneloading = htmlimageelement.complete; value a boolean value which is true if the image has completely loaded; 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 ...
...n the lightbox. while ideally this command wouldn't even be executed if the image hasn't fully loaded, for improved reliability you want to check to ensure this is the case. so the fixredeyecommand() function, which is called by the button that triggers red-eye removal, checks the value of the lightbox image's complete property before attempting to do its work. this is demonstrated in the code below. let lightboxelem = document.queryselector("#lightbox"); let lightboximgelem = lightboxelem.queryselector("img"); let lightboxcontrolselem = lightboxelem.queryselector(".toolbar"); async function loadimage(url, elem) { return new promise((resolve, reject) => { elem.onload = () => resolve(elem); elem.onerror = reject; elem.src = url; }); } async function lightbox(url) { lightb...
HTMLImageElement.crossOrigin - Web APIs
ests by the element will use cors, regardless of what domain the fetch is from. if crossorigin is an empty string (""), the anonymous mode is selected. example in this example, a new <img> element is created and added to the document, loading the image with the anonymous state; the image will be loaded using cors and credentials will be used for all cross-origin loads. javascript the code below demonstrates setting the crossorigin property on an <img> element to configure cors access for the fetch of a newly-created image. const imageurl = "https://mdn.mozillademos.org/files/16797/clock-demo-400px.png"; const container = document.queryselector(".container"); function loadimage(url) { const image = new image(200, 200); image.addeventlistener("load", () => container.prepend(imag...
...ymous"; image.alt = ""; image.src = url; } loadimage(imageurl); html <div class="container"> <p>here's a paragraph. it's a very interesting paragraph. you are captivated by this paragraph. keep reading this paragraph. okay, now you can stop reading this paragraph. thanks for reading me.</p> </div> css body { font: 1.125rem/1.5, helvetica, sans-serif; } .container { display: flow-root; width: 37.5em; border: 1px solid #d2d2d2; } img { float: left; padding-right: 1.5em; } output { background: rgba(100, 100, 100, 0.1); font-family: courier, monospace; width: 95%; } result specifications specification status comment html living standardthe definition of 'htmlimageelement.crossorigin' in that specification. unknown ...
HTMLImageElement.decode() - Web APIs
syntax var promise = htmlimageelement.decode(); parameters none. return value a promise which is resolved once the image data is ready to be used. exceptions encodingerror a domexception indicating that an error occurred while decoding the image. ...
...s (for example, in an online photo album), you can present a low resolution thumbnail image initially and then replace that image with the full-resolution image by instantiating a new htmlimageelement, setting its source to the full-resolution image's url, then using decode() to get a promise which is resolved once the full-resolution image is ready for use. at that time, you can then replace the low-resolution image with the full-resolution one that's now available. examples the following example shows how to use the decode() method to control when an image is appended to the dom. without a promise-returning method, you would add the image to the dom in a load event handler, such as by using the img.onload event handler, and by handling the error in the error event's handler. const img = ...
HTMLImageElement.loading - Web APIs
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 establishing the intrinsic aspect ratio in this manner, you prevent elements from shifting around while the docu...
...xplicitly 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"; let newimg = document.createelement...
HTMLImageElement.longDesc - Web APIs
optional added details beyond the short description provided in the title attribute. syntax descurl = htmlimageelement.longdesc; htmlimageelement.longdesc = descurl; value a domstring which may be either an empty string (indicating that no long description is available) or the url of a file containing a long form description of the image's contents. for example, if the image is a png of a flowchart. the longdesc property could be used to provide an explanation of the flow of control represented by the chart, using only text. this can be used by readers both as an explanation, but also as a substitute for visually-impaired users. usage notes this property is obsolete and should no longer be used. instead of using longdesc to provide a link to a detailed description of an image, encaps...
...f the flow of control represented by the chart, using only text. this can be used by readers both as an explanation, but also as a substitute for visually-impaired users. usage notes this property is obsolete and should no longer be used. instead of using longdesc to provide a link to a detailed description of an image, encapsulate the image within a link using the <a> element. consider the following older html: <img src="taco-tuesday.jpg" longdesc="image-descriptions/taco-tuesday.html"> here, the longdesc is used to indicate that the user should be able to access a detailed description of the image taco-tuesday.jpg in the html file image-descriptions/taco-tuesday.html. this can be easily converted into modern html: <a href="image-descriptions/taco-tuesday.html"> <img src="taco-tuesd...
HTMLImageElement.sizes - Web APIs
the htmlimageelement property sizes allows you to specify the layout width of the image for each of a list of media conditions. this provides the ability to automatically select among different images—even images of different orientations or aspect ratios—as the document state changes to match different media conditions. each condition is specified using the same conditional format used by media queries. syntax let sizes = htmlimageelement.sizes; htmlimageelement.sizes = sizes; value a usvstring containing a comma-separated list of source size descriptors followed by an optional fallback size. each source size descriptor is comprised of a media condition, then at least one whitespace character, then the source size value to use for the image when the media condition evaluates to tru...
... source size value is a css length. it may be specified using font-relative units (such as em or ex), absolute units (such as px or cm), or the vw unit, which lets you specify the width as a percentage of the viewport width (1vw being 1% of the viewport width). note: the source size value must not be specified as a percentage of the container size; that is, lengths such as 50% or 100% are not allowed, as there would be uncertainty as to what the specified value is a percentage of. example in this example, a blog-like layout is created, displaying some text and an image which for which three size points are specified, depending on the width of the window. three versions of the image are also available, with their widths specified. the browser takes all of this information and selects an i...
HTMLLIElement - Web APIs
the htmllielement interface exposes specific properties and methods (beyond those defined by regular htmlelement interface it also has available to it by inheritance) for manipulating list elements. ...
...of an <ol> element, the property has no meaning. methods no specific method; inherits properties from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmllielement' in that specification. living standard html5the definition of 'htmllielement' in that specification. recommendation the following property is now obsolete: type. document object model (dom) level 2 html specificationthe definition of 'htmllielement' in that specification. obsolete no change from document object model (dom) level 1 specification. document object model (dom) level 1 specificationthe definition of 'htmllielement' in that specification. obsolete initial definition. ...
HTMLLabelElement - Web APIs
the htmllabelelement interface gives access to properties specific to <label> elements. it inherits methods and properties from the base htmlelement interface. ...
... specific methods; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmllabelelement' in that specification. living standard html5the definition of 'htmllabelelement' in that specification. recommendation the property accesskey is now defined on htmlelement. the following property has been added: control. document object model (dom) level 2 html specificationthe definition of 'htmllabelelement' in that specification. obsolete no change from document object model (dom) level 1 specification. document object model (dom) level 1 specificationthe definition of 'htmllabelelement' in that specification. obsolete initial definition. ...
HTMLLinkElement - Web APIs
the relationship of those resources to a document and vice-versa (corresponds to <link> element; not to be confused with <a>, which is represented by htmlanchorelement). this object inherits all of the properties and methods of the htmlelement interface. ...
... its parent, htmlelement, and linkstyle. specifications specification status comment preload candidate recommendation defines <link rel="preload">, and the as property. note that currently firefox only supports preloading of cacheable resources. html living standardthe definition of 'htmllinkelement' in that specification. living standard adds the following properties: crossorigin, referrerpolicy, and as. html 5.1the definition of 'htmllinkelement' in that specification. recommendation html5the definition of 'htmllinkelement' in that specification. recommendation the following properties are now obsolete: charset, rev, and shape. the following properties have been added: rellist, and sizes. document obj...
HTMLMarqueeElement - Web APIs
the htmlmarqueeelement interface provides methods to manipulate <marquee> elements. it inherits properties and methods from the htmlelement interface. ...
...arqueeelement.scrollamount sets the amount of scrolling at each interval in pixels. the default value is 6. htmlmarqueeelement.scrolldelay sets the interval between each scroll movement in milliseconds. the default value is 85. note that any value smaller than 60 is ignored and the value 60 is used instead, unless truespeed is true. htmlmarqueeelement.truespeed by default, scrolldelay values lower than 60 are ignored. if truespeed is true, then those values are not ignored. htmlmarqueeelement.vspace sets the vertical margin. htmlmarqueeelement.width sets the width in pixels or percentage value. event handlers htmlmarqueeelement.onbounce fires when the marquee has reached the end of its scroll position. it can only fire when the behavior attribute is set to alternate. htmlmarqu...
HTMLMediaElement.defaultPlaybackRate - Web APIs
the value 0.0 is invalid and throws a not_supported_err exception. ...
...the value 0.0 is invalid and throws a not_supported_err exception. ...
HTMLMediaElement.srcObject - Web APIs
media associated with the htmlmediaelement. the object can be a mediastream, a mediasource, a blob, or a file (which inherits from blob). note: as of march 2020, only safari supports setting objects other than mediastream. until other browsers catch up, for mediasource, blob and file, consider falling back to creating a url with url.createobjecturl() and assign it to htmlmediaelement.src. see below for an example. syntax var sourceobject = htmlmediaelement.srcobject; htmlmediaelement.srcobject = sourceobject; value a mediastream, mediasource, blob, or file object (though see the compatibility table for what is actually supported). usage notes older versions of the media source specification required using createobjecturl() to create an object url then setting src to that url. now y...
...am = await navigator.mediadevices.getusermedia({video: true}); const video = document.createelement('video'); video.srcobject = mediastream; in this example, a new mediasource is assigned to a newly-created <video> element. const mediasource = new mediasource(); const video = document.createelement('video'); video.srcobject = mediasource; supporting fallback to the src property the examples below support older browser versions that require you to create an object url and assign it to src if srcobject isn't supported. first, a mediastream from a camera is assigned to a newly-created <video> element, with fallback for older browsers. const mediastream = await navigator.mediadevices.getusermedia({video: true}); const video = document.createelement('video'); if ('srcobject' in video) { vi...
HTMLMetaElement - Web APIs
the htmlmetaelement interface contains descriptive metadata about a document. it inherits all of the properties and methods described in the htmlelement interface. ...
...terpret the value of a meta-data property. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlmetaelement' in that specification. living standard html5the definition of 'htmlmetaelement' in that specification. recommendation the following property is now obsolete: scheme. document object model (dom) level 2 html specificationthe definition of 'htmlmetaelement' in that specification. obsolete no change from document object model (dom) level 1 specification. document object model (dom) level 1 specificationthe definition of 'htmlmetaelement' in that specification. obsolete initial definition. ...
HTMLMeterElement - Web APIs
ter> elements expose the htmlmeterelement interface, which provides special properties and methods (beyond the htmlelement object interface they also have available to them by inheritance) for manipulating the layout and presentation of <meter> elements. ...
...onsolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlmeterelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} 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 doubl...
HTMLObjectElement.setCustomValidity - Web APIs
y() method of the htmlobjectelement interface sets a custom validity message for the element. syntax htmlobjectelement.setcustomvalidity(message); parameters error the message to use for validity errors. return value undefined exceptions none. ...
..., too low or too high. additionally you must call the reportvalidity method on the same element or nothing will happen. function validate(inputid) { var input = document.getelementbyid(inputid); var validitystate_object = input.validity; if (validitystate_object.valuemissing) { input.setcustomvalidity('you gotta fill this out, yo!'); input.reportvalidity(); } else if (input.rangeunderflow) { input.setcustomvalidity('we need a higher number!'); input.reportvalidity(); } else if (input.rangeoverflow) { input.setcustomvalidity('thats too high!'); input.reportvalidity(); } else { input.setcustomvalidity(''); input.reportvalidity(); } } it's vital to set the message to an empty string if there are no errors. as long as the error message is not null, the form will n...
HTMLObjectElement - Web APIs
htmlobjectelement interface provides special properties and methods (beyond those on the htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of <object> element, representing external resources. ...
...ication status comment html living standardthe definition of 'htmlobjectelement' in that specification. living standard html5the definition of 'htmlobjectelement' in that specification. recommendation the w3c specification is a latest of a previous version of html living standard technically, the property tabindex is now defined on htmlelement. the following properties are now obsolete: align, archive, border, code, codebase, codetype, declare, hspace, standby, and vspace. the following properties have been added: typemustmatch, contentwindow, willvalidate, validity, and validationmessage. the following methods have been added: checkvalidity() and setcustomvalidity(). document object model (dom) level 2 html specificationthe defin...
Option() - Web APIs
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. ...
... if the defaultselected argument is true, the option is not selected. ...
HTMLOrForeignElement.tabIndex - Web APIs
elements that do not support the tabindex attribute or support it and assign tabindex to 0, in the order they appear. elements that are disabled do not participate in the tabbing order. values don't need to be sequential, nor must they begin with any particular value. ...
... elements that do not support the tabindex attribute or support it and assign tabindex to 0, in the order they appear. elements that are disabled do not participate in the tabbing order. values don't need to be sequential, nor must they begin with any particular value. ...
HTMLOrForeignElement - Web APIs
the htmlorforeignelement mixin describes several features common to the htmlelement, svgelement and mathmlelement interfaces. each of these interfaces can, of course, add more features in addition to the ones listed below. note: htmlorforeignelement is a mixin and not an interface; you can't actually create an object of type htmlorforeignelement. ...
...mlorforeignelement. 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 receive keyboard and similar events ...
HTMLParagraphElement - Web APIs
the htmlparagraphelement interface provides special properties (beyond those of the regular htmlelement object interface it inherits) for manipulating <p> elements. ...
...", "right", "justify", and "center". methods no specific methods, inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlparagraphelement' in that specification. living standard html5the definition of 'htmlparagraphelement' in that specification. recommendation the following property is now obsolete: align. document object model (dom) level 2 html specificationthe definition of 'htmlparagraphelement' in that specification. obsolete no change from document object model (dom) level 1 specification. document object model (dom) level 1 specificationthe definition of 'htmlparagraphelement' in that specification. obsolete initial definition...
HTMLParamElement - Web APIs
he htmlparamelement interface provides special properties (beyond those of the regular htmlelement object interface it inherits) for manipulating <param> elements, representing a pair of a key and a value that acts as a parameter for an <object> element. ...
...e of the values: "data", "ref", or "object". methods no specific methods, inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlparamelement' in that specification. living standard html5the definition of 'htmlparamelement' in that specification. recommendation the following properties are now obsolete: type, and valuetype. document object model (dom) level 2 html specificationthe definition of 'htmlparamelement' in that specification. obsolete no change from document object model (dom) level 1 specification. document object model (dom) level 1 specificationthe definition of 'htmlparamelement' in that specification. obsolete initial d...
HTMLPreElement - Web APIs
the htmlpreelement interface exposes specific properties and methods (beyond those of the htmlelement interface it also has available to it by inheritance) for manipulating a block of preformatted text (<pre>). ...
...ning a fixed-size length for the <pre> element. methods no specific method; inherits properties from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlpreelement' in that specification. living standard html5the definition of 'htmllielement' in that specification. recommendation the following property is now obsolete: width. document object model (dom) level 2 html specificationthe definition of 'htmlpreelement' in that specification. obsolete no change from document object model (dom) level 1 specification. document object model (dom) level 1 specificationthe definition of 'htmlpreelement' in that specification. obsolete initial definition. ...
HTMLSelectElement.selectedOptions - Web APIs
note also the <button>, whose role it is to trigger fetching the htmlcollection of selected elements using the selected property. javascript the javascript code that establishes the event handler for the button, as well as the event handler itself, looks like this: let orderbutton = document.getelementbyid("order"); let itemlist = document.
...self, looks like this: let orderbutton = document.getelementbyid("order"); let itemlist = document.getelementbyid("foods"); let outputbox = document.getelementbyid("output"); orderbutton.addeventlistener("click", function() { let collection = itemlist.selectedoptions; let output = ""; for (let i=0; i<collection.length; i++) { if (output === "") { output = "your order for the following items has been placed: "; } output += collection[i].label; if (i === (collection.length - 2) && (collection.length < 3)) { output += " and "; } else if (i < (collection.length - 2)) { output += ", "; } else if (i === (collection.length - 2)) { output += ", and "; } } if (output === "") { output = "you didn't order anything!"; } outputbo...
HTMLSelectElement - Web APIs
the htmlselectelement interface represents a <select> html element. these elements also share all of the properties and methods of other html elements via the htmlelement interface. ...
...ty 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. ...
HTMLSourceElement - Web APIs
the htmlsourceelement interface provides special properties (beyond the regular htmlelement object interface it also has available to it by inheritance) for manipulating <source> elements. ...
...> element. note: if the src property is updated (along with any siblings), the parent htmlmediaelement's load method should be called when done, since <source> elements are not re-scanned automatically. htmlsourceelement.srcset is a domstring reflecting the srcset html attribute, containing a list of candidate images, separated by a comma (',', u+002c comma). a candidate image is a url followed by a 'w' with the width of the images, or an 'x' followed by the pixel density. htmlsourceelement.type is a domstring reflecting the type html attribute, containing the type of the media resource. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlsourcee...
HTMLTableElement.frame - Web APIs
the htmltableelement interface's frame property is a string that indicates which of the table's exterior borders should be drawn. syntax htmltableelement.frame = framesides; var framesides = htmltableelement.frame; parameters framesides is a string whose value is one of the following values: void no sides. this is the default. ...
... the htmltableelement interface's frame property is a string that indicates which of the table's exterior borders should be drawn. syntax htmltableelement.frame = framesides; var framesides = htmltableelement.frame; parameters framesides is a string whose value is one of the following values: void no sides. this is the default. ...
HTMLTableRowElement - Web APIs
the htmltablerowelement interface provides special properties and methods (beyond the htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of rows in an html table. ...
...erowelement.sectionrowindex read only returns a long value which gives the logical position of the row within the table section it belongs to. if the row is not part of a section, returns -1. htmltablerowelement.valign is a domstring representing an enumerated value indicating how the content of the cell must be vertically aligned. it reflects the valign attribute and can have one of the following values: "top", "middle", "bottom", or "baseline". methods inherits methods from its parent, htmlelement. htmltablerowelement.deletecell() removes the cell at the given position in the row. if the given position is greater (or equal as it starts at zero) than the amount of cells in the row, or is smaller than 0, it raises a domexception with the indexsizeerror value. htmltablerowelement...
HTMLTableSectionElement - Web APIs
ectionelement interface provides special properties and methods (beyond the htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of sections, that is headers, footers and bodies, in an html table. ...
...e right (for left-to-right scripts; or at the left for right-to-left scripts) of the character defined by htmltablerowelement.ch. this property was optional and was not very well supported. htmltablesectionelement.valign is a domstring representing an enumerated value indicating how the content of the cell must be vertically aligned. it reflects the valign attribute and can have one of the following values: "top", "middle", "bottom", or "baseline". methods inherits methods from its parent, htmlelement. htmltablesectionelement.deleterow() removes the cell at the given position in the section. if the given position is greater (or equal as it starts at zero) than the amount of rows in the section, or is smaller than 0, it raises a domexception with the indexsizeerror value. htmltable...
HTMLTrackElement - Web APIs
the htmltrackelement interface represents an html <track> element within the dom. this element can be used as a child of either <audio> or <video> to specify a text track containing information such as closed captions or subtitles. ...
...error 3 indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way. some or all of the cues are likely missing and will not be obtained. htmltrackelement.track read only returns texttrack is the track element's text track data. methods no specific method; inherits methods from its parent, htmlelement. events the following events may be fired on a <track> element, in addition to any that may be fired at its parent, htmlelement. cuechange sent when the underlying texttrack has changed the currently-presented cues. this event is always sent to the texttrack but is also sent to the htmltrackelement if one is associated with the track. you may also use the oncuechange event handler to establish a handler for th...
History.replaceState() - Web APIs
although they may use it in the future. passing the empty string here should be safe against future changes to the method. alternatively, you could pass a short title for the state. url optional the url of the history entry. the new url must be of the same origin as the current url; otherwise replacestate throws an exception. ...
...tate throws an exception. examples suppose https://www.mozilla.org/foo.html executes the following javascript: const stateobj = { foo: 'bar' }; history.pushstate(stateobj, '', 'bar.html'); the explanation of these two lines above can be found in the example of pushstate() method section of the working with the history api article. then suppose https://www.mozilla.org/bar.html executes the following javascript: history.replacestate(stateobj, '', 'bar2.html'); this will cause the url bar to display https://www.mozilla.org/bar2.html, but won't cause the browser to load bar2.html or even check that bar2.html exists. suppose now that the user navigates to https://www.microsoft.com, then clicks the back button. at this point, the url bar will display https://www.mozilla.org/bar2.html. if th...
History - Web APIs
Web › API › History
this property can be either auto or manual. state read only returns an any value representing the state at the top of the history stack. this is a way to look at the state without having to wait for a popstate event. ...
...rowser session history, that is the pages visited in the tab or frame that the current page is loaded in. properties the history interface doesn't inherit any property. length read only returns an integer representing the number of elements in the session history, including the currently loaded page. for example, for a page loaded in a new tab this property returns 1. scrollrestoration allows web applications to explicitly set default scroll restoration behavior on history navigation. this property can be either auto or manual. state read only returns an any value representing the state at the top of the history stack. this is a way to look at the state without having to wait for a popstate event. methods the history interface doesn't inherit any methods. back() this asynch...
Ajax navigation example - Web APIs
this is an example of an ajax website composed only of three pages (first_page.php, second_page.php and third_page.php). to see how it works, please create the following files (or git clone https://github.com/giabao/mdn-ajax-nav-example.git ): note: for fully integrating the <form> elements within this mechanism, please take a look at the paragraph submitting forms and uploading files. first_page.php: <?php $page_title = "first page"; $as_json = false; if (isset($_get["view_as"]) && $_get["view_as"] == "json") { $as_json = true; ob_start(); } else { ?> <!doctype html> <html> <head> <?php include "include/header.php"; echo "<title>" . $page_title . "</title>"; ?> </head> <body> <?php include "include/before_content.php"; ?> <p>th...
...ound", 303: "see other", 304: "not modified", 305: "use proxy", 306: "reserved", 307: "temporary redirect", 308: "permanent redirect", 400: "bad request", 401: "unauthorized", 402: "payment required", 403: "forbidden", 404: "not found", 405: "method not allowed", 406: "not acceptable", 407: "proxy authentication required", 408: "request timeout", 409: "conflict", 410: "gone", 411: "length required", 412: "precondition failed", 413: "request entity too large", 414: "request-uri too long", 415: "unsupported media type", 416...
History API - Web APIs
ent page's relative position is 0.) to move back one page (the equivalent of calling back()): window.history.go(-1) to move forward a page, just like calling forward(): window.history.go(1) similarly, you can move forward 2 pages by passing 2, and so forth. ...
... 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 some of the methods of the history object to add, replace, and move within the browser history for the current tab. window.onpopstate = function(event) { alert(`loc...
IDBCursor.advance() - Web APIs
Web › API › IDBCursor › advance
the advance() method of the idbcursor interface sets the number of times a cursor should move its position forward. note: this feature is available in web workers. syntax cursor.advance(count); parameters count the number of times to move the cursor forward. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbcursor's transaction is inactive. typeerror the value passed into the count parameter was zero or a negative number. invalidstateerror the cursor is currently being iterated or has iterated past its end. example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through the rec...
...terated or has iterated past its end. example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through the records in the object store. here we use cursor.advance(2) to jump 2 places forward each time, meaning that only every other result will be displayed. advance() works in a similar way to idbcursor.continue, except that it allows you to jump multiple records at a time, not just always go onto the next record. note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. for a complete working example, see our idbcursor example (view example live.) function advanceresult() { list.innerhtml = ''; var transaction = db.transaction(['rushalbumlist'], "...
IDBCursor.update() - Web APIs
Web › API › IDBCursor › update
needs, you have to use idbindex.opencursor() instead. note: this feature is available in web workers. syntax var anidbrequest = myidbcursor.update(value); parameters value the new value to be stored at the current position. return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbcursor's transaction is inactive. readonlyerror the transaction mode is read only. invalidstateerror the cursor was created using idbindex.openkeycursor, is currently being iterated, or has iterated past its end. dataerror the underlying object store uses in-line ...
... was released using var request = cursor.update();. note that you cannot change primary keys using cursor.update(), hence us not changing the album title; this would ruin the integrity of the data. in such a situation, you would have to delete the record altogether and then add a new one using idbobjectstore.add. note also that you can't directly put cursor.value into an update call, hence the below example using an intermediary updatedata variable. the cursor does not require us to select the data based on a key; we can just grab all of it. also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. for a complete working example, see our idbcursor example (view example live.) function updateresult() { list.inne...
IDBDatabase.createObjectStore() - Web APIs
this feature is available in web workers. syntax idbdatabase.createobjectstore(name); idbdatabase.createobjectstore(name, options); parameters name the name of the new object store to be created. note that it is possible to create an object store with an empty name. optionalparameters optional an options object whose attributes are optional parameters to the method. it includes the following properties: attribute description keypath the key path to be used by the new object store. if empty or not specified, the object store is created without a key path and uses out-of-line keys. you can also pass in an array as a keypath. autoincrement if true, the object store has a key generator. defaults to false. unknown param...
... empty or not specified, the object store is created without a key path and uses out-of-line keys. you can also pass in an array as a keypath. autoincrement if true, the object store has a key generator. defaults to false. unknown parameters are ignored. returns a new idbobjectstore. exceptions this method may raise a domexception with a domerror of one of the following types: exception description invalidstateerror occurs if the method was not called from a versionchange transaction callback. for older webkit browsers, you must call first. transactioninactiveerror occurs if a request is made on a source database that doesn't exist (e.g. has been deleted or removed.) in firefox previous to version 41, an invalidstatee...
IDBDatabaseException - Web APIs
dbtransaction.abort. constraint_err 4 a mutation operation in the transaction failed because a constraint was not satisfied. for example, an object, such as an object store or index, already exists and a request attempted to create a new one. data_err 5 data provided to an operation does not meet requirements. non_transient_err 2 an operation was not allowed on an object. unless the cause of the error is corrected, retrying the same operation would result in failure. not_allowed_err 6 an operation was called on an object where it is not allowed or at a time when it is not allowed. it also occurs if a request is made on a source object that has been deleted or removed. more specific variants of this error includes: transact...
... transaction_inactive_err 7 a request was made against a transaction that is either not currently active or is already finished. unknown_err 1 the operation failed for reasons unrelated to the database itself, and it is not covered by any other error code--for example, a failure due to disk io errors. ver_err 12 a request to open a database with a version lower than the one it already has. this can only happen with idbopendbrequest. 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 androidf...
IDBFactory.cmp() - Web APIs
Web › API › IDBFactory › cmp
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. syntax var result = indexeddb.cmp(first, second); parameters first the first key to compare. second the second key to compare. ...
...key to compare. return value an integer that indicates the result of the comparison; the table below lists the possible values and their meanings: returned value description -1 1st key is less than the 2nd key 0 1st key is equal to the 2nd key 1 1st key is greater than the 2nd key exceptions this method may raise a domexception of the following types: attribute description dataerror one of the supplied keys was not a valid key. example var a = 1; var b = 2; var result = window.indexeddb.cmp(a, b); console.log( "comparison results: " + result ); specifications specification status comment indexed database api 2.0the definition of 'cmp()' in that specification. recommenda...
IDBFactory.open() - Web APIs
Web › API › IDBFactory › open
ager.persist() to get persistent storage instead. note: you can find out more information on the different available storage types, and how firefox handles client-side data storage, at browser storage limits and eviction criteria. return value a idbopendbrequest object on which subsequent events related to this request are fired. ...
...events related to this request are fired. exceptions this method may raise a domexception of the following types: exception description typeerror the value of version is zero or a negative number or not a number. example example of calling open with the current specification's version parameter: var request = window.indexeddb.open("todolist", 4); in the following code snippet, we make a request to open a database, and include handlers for the success and error cases. for a full working example, see our to-do notifications app (view example live.) var note = document.queryselector("ul"); // in the following line, you should include the prefixes // of implementations you want to test. window.indexeddb = window.indexeddb || window.mozindexeddb || window...
IDBIndex.count() - Web APIs
Web › API › IDBIndex › count
hin a key range. note: this feature is available in web workers. syntax var request = myindex.count(); var request = myindex.count(key); parameters key optional the key or key range that identifies the record to be counted. return value a idbrequest object on which subsequent events related to this operation are fired. ...
...ration are fired. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbindex has been deleted or removed. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key. myindex.count() is then used to...
IDBIndex.get() - Web APIs
Web › API › IDBIndex › get
ble in web workers. syntax var request = myindex.get(key); parameters key optional a key or idbkeyrange that identifies the record to be retrieved. if this value is null or missing, the browser will use an unbound key range. return value an idbrequest object on which subsequent events related to this operation are fired. ...
...ration are fired. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbindex has been deleted or removed. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key. myindex.get('bungle') is then u...
IDBIndex.getKey() - Web APIs
Web › API › IDBIndex › getKey
le in web workers. syntax var request = myindex.getkey(key); parameters key optional a key or idbkeyrange that identifies a record to be retrieved. if this value is null or missing, the browser will use an unbound key range. return value an idbrequest object on which subsequent events related to this operation are fired. ...
...ration are fired. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbindex has been deleted or removed. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key. myindex.getkey('bungle') is the...
IDBIndex.openCursor() - Web APIs
range to use as the cursor's range. if nothing is passed, this will default to a key range that selects all the records in this object store. direction optional the cursor's direction. see idbcursor constants for possible values. return value an idbrequest object on which subsequent events related to this operation are fired. ...
...we then open a basic cursor on the index using opencursor() — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key. ...
IDBIndex.openKeyCursor() - Web APIs
range to use as the cursor's range. if nothing is passed, this will default to a key range that selects all the records in this object store. direction optional the cursor's direction. see idbcursor constants for possible values. return value an idbrequest object on which subsequent events related to this operation are fired. ...
...we then open a key cursor on the index using openkeycursor() — this works the same as opening a cursor directly on an objectstore using idbobjectstore.openkeycursor except that the returned records are sorted based on the index, not the primary key. ...
IDBIndex - Web APIs
Web › API › IDBIndex
ey path of this index. if null, this index is not auto-populated. idbindex.multientry read only affects how the index behaves when the result of evaluating the index's key path yields an array. if true, there is one record in the index for each item in an array of keys. if false, then there is one record for each key that is an array. idbindex.unique read only if true, this index does not allow duplicate values for a key. methods inherits from: eventtarget idbindex.count() returns an idbrequest object, and in a separate thread, returns the number of records within a key range. idbindex.get() returns an idbrequest object, and, in a separate thread, finds either the value in the referenced object store that corresponds to the given key or the first corresponding value, if key is ...
...ced object store that correspond to the given key or are in range, if key is an idbkeyrange. idbindex.opencursor() returns an idbrequest object, and, in a separate thread, creates a cursor over the specified key range. idbindex.openkeycursor() returns an idbrequest object, and, in a separate thread, creates a cursor over the specified key range, as arranged by this index. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key. finally, we iterate through eac...
IDBKeyRange.only() - Web APIs
Web › API › IDBKeyRange › only
the only() method of the idbkeyrange interface creates a new key range containing a single value. note: this feature is available in web workers. syntax var myidbkeyrange = idbkeyrange.only(value); parameters value is the value for the new key range. return value idbkeyrange: the newly created key range. exceptions this method may raise a domexception of the following types: exception description dataerror the value parameter passed was not a valid key. example the following example illustrates how you'd use an only key range. here we declare a keyrangevalue = idbkeyrange.only("a"); — a range that only includes the value "a". we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstor...
...nge. here we declare a keyrangevalue = idbkeyrange.only("a"); — a range that only includes the value "a". we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. this means that the cursor will only retrieve the record with the key value "a". ...
IDBKeyRange.upper - Web APIs
Web › API › IDBKeyRange › upper
the upper read-only property of the idbkeyrange interface returns the upper bound of the key range. note: this feature is available in web workers. syntax var upper = mykeyrange.upper value the upper bound of the key range (can be any type.) example the following example illustrates how you'd use a key range. here we declare keyrangevalue = idbkeyrange.upperbound("f", "w", true, true); — a range that includes everything between "f" and "w" but not including them — since both the upper and lower bounds have been declared as open (true). we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. after declaring the key range, we log its upper property value to the con...
...hem — since both the upper and lower bounds have been declared as open (true). we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. after declaring the key range, we log its upper property value to the console, which should appear as "w". ...
IDBKeyRange.upperBound() - Web APIs
is feature is available in web workers. syntax var myidbkeyrange = idbkeyrange.upperbound(upper[, open=false]) parameters bound specifies the upper bound of the new key range. open indicates whether the upper bound excludes the endpoint value. the default is false. optional return value idbkeyrange: the newly created key range. exceptions this method may raise a domexception of the following type: exception description dataerror the value parameter passed was not a valid key. example the following example illustrates how you'd use an upper bound key range. here we declare keyrangevalue = idbkeyrange.upperbound("f"); — a range that includes the value "f" and everything before it. we open a transaction (using idbtransaction) and an obj...
... a range that includes the value "f" and everything before it. we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. if we used idbkeyrange.upperbound("f", true);, then the range excludes "f"; and instead only includes the values before it. ...
IDBKeyRange.upperOpen - Web APIs
boolean indicating whether the upper-bound value is included in the key range. note: this feature is available in web workers. syntax var upperopen = mykeyrange.upperopen value a boolean: value indication true the upper-bound value is not included in the key range. false the upper-bound value is included in the key range. example the following example illustrates how you'd use a key range. here we declare keyrangevalue = idbkeyrange.upperbound("f", "w", true, true); — a range that includes everything between "f" and "w" but not including them — since both the upper and lower bounds have been declared as open (true). we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor...
... open (true). we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. after declaring the key range, we log its upperopen property value to the console, which should appear as "true": the upper bound is open, so won't be included in the range. ...
IDBObjectStore.index() - Web APIs
t object store, after which it can be used to, for example, return a series of records sorted by that index using a cursor. note: this feature is available in web workers. syntax var index = objectstore.index(name); parameters name the name of the index to open. return value an idbindex object for accessing the index. ...
...or accessing the index. exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror the source object store has been deleted, or the transaction for the object store has finished. notfounderror there is no index with the given name (case-sensitive) in the database. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key. finally, we iterate through eac...
IDBObjectStore.put() - Web APIs
t have an autoincrement primary key, therefore the key is not in a field on the record object. in such cases, calling put(item) will always insert a new record, because it doesn't know what existing record you might want to modify. return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description readonlyerror the transaction associated with this operation is in read-only mode. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror any of the following conditions apply: the object store uses in-line keys or has a key generator, and a key parameter was provided. ...
...ved. datacloneerror the data being stored could not be cloned by the internal structured cloning algorithm. parameters value the value to be stored. key the key to use to identify the record. if unspecified, it results to null. if the object store has a key generator (e.g. autoincrement) the key of the object must be passed in to update the object. example the following example requests a given record title; when that request is successful the onsuccess function gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store in another request with put(). for a full working example, see our to-do notifications app (view exampl...
IDBRequest.readyState - Web APIs
state read-only property of the idbrequest interface returns the state of the request. every request starts in the pending state. the state changes to done when the request completes successfully or when an error occurs. note: this feature is available in web workers. ...
... the request completes successfully or when an error occurs. note: this feature is available in web workers. syntax var currentreadystate = request.readystate; value the idbrequestreadystate of the request, which takes one of the following two values: value meaning pending the request is pending. done the request is done. example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store in another request. the readystate of the 2nd request is logged to the developer console. for a full working example, see our to-do notifications ap...
IDBRequest.transaction - Web APIs
returned from idbfactory.open — in this case you're just connecting to a database, so there is no transaction to return. if a version upgrade is needed when opening a database then during the upgradeneeded event handler the transaction property will be an idbtransaction with mode equal to "versionchange", and can be used to access existing object stores and indexes, or abort the the upgrade. ...
...t handler the transaction property will be an idbtransaction with mode equal to "versionchange", and can be used to access existing object stores and indexes, or abort the the upgrade. following the upgrade, the transaction ​property will again be null. note: this feature is available in web workers. syntax var mytransaction = request.transaction; value an idbtransaction. example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store in another request. the source of the requests is logged to the developer console — both originate from the same transaction. for a full working e...
IDBRequest - Web APIs
ming 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. ...
...s no methods, but inherits methods from eventtarget. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. error fired when an error caused a request to fail. also available via the onerror property. success fired when an idbrequest succeeds. also available via the onsuccess property. example in the following code snippet, we open a database asynchronously and make a request; onerror and onsuccess functions are included to handle the success and error cases. for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database being // opened su...
IDBTransaction.error - Web APIs
d from the dom standard. the exact error is one of serveral possibilities. it can be a reference to the same error as the request object that raised it, or a transaction failure (for example quotaexceedederror or unknownerror). this property is null if the transaction is not finished, is finished and successfully committed, or was aborted with the idbtransaction.abort method. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. note the transaction.onerror = function(event) { }; block, making use of transaction.error to help in reporting what went wrong when the transac...
... when the transaction was unsuccessful. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction.onabort - Web APIs
the onabort event handler of the idbtransaction interface handles the abort event, fired, when the current transaction is aborted via the idbtransaction.abort method. note: this feature is available in web workers. syntax transaction.onabort = function(event) { ... }; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. note the transaction.onabort = function(event) { }; block, reporting when the transaction has been aborted. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.inde...
... when the transaction has been aborted. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction.oncomplete - Web APIs
ou can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config. syntax transaction.oncomplete = function(event) { ... }; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. note the transaction.oncomplete = function(event) { }; block, which reports back when the transaction was successful. for a full working example...
...ck when the transaction was successful. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction.onerror - Web APIs
the onerror event handler of the idbtransaction interface handles the error event, fired when a request returns an error and bubbles up to the transaction object. note: consider using idbtransaction.onabort instead to handle non- successful completion of the transaction. note: this feature is available in web workers. syntax transaction.onerror = function(event) { ... }; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. note the transaction.onerror = function(event) { }; block, making use of transaction.error to help in reporting what went wrong when the transac...
... when the transaction was unsuccessful. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBVersionChangeEvent - Web APIs
only the new version of the database in a versionchange transaction. warning: while this property is still implemented in older browsers, the latest specification replaces it with the oldversion and newversion attributes. see the compatibility table to know what browsers support them. methods no specific method, but inherits properties from its parent, method. ...
...window.indexeddb = window.indexeddb || window.mozindexeddb || window.webkitindexeddb || window.msindexeddb; // don't use "var indexeddb = ..." if you're not in a function. ...
IIRFilterNode - Web APIs
hen the output has approached zero closely enough. the actual time that takes depends on the filter coefficients provided. constructor iirfilternode() creates a new instance of an iirfilternode object. properties this interface has no properties of its own; however, it inherits properties from its parent, audionode. methods inherits methods from its parent, audionode. ...
... also see our using iir filters guide for a full explanation. specifications specification status comment web audio apithe definition of 'iirfilternode' in that specification. ...
ImageCapture.getPhotoSettings() - Web APIs
the getphotosettings() method of the imagecapture interface returns a promise that resolves with a photosettings object containing the current photo configuration settings. syntax const settingspromise = imagecapture.getphotosettings() return value a promise that resolves with a photosettings object containing the following properties: filllightmode: the flash setting of the capture device, one of "auto", "off", or "on". imageheight: the desired image height as an integer. the user agent selects the closest width value to this setting if it only supports discrete heights. imagewidth: the desired image width as an integer. the user agent selects the closest width value to this setting if it only supports discrete widths. redeyereduction: a boolean indicating whether the red-eye red...
...ge height as an integer. the user agent selects the closest width value to this setting if it only supports discrete heights. imagewidth: the desired image width as an integer. the user agent selects the closest width value to this setting if it only supports discrete widths. redeyereduction: a boolean indicating whether the red-eye reduction should be used if it is available. example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotosettings() to modify the size of an input range. this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream. const input = document.queryselector('input[type="range"]'); var imagecapture; navigator.mediadevices.getusermedi...
ImageCapture - Web APIs
ew imagecapture object which can be used to capture still frames (photos) from a given mediastreamtrack which represents a video stream. properties imagecapture.track read only returns a reference to the mediastreamtrack passed to the constructor. methods the imagecapture interface is based on eventtarget, so it includes the methods defined by that interface as well as the ones listed below. imagecapture.takephoto() takes a single exposure using the video capture device sourcing a mediastreamtrack and returns a promise that resolves with a blob containing the data. imagecapture.getphotocapabilities() returns a promise that resolves with a photocapabilities object containing the ranges of available configuration options. imagecapture.getphotosettings() returns a promise that ...
...mise that resolves with a photocapabilities object containing the ranges of available configuration options. imagecapture.getphotosettings() returns a promise that resolves with a photosettings object containing the current photo configuration settings. imagecapture.grabframe() takes a snapshot of the live video in a mediastreamtrack, returning an imagebitmap, if successful. example the following code is taken from chrome's grab frame - take photo sample. since imagecapture requires some place to capture an image from, the example below starts with a device's media device (in other words a camera). this example shows, roughly, a mediastreamtrack extracted from a device's mediastream. the track is then used to create an imagecapture object so that takephoto() and grabframe() can be cal...
KeyboardEvent: code values - Web APIs
the reason is that some browsers choose to interpret physical keys differently, there are some differences in which keys map to which codes. these tables show those variations when known. code values code values on windows this table shows the windows scan codes representing keys and the keyboardevent.code values which correspond to those hardware keys. only keys which generate scan codes on windows are listed. ...
... "f1" kvk_leftarrow (0x7b) "arrowleft" "arrowleft" kvk_rightarrow (0x7c) "arrowright" "arrowright" kvk_downarrow (0x7d) "arrowdown" "arrowdown" kvk_uparrow (0x7e) "arrowup" "arrowup" code values on linux (x11) (when scancode is available) note that x has too many keys and some of them are not testable with usual keyboard. so, following table is created from source code which maps from scancode to code value. scancode (hardware_keycode) gecko chromium (44) 0x0009 "escape" "escape" 0x000a "digit1" "digit1" 0x000b "digit2" "digit2" 0x000c "digit3" "digit3" 0x000d "digit4" "digit4" 0x000e "digit5" "digit5" 0x00...
KeyboardEvent.getModifierState() - Web APIs
s the typical modifier key for the shortcut key is pressed. for example, on windows, pressing ctrl key may make it return true. however, on mac, pressing ⌘ command key may make it return true. note that which modifier key makes it return true depends on platforms, browsers, and user settings. for example, firefox users can customize this with a pref, "ui.key.accelkey". example // ignore if following modifier is active. if (event.getmodifierstate("fn") || event.getmodifierstate("hyper") || event.getmodifierstate("os") || event.getmodifierstate("super") || event.getmodifierstate("win") /* hack for ie */) { return; } // also ignore if two or more modifiers except shift are active. if (event.getmodifierstate("control") + event.getmodifierstate("alt") + event.getmodi...
...getmodifierstate("super") || event.getmodifierstate("win") /* hack for ie */) { return; } // also ignore if two or more modifiers except shift are active. ...
KeyframeEffect - Web APIs
properties keyframeeffect.target gets and sets the element, or originating element of the pseudo-element, being animated by this object. ...
...ted 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. ...
Location - Web APIs
Web › API › Location
-space:nowrap;} [title] {position:relative; display:inline-block; box-sizing:border-box; /*border-bottom:.5em solid;*/ line-height:2em; cursor:pointer;} [title]:before {content:attr(title); font-family:monospace; position:absolute; top:100%; width:100%; left:50%; margin-left:-50%; font-size:40%; line-height:1.5; background:black;} [title]:hover:before, :target:before {background:black; color:yellow;} [title] [title]:before {margin-top:1.5em;} [title] [title] [title]:before {margin-top:3em;} [title]:hover, :target {position:relative; z-index:1; outline:50em solid rgba(255,255,255,.8);} javascript [].foreach.call(document.queryselectorall('[title][id]'), function (node) { node.addeventlistener("click", function(e) { e.preventdefault(); e.stoppropagation(); window.location.ha...
...otocol is a usvstring containing the protocol scheme of the url, including the final ':'. location.host is a usvstring containing the host, that is the hostname, a ':', and the port of the url. location.hostname is a usvstring containing the domain of the url. location.port is a usvstring containing the port number of the url. location.pathname is a usvstring containing an initial '/' followed by the path of the url. location.search is a usvstring containing a '?' followed by the parameters or "querystring" of the url. modern browsers provide urlsearchparams and url.searchparams to make it easy to parse out the parameters from the querystring. location.hash is a usvstring containing a '#' followed by the fragment identifier of the url. location.origin read only returns a usvst...
MediaList.mediaText - Web APIs
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. ...
... 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 "". examples the following would log to the console a textual representation of the medialist of the first stylesheet applied to the current document. const stylesheets = document.stylesheets; let stylesheet = stylesheets[0]; console.log(stylesheet.media.mediatext); specifications specification status comment css object model (cssom)the definition of 'mediatext' in that specification. worki...
MediaMetadata.MediaMetadata() - Web APIs
the mediametadata() constructor creates a new mediametadata object. syntax var mediametadata = new mediametadata([metadata]) parameters metadata optional the metadata parameters are as follows: title: the title of the media to be played. artist: the name of the artist, group, creator, etc. of the media to be played. album: the name of the album, or collection, containing the media to be played. artwork: an array of images associated with the playing media. ...
...ediametadata([metadata]) parameters metadata optional the metadata parameters are as follows: title: the title of the media to be played. artist: the name of the artist, group, creator, etc. of the media to be played. album: the name of the album, or collection, containing the media to be played. artwork: an array of images associated with the playing media. ...
MediaQueryList - Web APIs
t by calling matchmedia() on the window object. the resulting object handles sending notifications to listeners when the media query state changes (i.e. when the media query test starts or stops evaluating to true). this is very useful for adaptive design, since this makes it possible to observe a document to detect when its media queries change, instead of polling the values periodically, and allows you to programmatically make changes to a document based on media query status. properties the mediaquerylist interface inherits properties from its parent interface, eventtarget. matchesread only a boolean that returns true if the document currently matches the media query list, or false if not. mediaread only a domstring representing a serialized media query. methods the mediaquer...
...ylist changes media query status, which happens any time the document switches between matching and not matching the media queries listed in the mediaquerylist. this method has been kept for backward compatibility; if possible, you should generally use removeeventlistener() to remove change notification callbacks (which should have previously been added using addeventlistener()). 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 onc...
MediaRecorder.start() - Web APIs
the timeslice duration or the end-of-media, if no slice duration was provided), a dataavailable event is sent to the mediarecorder with the recorded data. if the source is still playing, a new blob is created and recording continues into that, and so forth. when the source stream ends, state is set to inactive and data gathering stops. a final dataavailable event is sent to the mediarecorder, followed by a stop event. note: if the browser is unable to start recording or continue recording, it will raise a domerror event, followed by a mediarecorder.dataavailable event containing the blob it has gathered, followed by the mediarecorder.stop event. syntax mediarecorder.start(timeslice) parameters timeslice optional the number of milliseconds to record into each blob. if this parameter...
...a. invalidstateerror the mediarecorder is not in the inactive state; you can't start recording media if it's already being recorded. see the state property. notsupportederror the media stream you're attempting to record is inactive, or one or more of the stream's tracks is in a format that can't be recorded using the current configuration. securityerror the mediastream is configured to disallow recording. this may be the case, for example, with sources obtained using getusermedia() when the user denies permission to use an input device. this also happens when a mediastreamtrack within the stream is marked as isolated due to the peeridentity constraint on the source stream. this exception may also be delivered as an error event if the security options for the source media change after r...
MediaRecorder - Web APIs
stop an eventhandler called to handle the stop event, which occurs when media recording ends, either when the mediastream ends — or after the mediarecorder.stop() method is called. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. error fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec. also available via the onerror property. example if (navigator.mediadevices) { console.log('getusermedia supported.'); var constraints = { audio: true }; var chunks = []; navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var mediarecorder = new mediarecorder(stream); visualize(stream); record.onc...
...some lines have been omitted for brevity; refer to the source for the complete code. specifications specification status comment mediastream recording working draft initial definition ...
MediaSession.playbackState - Web APIs
the playbackstate property of the mediasession interface indicates whether the current media session is playing or paused. syntax let playbackstate = mediasession.playbackstate; mediasession.playbackstate = playbackstate; value a domstring indicating the current playback state of the media session. ...
...t playback state of the media session. the value may be one of the following: none the browsing context doesn't currently know the current playback state, or the playback state is not available at this time. paused the browser's media session is currently paused. playback may be resumed. playing the browser's media session is currently playing media, which can be paused. ...
MediaSession.setActionHandler() - Web APIs
ser engages a device's built-in physical or onscreen media controls, such as play, stop, or seek buttons. syntax navigator.mediasession.setactionhandler(type, callback) parameters type a domstring representing an action type to listen for. it will be one of play, pause, seekbackward, seekforward, seekto, skipad,previoustrack, or nexttrack. further details on the action types can be found below under 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...
...y, 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. implement support for each of these in order to allow that type of action to be performed. the following strings identify the currently available types of media session action: nexttrack advances playback to the next track. pause pauses playback of the media. play begins (or resumes) playback of the media. previoustrack moves back to the previous track. seekbackward seeks backward through the media from the current position. seekforwar...
MediaSessionActionDetails - Web APIs
by the sole input parameter into the callback which is executed when a media session action occurs. it specifies the type of action which needs to be performed as well as the data needed to perform the action. properties action a media session action type string taken from the mediasessionaction enumerated type, indicating which type of action needs to be performed. see media action types below for possible values. fastseek optional an seekto action may optionally include this property, which is a boolean value indicating whether or not to perform a "fast" seek. a "fast" seek is a seek being performed in a rapid sequence, such as when fast-forwarding or reversing through the media, rapidly skipping through it. this property can be used to indicate that you should use the shortest poss...
...me within the media to move the playback position to, where 0 indicates the beginning of the media. this property is not present for other action types. media action types 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. implement support for each of these in order to allow that type of action to be performed. the following strings identify the currently available types of media session action: nexttrack advances playback to the next track. pause pauses playback of the media. play begins (or resumes) playback of the media. previoustrack moves back to the previous track. seekbackward seeks backward through the media from the current position. the mediase...
MediaSource.duration - Web APIs
the duration property of the mediasource interface gets and sets the duration of the current media being presented. syntax mediasource.duration = 5.5; // 5.5 seconds var myduration = mediasource.duration; value a double. a value in seconds is expected. exceptions the following exceptions may be thrown when setting a new value for this property. exception explanation invalidaccesserror an attempt was made to set a duration value that was negative, or nan. ...
...or this property. exception explanation invalidaccesserror an attempt was made to set a duration value that was negative, or nan. invalidstateerror mediasource.readystate is not equal to open, or one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e. ...
MediaSource - Web APIs
the mediasource interface of the media source extensions api represents a source of media data for an htmlmediaelement object. a mediasource object can be attached to a htmlmediaelement to be played in the user agent. ...
...ebuffer from the mediasource.sourcebuffers list. mediasource.setliveseekablerange() sets the range that the user can seek to in the media element. static methods mediasource.istypesupported() returns a boolean value indicating if the given mime type is supported by the current user agent — this is, if it can successfully create sourcebuffer objects for that mime type. examples the following simple example loads a video with xmlhttprequest, playing it as soon as it can. this example was written by nick desaulniers and can be viewed live here (you can also download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimeco...
MediaStreamTrack.applyConstraints() - Web APIs
to the track; these constraints let the web site or app establish ideal values and acceptable ranges of values for the constrainable properties of the track, such as frame rate, dimensions, echo cancelation, and so forth. constraints can be used to ensure that the media meets certain guidelines you prefer. for example, you may prefer high-density video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network. constraints can also specify ideal and/or acceptable sizes or ranges of sizes. see applying constraints in capabilities, constraints, and settings for more information on how to apply your preferred constraints. syntax const appliedpromise = track.applyconstraints([constraints]) parameters constraints optional a mediatrackconst...
... return value a promise which resolves when the constraints have been successfully applied. if the constraints cannot be applied, the promise is rejected with a mediastreamerror whose name is overconstrainederror, to indicate that the constraints could not be met. this can happen if the specified constraints are too strict to find a match when attempting to configure the track. examples the following shows how to specify a basic and advanced set of constraints. it specifies that the page or 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 a...
MediaStreamTrack: mute event - Web APIs
, a user-toggled state of silencing a track) is actually managed using the mediastreamtrack.enabled property, for which there are no events. bubbles no cancelable no interface event event handler property onmute examples in this example, event handlers are established for the mute and unmute events in order to detect when the media is not flowing from the source for the mediastreamtrack referenced by musictrack. musictrack.addeventlistener("mute", event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; }, false); musictrack.addeventlistener("unmute", event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; }, false); with these event handlers in place, when the track mus...
... element with the id timeline-widget gets its background color changed to #aaa. when the track exits the muted state—detected by the arrival of an unmute event—the background color is restored to white. you can also use the onmute event handler property to set up a handler for this event; similarly, the onunmute event handler is available for setting up a handler for the unmute event. the following example shows this: musictrack.onmute = event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; } musictrack.mute = event = > { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; } specifications specification status comment media capture and streamsthe definition of 'mute' in that specification. cand...
MediaStreamTrack: unmute event - Web APIs
event event handler property onunmute note: the condition that most people think of as "muted" (that is, a user-controllable way to silence a track) is actually managed using the mediastreamtrack.enabled property, for which there are no events. examples in this example, event handlers are established for the mute and unmute events in order to detect when the media is not flowing from the source for the mediastreamtrack stored in the variable musictrack. musictrack.addeventlistener("mute", event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; }, false); musictrack.addeventlistener("unmute", event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; }, false); with these event handlers in place, when the ...
...e element with the id timeline-widget gets its background color changed to #aaa. when the track exits the muted state—detected by the arrival of an unmuted event—the background color is restored to white. you can also use the onunmute event handler property to set up a handler for this event; similarly, the onmute event handler is available for setting up a handler for the mute event. the following example shows this: musictrack.onmute = event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; } musictrack.mute = event = > { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; } specifications specification status comment media capture and streamsthe definition of 'unmute' in that specification. ca...
Recording a media element - Web APIs
ideo> <a id="downloadbutton" class="button"> download </a> </div> on the right we see a stop button and the <video> element which will be used to play back the recorded video. notice that the playback panel doesn't have autoplay set (so the playback doesn't start as soon as media arrives), and it has controls set, which tells it to show the user controls to play, pause, and so forth. below the playback element is a button for downloading the recorded video. <div class="bottom"> <pre id="log"></pre> </div> css content body { font: 14px "open sans", "arial", sans-serif; } video { margin-top: 2px; border: 1px solid black; } .button { cursor: pointer; display: block; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px;...
...ttribute can be a boolean, you can also set it to a string to use as the name for the downloaded file. so by setting the download link's download attribute to "recordedvideo.webm", we tell the browser that clicking the button should download a file named "recordedvideo.webm" whose contents are the recorded video. lines 17-18 the size and type of the recorded media are output to the log area below the two videos and the download button. line 20 the catch() for all the promises outputs the error to the logging area by calling our log() function. handling the stop button the last bit of code adds a handler for the click event on the stop button using addeventlistener(): stopbutton.addeventlistener("click", function() { stop(preview.srcobject); }, false); this simply calls the stop()...
MediaTrackConstraints.logicalSurface - Web APIs
the mediatrackconstraints dictionary's logicalsurface property is a constraindomstring describing the requested or mandatory 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 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 logicalsurface object. for example, if your app needs to know if the selected display surface is a logical one: let islogicalsurface = displaystream.getvideotracks()[0].getsettings().logicalsurface; following this code, islogicalsurface is true if the display surface contained in the stream is a logical surface; that is, one which may not be entirely onscreen, or may even be entirely offscreen. specifications specification status comment screen capturethe definition of 'mediatrackconstraints.logicalsurface' in that specification. working draft initial specificat...
MediaTrackSettings - Web APIs
any constraints previously described using a mediatrackconstraints object and set using applyconstraints(), and will adhere to the default constraints for any properties whose constraints haven't been changed, or whose customized constraints couldn't be matched. to learn more about how constraints and settings work, see capabilities, constraints, and settings. properties some or all of the following will be included in the object, either because it's not supported by the browser or because it's not available due to context. for example, because rtp doesn't provide some of these values during negotiation of a webrtc connection, a track associated with a rtcpeerconnection will not include certain values, such as facingmode or groupid. properties of all media tracks deviceid a domstring...
...ight be the result of the user agent using cropping or downscaling from a higher camera resolution. properties of shared screen tracks tracks containing video shared from a user's screen (regardless of whether the screen data comes from the entire screen or a portion of a screen, like a window or tab) are generally treated like video tracks, with the exception that they also support the following added settings: cursor a domstring which indicates whether or not the mouse cursor is being included in the generated stream and under what conditions. possible values are: always the mouse is always visible in the video content of the {domxref("mediastream"), unless the mouse has moved outside the area of the content. motion the mouse cursor is always included in the video if...
MediaTrackSupportedConstraints.frameRate - Web APIs
dictionary's framerate property is a read-only boolean value which is present (and set to true) in the object returned by mediadevices.getsupportedconstraints() if and only if the user agent supports 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.frame...
... if this property is present, its value is always true. example this simple example looks to see if your browser supports constraining the frame rate when requesting video tracks. ...
MediaTrackSupportedConstraints - Web APIs
ttempting to establish constraints if you need to know the difference between silently ignoring a constraint and a constraint being accepted. an actual constraint set is described using an object based on the mediatrackconstraints dictionary. to learn more about how constraints work, see capabilities, constraints, and settings. properties some combination—but not necessarily all—of the following properties will exist on the object. autogaincontrol a boolean whose value is true if the autogaincontrol constraint is supported in the current environment. width a boolean value whose value is true if the width constraint is supported in the current environment. height a boolean value whose value is true if the height constraint is supported in the current environment. aspectratio ...
...straint is supported in the current environment. deviceid a boolean value whose value is true if the deviceid constraint is supported in the current environment. groupid a boolean value whose value is true if the groupid constraint is supported in the current environment. properties specific to shared screen tracks for tracks containing video sources from the user's screen contents, the following additional properties are may be included in addition to those available for video tracks. cursor a boolean value which is true if the cursor constraint is supported in the current environment. displaysurface a boolean value which is true if the cursor constraint is supported in the current environment. logicalsurface a boolean value which is true if the logicalsurface constrai...
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. ...
...ities dictionaries mediaconfiguration describes how video and audio configuration dictionaries must be configured, or defined, to be passed as a parameter of the mediacapabilities.encodinginfo() and mediacapabilities.decodinginfo() methods. it is inherited by the mediadecodingconfiguration and mediaencodingconfiguration dictionaries. mediadecodingconfiguration defines the valid values for allowed types of media when the media configuration is submitted as the parameter for mediacapabilities.decodinginfo(). consists of a media decoding type and a videoconfiguration or audioconfiguration dictionary. mediaencodingconfiguration defines the valid values for allowed types of media when the media configuration is submitted as the parameter for mediacapabilities.encodinginfo(). consists of a ...
Media Source API - Web APIs
ns 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 single track src value fed to media elements with a reference to a mediasource object, which is a container for information like the ready state of the media for being played, and references to multiple sourcebuffer objects that represent the different chunks of media that make up the entire stream. mse gives us finer grained control over how much and how often content is...
...er http protocol to fetch files. indeed, one can support dash with a simple static file server, which is also great for cdns. this is in direct contrast with previous streaming solutions that required expensive licenses for proprietary non-standard client/server protocol implementations. 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. live profile content can introduce latency due to its transcoding and broadcasting, so dash is not suitable for real time communication like webrtc is. it can however support significantly more client connections than webrtc. there are numerous available free and open source tools for transcodin...
MessageEvent - Web APIs
achannel.onmessage). the action triggered by this event is defined in a function set as the event handler for the relevant message event (e.g. using an onmessage handler as listed above). note: this feature is available in web workers. ...
...use this anymore — use the messageevent() constructor instead. examples in our basic shared worker example (run shared worker), we have two html pages, each of which uses some javascript to perform a simple calculation. the different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows. the following code snippet shows creation of a sharedworker object using the sharedworker() constructor. both scripts contain this: var myworker = new sharedworker('worker.js'); both scripts then access the worker through a messageport object created using the sharedworker.port property. if the onmessage event is attached using addeventlistener, the port is manually started using its start() method: myw...
MessagePort.start() - Web APIs
Web › API › MessagePort › start
the start() method of the messageport interface starts the sending of messages queued on the port. this method is only needed when using eventtarget.addeventlistener; it is implied when using messagechannel.onmessage. note: this feature is available in web workers. syntax port.start() returns void. parameters none. ...
...in the following code block, you can see a handlemessage handler function, run when a message is sent back to this document using onmessage: channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } another option would be to do this using eventtarget.addeventlistener, however, when this method is used, you need to explicitly call start() to begin the flow of messages to this document: channel.port1.addeventlistener('message', handlemessage, false); function handlemessage(e) { para.innerhtml = e.data; textinput.value = ''; } channel.port1.start(); specifications specification status comment html living standardthe definition of 'start()' in that specification. living standard ...
MessagePort - Web APIs
note: this feature is available in web workers. methods inherits methods from its parent, eventtarget postmessage() sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts. start() starts the sending of messages queued on the port (only needed when using eventtarget.addeventlistener; it is implied when using messageport.onmessage.) close() disconnects the port, so it is no longer active. ...
...d when a messageevent of type messageerror is fired—that is, when it receives a message that cannot be deserialized. events message fired when a messageport object receives a message. also available via the onmessage property. messageerror fired when a messageport object receives a message that can't be deserialized. also available via the onmessageerror property. example in the following example, you can see a new channel being created using the messagechannel() constructor. when the iframe has loaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message. when a message is received back from the iframe, the onmessage function simply outputs the message to a paragraph...
Microdata DOM API - Web APIs
inner = document.createelement('ul'); for (var name = 0; name < items[item].properties.names.length; name += 1) { var propli = document.createelement('li'); propli.appendchild(document.createtextnode(items[item].properties.names[name])); inner.appendchild(propli); } itemli.appendchild(inner); outer.appendchild(itemli); } document.body.appendchild(outer); if faced with the following from an earlier example: <section itemscope itemtype="http://example.org/animals#cat"> <h1 itemprop="name http://example.com/fn">hedral</h1> <p itemprop="desc">hedral is a male american domestic shorthair, with a fluffy <span itemprop="http://example.com/color">black</span> fur with <span itemprop="http://example.com/color">white</span> paws and belly.</p> <img itemprop="img" src="hedral.jpeg...
... interface description language interface htmlpropertiescollection...
MouseEvent.pageX - Web APIs
Web › API › MouseEvent › pageX
r pagex = mouseevent.pagex; value a floating-point number of pixels from the left edge of the document at which the mouse was clicked, regardless of any scrolling or viewport positioning that may be in effect. this property was originally specified in the touch events specification as a long integer, but was redefined in the cssom view module to be a double-precision floating-point number to allow for subpixel precision. even though numeric types both are represented by number in javascript, they may be handled differently internally in the browser's code, resulting in potential behavior differences. see browser compatibility to learn which browsers have been updated to use the revised data type. example more examples you can also see an example that demonstrates how to access the mouse...
... </p> <p> <code>pagey</code>: <span id="y">n/a</span> </p> </div> the html is simple; the box we'll be watching for mouse events on is given the class "box". it has two <span> elements, one with the id "x" and one with the id "y". those will be updated each time an event occurs to contain the latest mouse coordinates relative to the page. css the css used for this example is shown below. .box { width: 400px; height: 250px; border: 2px solid darkblue; background-color: blue; color: white; font: 16px "zilla", "open sans", "helvetica", "arial", sans-serif; } result try this out here: specifications specification status comment css object model (cssom) view modulethe definition of 'pagex' in that specification. working draft redefine...
MouseEvent.screenX - Web APIs
working draft redefines mouseevent from lon...
... working draft redefines mouseevent from long to double. document object model (dom) level 3 events specificationthe definition of 'mouseevent.screenx' in that specification. ...
MouseEvent - Web APIs
vent.initmouseevent() method is kept for backward compatibility, creating of a mouseevent object should be done using the mouseevent() constructor. several more specific events are based on mouseevent, including wheelevent and dragevent. ...
...plied to a touch or tablet device when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure). instead of using this deprecated (and non-standard) property, you should instead use pointerevent and look at its pressure property. mouseevent.mozinputsource read only the type of device that generated the event (one of the moz_source_* constants listed below). 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). mouseevent.webkitforce read only the amount of pressure applied when clicking mouseevent.x read only alias for mouseevent.clientx. mouseevent.y read only alias...
msRealTime - 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. msrealtime is a read/write property which specifies whether or not to enable low-latency playback on the media element. ...
...re may also be large incompatibilities between implementations and the behavior may change in the future. msrealtime 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 play...
MutationObserver.observe() - Web APIs
ve(target, options) parameters target a dom node (which may be an element) within the dom tree to watch for changes, or to be the root of a subtree of nodes to be watched. options a mutationobserverinit object providing options that describe which dom mutations should be reported to mutationobserver’s callback. return value undefined. exceptions typeerror thrown in any of the following circumstances: the options are configured such that nothing will actually be monitored. (for example, if mutationobserverinit.childlist, mutationobserverinit.attributes, and mutationobserverinit.characterdata are all false.) the value of options.attributes is false (indicating that attribute changes are not to be monitored), but attributeoldvalue is true and/or attributefilter is pre...
... there are some caveats to note: if you call observe() on a node that's already being observed by the same mutationobserver, all existing observers are automatically removed from all targets being observed before the new observer is activated. if the same mutationobserver is not already in use on the target, then the existing observers are left alone and the new one is added. observation follows nodes when disconnected mutation observers are intended to let you be able to watch the desired set of nodes over time, even if the direct connections between those nodes are severed. if you begin watching a subtree of nodes, and a portion of that subtree is detached and moved elsewhere in the dom, you continue to watch the detached segment of nodes, receiving the same callbacks as before the n...
Navigation Timing API - Web APIs
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. while this interface is defined by the high resolution time api, the navigation timing api adds two properties: timing and navigation, of the types below. performancenavigationtiming 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. performancetiming used as the type for the value of timing, objects of this type contain timing information that can provide insight into web pa...
...ation timing api can be used to gather performance data on the client side to be sent to a server via xhr as well as measure data that was very difficult to measure by other means such as time to unload a previous page, domain look up time, window.onload total time, etc. examples calculate the total page load time to compute the total amount of time it took to load the page, you can use the following code: const perfdata = window.performance.timing; const pageloadtime = perfdata.loadeventend - perfdata.navigationstart; this subtracts the time at which navigation began (navigationstart) from the time at which the load event handler returns (loadeventend). this gives you the perceived page load time. calculate request response time you can calculate the time elapsed between the beginnin...
Navigator.getBattery() - Web APIs
syntax var batterypromise = navigator.getbattery(); return value a promise which, when resolved, calls its fulfillment handler with a single parameter: a batterymanager object which you can use to get information about the battery's state. ...
... to get information about the battery's state. exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: securityerror the user agent does not expose battery information to insecure contexts and this method was called from insecure context. note: old versions of some user agents might allow use of this feature in insecure contexts. notallowederror note: no user agent currently throws this exception, but the specification describes the following behaviors: this document is not allowed to use this feature. for example, it might not be explicitly allowed or restricted via feature-policy battery feature. example this example fetches the current charging state of the battery and es...
NavigatorID.userAgent - Web APIs
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 changes the http header that gets sent, and doesn't affect browser detection performed by javascript code. opera 6+ allows users to set the browser identification string via a menu. microsoft internet explorer uses the windows registry. safari and icab allow users to change the browser user agent string to predefined internet explorer or netscape strings via a menu. syntax var ua = navigator.useragent; value a domstring specifying the complete user agent string the browser provides both in http headers and i...
... the complete user agent string the browser provides both in http headers and in response to this and other related methods on the navigator object. the user agent string is built on a formal structure which can be decomposed into several pieces of info. each of these pieces of info comes from other navigator properties which are also settable by the user. ...
Online and offline events - Web APIs
operty is updated whenever the user switches into "offline mode" by selecting the corresponding menu item (file -> work offline in firefox). additionally, this property should update whenever a browser is no longer capable of connecting to the network. according to the specification: the navigator.online attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail)... firefox 2 updates this property when switching to/from the browser's offline mode. firefox 41 updates this property when the os reports a change in network connectivity on windows, linux, and os x. this property existed in older versions of firefox and internet explorer (the specification based itself o...
...v> <p>this is a test</p> here's the live result notes if the api isn't implemented in the browser, you can use other signals to detect if you are offline including using service workers and responses from xmlhttprequest. references 'online/offline events' section from the whatwg web applications 1.0 specification the bug tracking online/offline events implementation in firefox and a follow-up a simple test case an explanation of online/offline events ...
NavigatorPlugins.plugins - Web APIs
ugin names from enumeration. syntax var plugins = navigator.plugins; plugins is pluginarray object used to access plugin objects either by name or as a list of items. the returned value is not a javascript array, but has the length property and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and nameditem("name") methods. examples the following example function returns the version of the shockwave flash plugin. function getflashversion() { var flash = navigator.plugins.nameditem('shockwave flash'); if (typeof flash != 'object') { // flash is not present return undefined; } if(flash.version){ return flash.version; } else { //no version property (e.g. in chrome) return flash.description.replace(/shockwave...
...the version of the shockwave flash plugin. function getflashversion() { var flash = navigator.plugins.nameditem('shockwave flash'); if (typeof flash != 'object') { // flash is not present return undefined; } if(flash.version){ return flash.version; } else { //no version property (e.g. in chrome) return flash.description.replace(/shockwave flash /,""); } } the following example displays information about the installed plugin(s). var pluginslength = navigator.plugins.length; document.body.innerhtml = pluginslength + " plugin(s)<br>" + '<table id="plugintable"><thead>' +'<tr><th>name</th><th>filename</th><th>description</th><th>version</th></tr>' +'</thead><tbody></tbody></table>'; var table = document.getelementbyid('plugintable'); for(var i = 0; i <...
NetworkInformation - Web APIs
k read only returns the effective bandwidth estimate 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 th...
... 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 returns the type of connection a device is using to communicate with the network. it will be one of the following values: bluetooth cellular ethernet none wifi wimax other unknown event handlers networkinformation.onchange the event that's fired when connection information changes and the change is fired on this object. methods this interface also inherits methods of its parent, eventtarget. specifications specification status comment network in...
Network Information API - Web APIs
the entire api consists of the addition of the networkinformation interface and a single property to the navigator interface: navigator.connection. note: this feature is available in web workers. examples detect connection changes this example watches for changes to the user's connection. ...
...statement or some other method to check all of the possible values of networkinformation.type. regardless of the type value you can get an estimate of connection speed through the networkinformation.effectivetype property. let preloadvideo = true; var connection = navigator.connection || navigator.mozconnection || navigator.webkitconnection; if (connection) { if (connection.effectivetype === 'slow-2g') { preloadvideo = false; } } interfaces networkinformation provides information about the connection a device is using to communicate with the network and provides a means for scripts to be notified if the connection type changes. the networkinformation interfaces cannot be instantiated. it is instead accessed through the navigator interface. specifications specificatio...
Node.compareDocumentPosition() - Web APIs
the node.comparedocumentposition() method reports the position of the given node relative to another node in any document — not just the given node’s document. the return value is a bitmask of the following values: name value document_position_disconnected 1 document_position_preceding 2 document_position_following 4 document_position_contains 8 document_position_contained_by 16 document_position_implementation_specific 32 syntax comparemask = node.comparedocumentposition(othernode) parameters othernode the other node with which to compare the first node’s document position. return value an integer value whose bits represent the othernode's relationship to the calling node. more ...
...rios apply. for example, if othernode is located earlier in the document and contains the node on which comparedocumentposition() was called, then both the document_position_contains and document_position_preceding bits would be set, producing a value of 10 (0x0a). example const head = document.head; const body = document.body; if (head.comparedocumentposition(body) & node.document_position_following) { console.log('well-formed document'); } else { console.error('<head> is not before <body>'); } note: because the result returned by comparedocumentposition() is a bitmask, the bitwise and operator must be used for meaningful results. specifications specification status comment domthe definition of 'node.comparedocumentposition()' in that specification. li...
Node.localName - Web APIs
Web › API › Node › localName
the node.localname read-only property returns the local part of the qualified name of this node. in dom4 this api was moved from node to the element and attr interfaces. ...
... <ecomm:partner id="1001">tony's syrup warehouse </ecomm:partner> </ecomm:partners> </ecomm:business> note: in gecko 1.9.2 and earlier, the property returns the upper-cased version of the local name for html elements in html doms (as opposed to xhtml elements in xml doms). in later versions, in compliance with html5, the property returns in the case of the internal dom storage, which is lower case for both html elements in html doms and xhtml elements in xml doms. the tagname property continues to return in the upper case for html elements in html doms. for nodes of any type other than element_node and attribute_node localname is always null. specifications specification status comment document object model (dom) level 3 core specificationthe definiti...
Node.nodeName - Web APIs
Web › API › Node › nodeName
however, in html, text_field's value would read "div", because nodename and tagname return in upper c...
...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 c...
NodeList - Web APIs
Web › API › NodeList
st'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 is mostly useful for non-javascript dom implementations. ...
...javascript dom implementations. nodelist.entries() returns an iterator, allowing code to go through all key/value pairs contained in the collection. (in this case, the keys are numbers starting from 0 and the values are nodes.) nodelist.foreach() executes a provided function once per nodelist element, passing the element as an argument to the function. nodelist.keys() returns an iterator, allowing code to go through all the keys of the key/value pairs contained in the collection. (in this case, the keys are numbers starting from 0.) nodelist.values() returns an iterator allowing code to go through all values (nodes) of the key/value pairs contained in the collection. example it's possible to loop over the items in a nodelist using a for loop: for (let i = 0; i < mynodelist.length;...
NonDocumentTypeChildNode.nextElementSibling - Web APIs
the nondocumenttypechildnode.nextelementsibling read-only property returns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list. ...
...var nextnode = elementnodereference.nextelementsibling; example <div id="div-01">here is div-01</div> <div id="div-02">here is div-02</div> <script type="text/javascript"> var el = document.getelementbyid('div-01').nextelementsibling; console.log('siblings of div-01:'); while (el) { console.log(el.nodename); el = el.nextelementsibling; } </script> this example outputs the following into the console when it loads: siblings of div-01: div script polyfill for internet explorer 8 this property is unsupported prior to ie9, so the following snippet can be used to add support to ie8: // source: https://github.com/alhadis/snippets/blob/master/js/polyfills/ie8-child-elements.js if(!("nextelementsibling" in document.documentelement)){ object.defineproperty(element.prototyp...
OES_texture_float - Web APIs
tionality of this extension is available on the webgl2 context 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 extensio...
...map_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 buffers this extension implicitly enables the webgl_color_buffer_float extension (if supported), which allows rendering to 32-bit floating-point color buffers. examples var ext = gl.getextension('oes_texture_float'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.teximage2d(gl.texture_2d, 0, gl.rgba, gl.rgba, gl.float, image); specifications specification status comment oes_texture_floatthe definition of 'oes_texture_float' in that specificati...
OES_texture_float_linear - Web APIs
this extension enables this ability. ...
...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. ...
OES_texture_half_float - Web APIs
gl2 context by default. the constant in webgl2 is gl.half_float. 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_...
..._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 floating-point color buffers this extension implicitly enables the ext_color_buffer_half_float extension (if supported), which allows rendering to 16-bit floating point formats. examples var ext = gl.getextension('oes_texture_half_float'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.teximage2d(gl.texture_2d, 0, gl.rgba, gl.rgba, ext.half_float_oes, image); specifications specification status comment oes_texture_half_floatthe definition of 'oes_texture_half_float' ...
OES_texture_half_float_linear - Web APIs
this extension enables this ability. ...
...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. ...
OfflineAudioContext.suspend() - Web APIs
the time progression in the audio context at the specified time and returns a promise. this is generally useful at the time of manipulating the audio graph synchronously on offlineaudiocontext. note that the maximum precision of suspension is the size of the render quantum and the specified suspension time will be rounded down to the nearest render quantum boundary. for this reason, it is not allowed to schedule multiple suspends at the same quantized frame. also scheduling should be done while the context is not running to ensure the precise suspension. syntax offlineaudiocontext.suspend(suspendtime).then(function() { ... }); parameters suspendtime a double specifying the suspend time, in seconds. returns a promise resolving to void. exceptions the promise is rejected when any ...
... while the context is not running to ensure the precise suspension. syntax offlineaudiocontext.suspend(suspendtime).then(function() { ... }); parameters suspendtime a double specifying the suspend time, in seconds. returns a promise resolving to void. exceptions the promise is rejected when any exception is encountered. invalidstateerror if the quantized frame number is one of the following: a negative number is less than or equal to the current time is greater than or equal to the total render duration is scheduled by another suspend for the same time specifications specification status comment web audio apithe definition of 'suspend()' in that specification. working draft initial definition. ...
OrientationSensor - Web APIs
interface cannot be used directly. instead it provides properties and methods accessed by interfaces that inherit from it. 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. interfaces based on orientationsensor below is a list of interfaces based on the orientationsensor interface. absoluteorientationsensor relativeorientationsensor properties orientationsensor.quaternion returns a four element array whose elements contain the components of the unit quaternion representing the device's orientation. methods orientationsensor.populatematrix() populates the given object with the rotation matrix...
... absoluteorientationsensor relativeorientationsensor properties orientationsensor.quaternion returns a four element array whose elements contain the components of the unit quaternion representing the device's orientation. methods orientationsensor.populatematrix() populates the given object with the rotation matrix based on the latest sensor reading. the rotation maxtrix is shown below. examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an absoluteorientationsensor with a frequency of 60 times a second. on each reading it uses orientationsensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceframe: 'device' }; const sensor = new absoluteorientationsensor(options); ...
PaintWorklet - Web APIs
event handlers none. methods this interface inherits methods from worklet. paintworklet.registerpaint() registers a class programmatically generate an image where a css property expects a file. css.paintworklet.addmodule() the addmodule() method, inhertied from the worklet interface loads the module in the given javascript file and adds it to the current paintworklet. examples the following three examples go together to show creating, loading, and using a paintworklet. create a paintworklet the following shows an example worklet module. this should be in a separate js file. note that registerpaint() is called without a reference to paintworklet. class checkerboardpainter { paint(ctx, geom, properties) { // use `ctx` as if it was a normal canvas const colors = ['red',...
... <script> if ('paintworklet' in css) { css.paintworklet.addmodule('checkerboard.js'); } </script> use a paintworklet this example shows how to use a paintworklet in a stylesheet, including the simplest way to provide a fallback if paintworklet isn't supported. <style> textarea { ...
PannerNode.rolloffFactor - Web APIs
node interface is a double value describing how quickly the volume is reduced as the source moves away from the listener. this value is used by all distance models.the rollofffactor property's default value is 1. syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.rollofffactor = 1; value a number whose range depends on the distancemodel of the panner as follows (negative values are not allowed): "linear" the range is 0 to 1. "inverse" the range is 0 to infinity. "exponential" the range is 0 to infinity. exceptions rangeerror the property has been given a value that is outside the accepted range. example this example demonstrates how different rollofffactor values affect how the volume of the test tone decreases with increas...
...z position, then schedule the ramp panner.positionz.setvalueattime(0, starttime); panner.positionz.linearramptovalueattime(z_distance, starttime + note_length); osc.connect(panner) .connect(context.destination); osc.start(starttime); osc.stop(starttime + note_length); }; // this tone should decay fairly quickly scheduletesttone(1, context.currenttime); // this tone should decay slower than the previous one scheduletesttone(0.5, context.currenttime + note_length); // this tone should decay only slightly scheduletesttone(0.1, context.currenttime + note_length * 2); after running this code, the resulting waveforms should look something like this: specifications specification status comment web audio apithe definition of 'rollofffactor' in that speci...
ParentNode.append() - Web APIs
Web › API › ParentNode › append
parentnode.append() has no return value, whereas node.appendchild() returns the appended node object. parentnode.append() can append several nodes and strings, whereas node.appendchild() can only append one node. ...
...nodes) // nodelist [ #text "some text", <p> ] parentnode.append() is unscopable the append() method is not scoped into the with statement. see symbol.unscopables for more information. ...
ParentNode.replaceChildren() - Web APIs
replacechildren() provides a very convenient mechanism for emptying a node of all its children. you simply call it on the parent node without any argument specified: mynode.replacechildren(); transferring nodes between parents replacechildren() enables you to easily transfer nodes between parents, without having to resort to verbose looping code. for example, say we have a simple application allowing you to choose what food you want for your party. this html might look something like this: <h2>party food option list</h2> <main> <div> <label for="no">no thanks!</label> <select id="no" multiple size="10"> <option>apples</option> <option>oranges</option> <option>grapes</option> <option>bananas</option> <option>kiwi fruits</option> <option>choco...
... to do this, we give each of the buttons a click event handler, which collects together the selecte...
PaymentCurrencyAmount.value - Web APIs
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. ...
...east 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 value to this format before submitting the payment. see the example verifying a properly formatted price below for a simple regular expression that can be used to validate the value string prior to submission. examples representing prices this example represents the price of $42.95 in us dollars: let itemprice = { currency: "usd", value: "42.95" }; this example specifies a price of £7.77: let shippingcost = { currency: "gbp", value: "7.77" } this example specifies a price of 1000¥: let...
PaymentCurrencyAmount - Web APIs
-letter iso 4217 currency identifier (iso 4217) indicating the currency used for the payment value. value a string containing a valid decimal value representing the mount of currency constituting the payment amount. ...
... specifications specification status comment payment request apithe definition of 'paymentcurrencyamount' in that specification. ...
PaymentResponse.retry() - Web APIs
the paymentresponse interface's retry() method makes it possible to ask the user to retry a payment after an error occurs during processing. this lets your app gracefully deal with situations such as invalid shipping addresses or declined credit cards. syntax retrypromise = paymentrequest.retry(errorfields); parameters errorfields a paymentvalidationerrors object, with the following properties: error optional a general description of a payment error from which the user may attempt to recover by retrying the payment, possibly after correcting mistakes in the payment information. error can be provided all by itself to provide only a generic error message, or in concert with the other properties to serve as an overview while other properties' values gude the user to errors in s...
...typically you will use this by calling show(), then entering a loop or recursive function that checks the paymentresponse for errors or other reasons to retry the payment request. if a retry is needed, the loop calls retry(), then loops back to check the response when it comes in. the loop exits only when the user either cancels the payment request or the request is successful. see the example below for a thorough example, but the basic concept, in outline form, is: create a new paymentrequest (new paymentrequest()) display the payment request (paymentrequest.show() if show() resolves, the returned paymentresponse describes the requested payment and the options chosen by the user. continue by... validate the returned reponse; if there are any fields whose values are not acceptable...
PaymentResponse - Web APIs
goption read only secure context returns the id attribute of the shipping option selected by the user. this option is only present when the requestshipping option is set to true in the options parameter of the paymentrequest() constructor. methods paymentresponse.retry() secure context if something is wrong with the payment response's data (and there is a recoverable error), this method allows a merchant to request that the user retry the payment. the method takes an object as argument, which is used to signal to the user exactly what is wrong with the payment response so they can try to correct any issues. paymentresponse.complete() secure context notifies the user agent that the user interaction is over. this causes any remaining user interface to be closed. this method should onl...
...d. this method should only be called after the promise returned by the paymentrequest.show() method. events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface. payerdetailchange secure context fired during a retry when the user makes changes to their personal information while filling out a payment request form. allows the developer to revalidate any requested user data (e.g., the phone number or the email address) if it changes. also available via the onpayerdetailchange property. specifications specification status comment payment request apithe definition of 'paymentresponse' in that specification. candidate recommendation initial definition. ...
Payment processing concepts - Web APIs
vice is the payment method provider. payment handler the implementation of the code needed to interface with a particular payment method provider in order to process payments. some payment handlers use merchant validation, which is the process of validating the identity of a merchant in some way, usually using some form of cryptographic response such as a public key. validated merchants are allowed to interface with a payment handler. payment method identifiers payment handlers are identified by payment method identifiers, which are strings uniquely identifying the payment handler. these may be either one of the standardized payment handler identifiers, or a url used by the payment processing service to both identify itself and to handle payments. standardized payment method identifier...
.... this results in the creation and returning of a payment method-specific object that contains the information needed to handle the transaction. merchant validation some payment handlers use merchant validation, which is the process of validating the identity of a merchant in some way, usually using some form of cryptographic challenge. if the merchant doesn't successfully validate, it's not allowed to use the payment handler. the exact validation technology depends on the payment handler, and merchant validation is entirely optional. in the end, the only thing that the web site or app is responsible for is fetching the merchant's validation key and passing it into the event's complete() method. paymentrequest.onmerchantvalidation = function(event) { event.complete(fetchvalidationdata(...
performance.measure() - Web APIs
's performance entry buffer between marks, the navigation start time, or the current time. when measuring between two marks, there is a start mark and end mark, respectively. the named timestamp is referred to as a measure. the measure can be retrieved by one of the performance 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); perform...
...ng 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 in the browser's performance entry buffer. const markernamea = "example-marker-a" const markernameb = "example-marker-b" // run some nested timeouts, and create a performancemark for each. performance.mark(markernamea); settimeout(function() { performance.mark(markernameb); settimeout(function() { // creat...
performance.now() - Web APIs
Web › API › Performance › now
it used to be the same as t0 of the main context, but this was changed. ...
...it used to be the same as t0 of the main context, but this was changed. ...
PerformanceEntry.entryType - Web APIs
he entrytype property returns a domstring representing the type of performance metric such as, for example, "mark". this property is read only. note: this feature is available 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. ...
...reated 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("performance.mark not supported"); return; } // create a performance entry named "begin" via the mark() method performance.mark("begin"); // check the entrytype of all the "begin" entries va...
PerformanceEntry.name - Web APIs
f the performanceentry interface returns a value that further specifies the value returned by the performanceentry.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 n...
...equest 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("begin"); do_work(50000); performance.mark("end"); // use getentries() to iterate throug...
PerformanceEntry - Web APIs
ates a single performance metric that 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. 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 prop...
...erty page for valid values. performanceentry.starttime read only a domhighrestimestamp representing the starting time for the performance metric. performanceentry.duration read only a domhighrestimestamp representing the time value of the duration of the performance event. methods performanceentry.tojson() returns a json representation of the performanceentry object. example the following example checks all performanceentry properties to see if the browser supports them and if so, write their values to the console. function print_performanceentries() { // use getentries() to get a list of all performance entries var p = performance.getentries(); for (var i=0; i < p.length; i++) { console.log("performanceentry[" + i + "]"); print_performanceentry(p[i]); } } func...
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. ...
...heck 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 logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_start_and_end_properties(p[i]); } } function print_start_and_end_properties(perfentry) { // print...
PerformanceServerTiming - Web APIs
note that this interface is only available in secure contexts (https) in some browsers. ...
...note that this interface is only available in secure contexts (https) in some browsers. ...
Using the Performance API - Web APIs
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. the following code example shows the use of domhighrestimestamp and the performance.now() method. the now() method returns a timestamp (of type domhighrestimestamp) that is a discrete point in time. by calling this method before and after a task, the time it takes to do the task can be measured. function calculate_time() { var starttime; var endtime; starttime = performance.now(); do_task(); end...
.... by calling this method before and after a task, the time it takes to do the task can be measured. function calculate_time() { var starttime; var endtime; starttime = performance.now(); do_task(); endtime = performance.now(); return (endtime - starttime); } serializing the performance object json serialization of the performance object is done via the tojson() method. in the following example, json serialization for the performance, performance.timing and performance.navigation objects is printed in the object element. function print_json() { var json; var o = document.getelementsbytagname("output")[0]; if (window.performance.tojson === undefined) { json = "window.performance.tojson() is not supported"; o.innerhtml += json + "<br>"; } else { var s; ...
Performance API - Web APIs
iming 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, 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...
...alizer to the performanceentry interface as well as adding the performanceobserver interface and callback resource timing level 1 candidate recommendation adds the performanceresourcetiming interface. adds the clearresourcetimings() method, the setresourcetimingbuffersize() method, and the onresourcetimingbufferfull event handler to the performance interface. also adds the timing-allow-origin response header. resource timing level 2 working draft adds the nexthopprotocol, workerstart, transfersize, encodedbodysize, and decodedbodysize properties to the performanceresourcetiming interface. resource timing level 3 editor's draft user timing recommendation adds mark(), clearmarks(), measure() and clearmeasures() methods to the performa...
Permissions.query() - Web APIs
Web › API › Permissions › query
rmission 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 send silent push notifications. the default is false. sysex: (midi only) indicates whether you need and/or receive system exclusive messages. the default is false. note: as of firefox 44, the permissions for notifications and push have been merged. if permission is granted (e.g. by the user, in the relevan...
...midi only) indicates whether you need and/or receive system exclusive messages. the default is false. note: as of firefox 44, the permissions for notifications and push have been merged. if permission is granted (e.g. by the user, in the relevant permissions dialog), navigator.permissions.query() will return true for both notifications and push. note: the persistent-storage permission allows an origin to use a persistent box (i.e persistent storage) for its storage, as per the storage api. returns a promise that resolves to a permissionstatus object. exceptions exception explanation typeerror retrieving the permissiondescriptor information failed in some way, or the permission doesn't exist or is currently unsupported (e.g. midi, or push with uservis...
Permissions.revoke() - Web APIs
sed on the permissiondescriptor dictionary that sets options for the 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. valid values are 'geolocation', 'midi', 'notifications', and 'push'. uservisibleonly: (push only, not supported in firefox — see the browser compatibility section below) indicates whether you want to show a notification for every message or be able to send silent push notifications. the default is false. sysex: (midi only) indicates whether you need and/or receive system exclusive messages. the default is false. note: as of firefox 44, the permissions for notifications and push have been merged. if permission is granted (e.g. by the user, in the relevan...
...midi only) indicates whether you need and/or receive system exclusive messages. the default is false. note: as of firefox 44, the permissions for notifications and push have been merged. if permission is granted (e.g. by the user, in the relevant permissions dialog), navigator.permissions.query() will return true for both notifications and push. note: the persistent-storage permission allows an origin to use a persistent box (i.e persistent storage) for its storage, as per the storage api. returns a promise that calls its fulfillment handler with a permissionstatus object indicating the result of the request. exceptions typeerror retrieving the permissiondescriptor information failed in some way, or the permission doesn't exist or is currently unsupported (e.g. midi, or push...
PluginArray - Web APIs
r enumerable in the latest browser versions. properties pluginarray.lengthread only the number of plugins in the array. methods pluginarray.item returns the plugin at the specified index into the array. pluginarray.nameditem returns the plugin with the specified name. pluginarray.refresh refreshes all plugins on the current page, optionally reloading documents. examples the following example function returns the version of the shockwave flash plugin. var pluginslength = navigator.plugins.length; document.body.innerhtml = pluginslength + " plugin(s)<br>" + '<table id="plugintable"><thead>' +'<tr><th>name</th><th>filename</th><th>description</th><th>version</th></tr>' +'</thead><tbody></tbody></table>'; var table = document.getelementbyid('plugintable'); for(var i ...
... var pluginslength = navigator.plugins.length; document.write( pluginslength.tostring() + " plugin(s)<br>" + "name | filename | description<br>" ); for(var i = 0; i < pluginslength; i++) { document.write( navigator.plugins[i].name + " | " + navigator.plugins[i].filename + " | " + navigator.plugins[i].descri...
PositionOptions - Web APIs
ect containing option properties to pass as a parameter of geolocation.getcurrentposition() and geolocation.watchposition(). properties positionoptions.enablehighaccuracy secure context is a boolean that indicates the application would like to receive the best possible results. if true and if the device is able to provide a more accurate position, it will do so. ...
...the default value is infinity, meaning that getcurrentposition() won't return until the position is available. positionoptions.maximumage secure context is a positive long value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return. ...
ProgressEvent - Web APIs
the progressevent interface represents events measuring progress of an underlying process, like an http request (for an xmlhttprequest, or the loading of the underlying resource of an <img>, <audio>, <video>, <style> or <link>). ...
...ork 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 uses it to display the status of the request. var progressbar = document.getelementbyid("p"), client = new xmlhttprequest() client.open("get", "magical-unicorns") client.onprogress = function(pe) { if(pe.lengthcomputable) { progressbar.max = pe.total progressbar.value = pe.loaded } } client.onloadend = function(pe) { p...
PublicKeyCredentialCreationOptions.excludeCredentials - Web APIs
ckeycredentialcreationoptions dictionary, is an array whose elements are descriptors for the public keys already existing for a given user. this is provided by the relying party's server if it wants to prevent creation of new credentials for an existing user. syntax excludecredentials = publickeycredentialcreationoptions.excludecredentials value an array whose elements are objects with the following properties: type a string describing type of public-key credential to be created. as of this writing (march 2019), only "public-key" may be used. id a buffersource matching an existing public key credential identifier (publickeycredential.rawid). this identifier is generated during the creation of the publickeycredential instance. transports optional an array of strings describing the ...
...ation of the publickeycredential instance. transports optional an array of strings describing the possible transports between the client and the authenticator. the value of the strings may be: "usb": the authenticator can be contacted via a removable usb link "nfc": the authenticator may be used over nfc (near field communication) "ble": the authenticator may be used over ble (bluetooth low energy) "internal": the authenticator is specifically bound to the client device (cannot be removed). if the authenticator already contains one of such a public key credential, the client will throw a domexception or asks the user if they want to create a new credential. examples var publickey = { excludecredentials: [ { type: "public-key", // the id for john.doe@examp...
PublicKeyCredentialRequestOptions - Web APIs
onds, which indicates the time the caller is willing to wait for the retrieval operation to complete. this hint may be overridden by the browser. publickeycredentialrequestoptions.rpid optional a usvstring which indicates the relying party's identifier (ex. "login.example.org"). if this option is not provided, the client will use the current origin's domain. publickeycredentialrequestoptions.allowcredentials optional an array of credentials descriptor which restricts the acceptable existing credentials for retrieval. publickeycredentialrequestoptions.userverification optional a string qualifying how the user verification should be part of the authentication process. publickeycredentialrequestoptions.extensions optional an object with several client extensions' inputs. those extensions...
... legacy fido apis credentials, prompting a specific text on the authenticator, etc.). methods none. ...
PushManager.subscribe() - Web APIs
urns a promise that resolves to a pushsubscription object containing details of a push subscription. a new push subscription is created if the current service worker does not have an existing subscription. syntax ​pushmanager.subscribe(options).then(function(pushsubscription) { ... } ); parameters options optional an object containing optional configuration parameters. it can have the following properties: uservisibleonly: a boolean indicating that the returned push subscription will only be used for messages whose effect is made visible to the user. applicationserverkey: a base64-encoded domstring or arraybuffer containing an ecdsa p-256 public key that the push server will use to authenticate your application server. if specified, all messages from your application server mus...
...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. ...
RTCConfiguration.bundlePolicy - Web APIs
eerconnection. the configuration object is used as an input to the rtcpeerconnection() constructor. syntax let rtcconfiguration = { bundlepolicy: policy }; rtcconfiguration.bundlepolicy = policy; value a domstring identifying the sdp bundling policy to use for the rtp streams used by the rtcpeerconnection. this string, which must be a member of the rtcbundlepolicy enumeration, has the following possible values: balanced the ice agent begins by creating one rtcdtlstransport to handle each type of content added: one for audio, one for video, and one for the rtc data channel, if applicable. if the remote peer isn't bundle-aware, the ice agent chooses one audio track and one video track and those two tracks are each assigned to the corresponding rtcdtlstransport. all other tracks are...
...a single ip and port on one peer to a single ip and port on another peer, all using the same rtcdtlstransport. the goal of bundling is to optimize performance by reducing the overhead of having multiple transports in play. the fewer rtp transports or bundles of rtp streams you have, the better the network performance will be. all current major browsers are bundle compatible. examples the following example creates a new rtcpeerconnection with a configuration setting the connection's bundlepolicy to max-compat to maximize compatibility while attempting to optimize network use. it also specifies stun:stun.example.com as the stun server for ice to use during negotiation. let config = { iceservers: [ { urls: [ "stun:stun.example.com" ] }, ], bundlepolicy: "max-compat" };...
RTCConfiguration.certificates - Web APIs
catelist }; let rtcconfiguration.certificates = [ cert1... ]; let certificates = rtcconfiguration.certificates; value an array of rtccertificate objects, each specifying one security certificate available for use when connecting to a remote peer. if this property isn't specified, the browser will automatically generate and use a certificate to secure the connection. see using certificates below for more information on why you might want to—or not to—explicitly provide certificates. description if this property isn't included in the configuration, a set of certificates is automatically generated for each instance of rtcpeerconnection. although a given dtls connection only uses a single certificate, providing multiple options in the certificates list may improve the odds of establis...
...cpeerconnection.generatecertificate() function. the certificates property's value cannot be changed once it's first specified. if it's included in the configuration passed into a call to a 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 sub...
RTCDTMFSender - Web APIs
the rtcdtmfsender interface provides a mechanism for transmitting dtmf codes on a webrtc rtcpeerconnection. you gain access to the connection's rtcdtmfsender through the rtcrtpsender.dtmf property on the audio track you wish to send dtmf with. the primary purpose for webrtc's dtmf support is to allow webrtc-based communication clients to be connected to a public-switched telephone network (pstn) or other legacy telephone service, including extant voice over ip (voip) services. ...
...ork (pstn) or other legacy telephone service, including extant voice over ip (voip) services. for that reason, dtmf can't be used between two webrtc-based devices, because there is no mechanism provided by webrtc for receiving dtmf codes. ...
RTCDTMFToneChangeEvent.RTCDTMFToneChangeEvent() - Web APIs
the rtcdtmftonechangeevent() constructor creates a new rtcdtmftonechangeevent. syntax var event = new rtcdtmftonechangeevent(type, options); parameters type a domstring containing the name of the event. this is always "tonechange". options a dictionary of type rtcdtmftonechangeeventinit, which may contain one or more of the following fields: tone a domstring containing a single dtmf tone character which has just begun to play, or an empty string ("") to indicate that the previous tone has stopped playing. see tone characters for details on what characters are permitted. return value a newly-created rtcdtmftonechangeevent, configured as specified in the provided options. tone characters the digits 0-9 these characters represent the digit keys on a telepho...
...ermitted. return value a newly-created rtcdtmftonechangeevent, configured as specified in the provided options. tone characters the digits 0-9 these characters represent the digit keys on a telephone keypad. the letters a-d these characters represent the "a" through "d" keys which are part of the dtmf standard but not included on most telephones. these are not interpreted as digits. lower-case "a"-"d" automatically gets converted to upper-case. the pound/hash sign ("#") and the asterisk ("*") these correspond to the similarly-labeled keys which are typically on the bottom row of the telephone keypad. the comma (",") this character instructs the dialing process to pause for two seconds before sending the next character in the buffer. all other characters are unrecognized a...
RTCDTMFToneChangeEvent - Web APIs
constructors rtcdtmftonechangeevent() returns a new rtcdtmftonechangeevent. ...
...of the properties of the event. methods supports the methods defined in event. there are no additional methods. examples this snippet is derived loosely from the full, working example you'll find in when a tone finishes playing in using dtmf with webrtc. it appends each tone to a display box as it's played, and, once all tones have been sent, re-enabled a previously-disabled "send" button, allowing the next dmtf string to be entered. dtmfsender.addeventlistener("change", function(event) { if (event.tone !== "") { dialstringbox.innertext += event.tone; } else { senddtmfbutton.disabled = false; } }, false); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtmftonechangeevent' in th...
RTCDataChannel.bufferedAmount - Web APIs
ronously. 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 bufferedamount value, even though the messages are neither sent nor buffered. whenever this value decreases to fall to or below the value specified in the bufferedamountlowthreshold property, the user agent fires the bufferedamountlow event. this event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them. syntax var amount = adatachannel.bufferedamount; value the number of bytes of data currently queued to be sent over the data channel but have not yet...
... var dc = peerconnection.createdatachannel("file transfer"); /* ... ...
RTCIceCandidate.RTCIceCandidate() - Web APIs
l rtcicecandidateinit object providing information about the candidate; if this is provided, the candidate is initialized configured to represent the described candidate. return value a newly-created rtcicecandidate object, optionally configured based on the specified object based on the rtcicecandidateinit dictionary. if candidateinfo is provided, the new rtcicecandidate is initialized as follows: each member of the rtcicecandidateinit object is initialized to the value of the property by the same name from rtcicecandidateinit. this includes the candidate, sdpmid, sdpmlineindex, and usernamefragment properties. the candidate string (which is sdp text) is parsed; each property found is stored in the corresponding field in the rtcicecandidate. if any of the fields is invalid, parsing o...
... and usernamefragment properties. the candidate string (which is sdp text) is parsed; each property found is stored in the corresponding field in the rtcicecandidate. if any of the fields is invalid, parsing of the string silently aborts without throwing an exception. the default value of candidate is the empty string, which indicates that the candidate is an "end-of-candidates" message. the following fields are initialized to null if they are not included in the rtcicecandidate.candidate property: foundation, component, priority , ip, protocol, port, type, tcptype, relatedaddress, and relatedport. note: parsing of the candidate string is performed using the candidate-attribute grammar from the webrtc specification. exceptions typeerror the specified rtcicecandidateinit has values ...
RTCIceCandidate.usernameFragment - Web APIs
username fragment ("ufrag") that uniquely identifies a single ice interaction session. this value is specified when creating the rtcicecandidate by setting the corresponding usernamefragment value in the rtcicecandidateinit object when creating a new candidate with new rtcicecandidate(). note that 24 bits of the username fragment are required to be randomized by the browser. see randomization below for details. if you instead call rtcicecandidate() with a string parameter containing the candidate m-line text, the value of usernamefragment is extracted from the m-line. syntax var ufrag = rtcicecandidate.usernamefragment; value a domstring containing the username fragment (usually referred to in shorthand as "ufrag" or "ice-ufrag") that, along with the ice password ("ice-pwd"), uniquely ...
...andidate() 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.getreceivers(); receivers.forea...
RTCIceCandidatePairStats - Web APIs
ary reports statistics which provide insight 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 op...
.... this includes botyh connectivity check and consent check requests. you can compute the average round trip time (rtt) by dividing this value by responsesreceived. transportid optional a domstring that uniquely identifies the rtcicetransport that was inspected to obtain the transport-related statistics (as found in rtctransportstats) used in generating this object. obsolete properties the following properties have been removed from the specification and should no longer be used. you should update any existing code to avoid using them as soon as is practical. check the compatibility table for details on which browsers support them and in which versions. priority optional an integer value indicating the candidate pair's priority. readable optional a boolean value indicating wheth...
RTCIceServer - Web APIs
in the urls property; the startup time for your connection will go up substantially. every server in the list will be contacted and tried out before one is selected to be used for negotiation. older versions of the webrtc specification included an url property instead of urls; this was changed in order to let you specify multiple addresses for each server in the list, as shown in the example below. obsolete properties the following properties have been removed from the specification and should not be used. url this obsolete property is a string specifies a single ice server's url. do not use this property; use urls instead. because many older books and examples still use this, we include it to help developers update their code or make sense of older examples. example the config...
...the first one, stun:stun.services.mozilla.com, requires authentication, so the username and password are provided. the second server has two urls: stun:stun.example.com and stun:stun-1.example.com. ...
RTCIdentityErrorEvent.protocol - Web APIs
the read-only property rtcidentityerrorevent.protocol is a domstring describing the idp protocol in use. firefox implements the interface of this property under the following name: rtcpeerconnectionidentityerrorevent. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
...e of this property under the following name: rtcpeerconnectionidentityerrorevent. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
RTCInboundRtpStreamStats.averageRtcpInterval - Web APIs
g-point value indicating the average rtcp transmission interval, in seconds. the rtcp 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. ...
...ing-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 endpoint computes this value when sending compound rtcp packets, which must contain at least an rtcp rr or sr packet and an sdes packet with the cname item. specifications specifi...
RTCInboundRtpStreamStats.qpSum - Web APIs
ery 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 average from there. see calculating average quantization below for a function that does this. also, the exact meaning of the qp value depends on the codec being used. for example, for the vp8 codec, the qp value can be anywhere from 1 to 127 and is found in the frame header element "y_ac_qi", whose value is defined in rfc 6386: 19.2. h.264 uses a qp which ranges from 0 to 51; in this case, it's an index used to derive a scaling matrix used during the quanti...
...ed in rfc 6386: 19.2. h.264 uses a qp which ranges from 0 to 51; in this case, it's an index used to derive a scaling matrix used during the quantization process. additionally, qp is not likely to be the only parameter the codec uses to adjust the compression. see the individual codec specifications for details. example calculating average quantization the calculateaverageqp() function shown below computes the average qp for the given rtcstats object that contains rtp stream statistics, returning 0 if the object doesn't describe an rtp stream. function calculateaverageqp(stats) { let framecount = 0; switch(stats.type) { case "inbound-rtp": case "remote-inbound-rtp": framecount = stats.framesdecoded; break; case "outbound-rtp": case "remote-outbound-rtp": ...
RTCOutboundRtpStreamStats.averageRtcpInterval - Web APIs
erty of the rtcoutboundrtpstreamstats dictionary is a floating-point value indicating 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. ...
...ing-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 endpoint computes this value when sending compound rtcp packets, which must contain at least an rtcp rr or sr packet and an sdes packet with the cname item. specifications specifi...
RTCOutboundRtpStreamStats.pliCount - Web APIs
sent to this sender by the remote peer's rtcrtpreceiver. these are sent by the receiver's decoder to notify the sender's encoder that an undefined amount of coded video data, which may span frame boundaries, has been lost. note: this property is only used for video streams. ...
...oder to notify the sender's encoder that an undefined amount of coded video data, which may span frame boundaries, has been lost. note: this property is only used for video streams. usage notes upon receiving a pli packet, the sender may have responded by sending a full frame to the remote peer to allow it to re-synchronize with the media. however, the primary purpose of a pli packet is to allow the rtcrtpsender for which this rtcoutboundrtpstreamstats object provides statistics to consider techniques to mitigate network performance issues. this is often achieved by methods such as increasing the compression or lowering resolution, although the mechanisms available to reduce the bit rate of the stream vary from codec to codec. specifications specification status comment ...
RTCOutboundRtpStreamStats.qpSum - Web APIs
mportant 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 does this. also, the exact meaning of the qp value depends on the codec being used. for example, for the vp8 codec, the qp value can be anywhere from 1 to 127 and is found in the frame header element "y_ac_qi", whose value is defined in rfc 6386: 19.2. h.264 uses a qp which ranges from 0 to 51; in this case, it's an index used to derive a scaling matrix used during the quanti...
...ed in rfc 6386: 19.2. h.264 uses a qp which ranges from 0 to 51; in this case, it's an index used to derive a scaling matrix used during the quantization process. additionally, qp is not likely to be the only parameter the codec uses to adjust the compression. see the individual codec specifications for details. example calculating average quantization the calculateaverageqp() function shown below computes the average qp for the given rtcstats object that contains rtp stream statistics, returning 0 if the object doesn't describe an rtp stream. function calculateaverageqp(stats) { let framecount = 0; switch(stats.type) { case "inbound-rtp": case "remote-inbound-rtp": framecount = stats.framesdecoded; break; case "outbound-rtp": case "remote-outbound-rtp": ...
RTCPeerConnection() - Web APIs
of type rtccertificate which are used by the connection for authentication. if this property isn't specified, a set of certificates is generated automatically for each rtcpeerconnection instance. although only one certificate is used by a given connection, providing certificates for multiple algorithms may improve the odds of successfully connecting in some circumstances. see using certificates below for additional information. this configuration option cannot be changed after it is first specified; once the certificates have been set, this property is ignored in future calls to rtcpeerconnection.setconfiguration(). icecandidatepoolsize optional an unsigned 16-bit integer value which specifies the size of the prefetched ice candidate pool. the default value is 0 (meaning no candidate pre...
...once the certificates have been set, this property is ignored in future calls to rtcpeerconnection.setconfiguration(). icecandidatepoolsize optional an unsigned 16-bit integer value which specifies the size of the prefetched ice candidate pool. the default value is 0 (meaning no candidate prefetching will occur). you may find in some cases that connections can be established more quickly by allowing the ice agent to start fetching ice candidates before you start trying to connect, so that they're already available for inspection when rtcpeerconnection.setlocaldescription() is called. changing the size of the ice candidate pool may trigger the beginning of ice gathering. iceservers optional an array of rtciceserver objects, each describing one server which may be used by the ice agent...
RTCPeerConnection.createOffer() - Web APIs
s 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 transmission, this can cause loss of important low-volume sounds. also, emergency calls should never cut audio when quiet. this option defaults to true (voice ac...
... option defaults to true (voice activity detection enabled). deprecated parameters in older code and documentation, you may see a callback-based version of this function. this has been deprecated and its use is strongly discouraged. you should update any existing code to use the promise-based version of createoffer() instead. the parameters for this form of createoffer() are described below, to aid in updating existing code. successcallback an rtcsessiondescriptioncallback which will be passed a single rtcsessiondescription 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...
RTCPeerConnection.getStats() - Web APIs
ull (the default value), statistics will be gathered for the entire rtcpeerconnection. return value a promise which resolves with an rtcstatsreport object providing connection statistics. the contents of the report depend on the selector as well as other details of the connection. exceptions this method does not throw exceptions; instead, it rejects the returned promise with one of the following errors: invalidaccesserror there is no rtcrtpsender or rtcrtpreceiver whose track matches the specified selector, or selector matches more than one sender or receiver. obsolete syntax previously, getstats() used success and failure callbacks to report the results to you, instead of using a promise. this version of getstats() is obsolete; in addition, the data it returns is entirely di...
...atsoutput += `<strong>${statname}:</strong> ${report[statname]}<br>\n`; } }); }); document.queryselector(".stats-box").innerhtml = statsoutput; }); }, 1000); this works by calling getstats(), then, when the promise is resolved, iterates over the rtcstats objects on the returned rtcstatsreport. a section is created for each report with a header and all of the statistics below, with the type, id, and timestamp handled specially to place them at the top of the list. once the html for the report is generated, it is injected into the element whose class is "stats-box" by setting its innerhtml property. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.getstats()' ...
RTCPeerConnection: negotiationneeded event - Web APIs
celable no interface event event handler property rtcpeerconnection.onnegotiationneeded the negotiationneeded event is first dispatched to the rtcpeerconnection when media is first added to the connection. this starts the process of ice negotiation by instructing your code to begin exchanging ice candidates through the signaling server. see signaling transaction flow in signaling and video calling for a description of the signaling process that begins with a negotiationneeded event. examples in this example, we use addeventlistener() to create an event handler for negotiationneeded. its role is to create an sdp offer and send it through the signaling channel to the remote peer. pc.addeventlistener("negotiationneeded", ev => { pc.createoffer() .then(off...
...ideo-offer", sdp: pc.localdescription })) .catch(err => { /* handle error */ ); }, false); after creating the offer, the local end is configured by calling rtcpeerconnection.setlocaldescription(); then a signaling message is created and sent to the remote peer through the signaling server, to share that offer with the other peer. the other peer should recognize this message and follow up by creating its own rtcpeerconnection, setting the remote description with setremotedescription(), and then creating an answer to send back to the offering peer. you can also set an event handler for the negotiationneeded event by assigning the event handler function to the rtcpeerconnection.onnegotiationneeded property: pc.onnegotiationneeded = ev => { pc.createoffer() .then(offer => re...
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
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 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) {...
... dividing framesdecoded by elapsedtime. the remainder of the networkteststop() function constructs the html used to display the output of the collected and computed results to the user, then append it to the element statsbox, which we're using to show the status updates to the user. the output log, given the styles used by the example, looks like this: in the screenshot, we see a heading followed by the scrollable <div> we refer to as statsbox. the box contains a number of log entries, the last handful of which are visible. each one represents approximately one second of time (since that's much time we're waiting between calling networkteststart() and networkteststop()). try it and fork it this example is available on glitch for you to try out, examine, or remix. you can also access ...
RTCRtpEncodingParameters.maxBitrate - Web APIs
the rtcrtpencodingparameters dictionary's maxbitrate property specifies the maximum number of bits per second to allow a track encoded with this encoding to use. syntax rtpencodingparameters.maxbitrate = maxbitspersecond; rtpencodingparameters = { maxbitrate: maxbitspersecond }; maxbitspersecond = rtpencodingparameters.maxbitrate; value an unsigned long integer value specifying the maximum bandwidth this encoding is permitted to use for a track of media it encodes in terms of bits per second. other parameters may further reduce the bandwidth used by the track; for example, maxframerate will, if set low enough, constrain the bandwidth as well. in addition, there's no guarantee that the network interface can support the specified bandwidth, in which case the actual bandwidth will be ...
...bandwidth this encoding is permitted to use for a track of media it encodes in terms of bits per second. other parameters may further reduce the bandwidth used by the track; for example, maxframerate will, if set low enough, constrain the bandwidth as well. in addition, there's no guarantee that the network interface can support the specified bandwidth, in which case the actual bandwidth will be lower. this value is computed using the standard transport independent application specific maximum (tias) bandwidth as defined by rfc 3890, section 6.2.2; this is the maximum bandwidth needed without considering protocol overheads from ip, tcp or udp, and so forth. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definitio...
RTCRtpSendParameters - Web APIs
degradationpreference specifies the preferred way the webrtc layer should handle optimizing bandwidth against quality in constrained-bandwidth situations; the value comes from the rtcdegradationpreference enumerated string type, and the default is balanced. ...
...width situations; the value comes from the rtcdegradationpreference enumerated string type, and the default is balanced. encodings an array of rtcrtpencodingparameters objects, each specifying the parameters for a single codec that could be used to encode the track's media. priority a string from the rtcprioritytype enumerated type which indicates the encoding's priority. the default value is low. transactionid a string containing a unique id for the last set of parameters applied; this value is used to ensure that setparameters() can only be called to alter changes made by a specific previous call to getparameters(). specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpsendparameters' in tha...
RTCRtpStreamStats.qpSum - Web APIs
ery 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 average from there. see calculating average quantization below for a function that does this. also, the exact meaning of the qp value depends on the codec being used. for example, for the vp8 codec, the qp value can be anywhere from 1 to 127 and is found in the frame header element "y_ac_qi", whose value is defined in rfc 6386: 19.2. h.264 uses a qp which ranges from 0 to 51; in this case, it's an index used to derive a scaling matrix used during the quanti...
...ed in rfc 6386: 19.2. h.264 uses a qp which ranges from 0 to 51; in this case, it's an index used to derive a scaling matrix used during the quantization process. additionally, qp is not likely to be the only parameter the codec uses to adjust the compression. see the individual codec specifications for details. example calculating average quantization the calculateaverageqp() function shown below computes the average qp for the given rtcrtpstreamstats object, returning 0 if the object doesn't describe an rtp stream. function calculateaverageqp(stats) { let framecount = 0; switch(stats.type) { case "inbound-rtp": case "remote-inbound-rtp": framecount = stats.framesdecoded; break; case "outbound-rtp": case "remote-outbound-rtp": framecount = stats.fra...
RTCRtpStreamStats - Web APIs
and rtcrtpreceiver.getstats() methods to provide detailed statistics about webrtc connectivity. while the dictionary has a base set of properties that are present in each of these cases, there are also additional properties added depending on which interface the method is called on. rtcrtpstreamstats is the base class for all rtp-related statistics reports. ...
... standard fields included for all media types codecid a domstring which uniquely identifies the object which was inspected to produce the rtccodecstats object associated with this rtp stream. kind a domstring whose value is "audio" if the associated mediastreamtrack is audio-only or "video" if the track contains video. ...
RTCRtpTransceiver.direction - Web APIs
ar direction = rtcrtptransceiver.direction value a domstring whose value is one of the strings which are a member of the rtcrtptransceiverdirection enumerated type, indicating the transceiver's preferred direction. the rtcrtptransceiverdirection type is an enumeration of string values. each describes how the transceiver's associated rtcrtpsender and rtcrtpreceiver behave as shown in the table below. value rtcrtpsender behavior rtcrtpreceiver behavior "sendrecv" offers to send rtp data, and will do so if the other peer accepts the connection and at least one of the sender's encodings is active1. offers to receive rtp data, and does so if the other peer accepts. "sendonly" offers to send rtp data, and will do so if the other peer accepts the conn...
...ot 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's rtcpeerconnection is closed or the rtcrtpreceiver is stopped. usage notes setting the direction when you change the value of direction, an invalidstateerror exception will occur if the connection is closed or the receiver is stopped. if the new value of direction is in fact different from the existing value, renegotiation o...
RTCSessionDescription.toJSON() - Web APIs
"sdp", containing a domstring, or null, with the sdp message corresponding to rtcsessiondescription.sdp property. ...
... "sdp", containing a domstring, or null, with the sdp message corresponding to rtcsessiondescription.sdp property. ...
ReadableStream.ReadableStream() - Web APIs
the readablestream() constructor creates and returns a readable stream object from the given handlers. syntax var readablestream = new readablestream(underlyingsource[, queuingstrategy]); parameters underlyingsource an object containing methods and properties that define how the constructed stream instance will behave. underlyingsource can contain the following: start(controller) this is a method, called immediately when the object is constructed. the contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream fuctionality. if this process is to be done asynchronously, it can return a promise to signal success or failure. the controller parameter passed to this method is a readablestr...
...queuingstrategy, or use an instance of bytelengthqueuingstrategy or countqueuingstrategy for this object value. if no queuingstrategy is supplied, the default used is the same as a countqueuingstrategy with a high water mark of 1. return value an instance of the readablestream object. exceptions rangeerror the supplied type value is neither "bytes" nor undefined. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream. a cancel() fuction is also provided to stop the generation if readablestream.cancel() is called for any reason. when a button is pressed, the generation is stopped, ...
ReadableStream.cancel() - Web APIs
er side of the result in the match var contextbefore = 30; var contextafter = 30; var caseinsensitive = true; var url = 'https://html.spec.whatwg.org/'; console.log(`searching '${url}' for '${searchterm}'`); fetch(url).then(response => { console.log('received headers'); var decoder = new textdecoder(); var reader = response.body.getreader(); var tomatch = caseinsensitive ? ...
...esult) { if (result.done) { console.log('failed to find match'); return; } bytesreceived += result.value.length; console.log(`received ${bytesreceived} bytes of data so far`); buffer += decoder.decode(result.value, {stream: true}); // already found match & just context-gathering? if (matchfoundat === -1) { matchfoundat = (caseinsensitive ? ...
ReadableStream.tee() - Web APIs
you might do this for example in a serviceworker if you want to fetch a response from the server and stream it to the browser, but also stream it to the serviceworker cache. since a response body cannot be consumed more than once, you’d need two copies to do this. ...
...this. to cancel the stream you then need to cancel both resulting branches. teeing a stream will generally lock it for the duration, preventing other readers from locking it. syntax var teedstreams = readablestream.tee(); parameters none. return value an array containing two readablestream instances. exceptions typeerror the source stream is not a readablestream. examples in the following simple example, a previously-created stream is teed, then both resulting streams (contained in two members of a generated array) are passed to a function that reads the data out of the two streams and prints each stream's chunks sequentially to a different part of the ui. see simple tee example for the full code. function teestream() { const teedoff = stream.tee(); fetchstream(teedoff[0],...
ReadableStream - Web APIs
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. ...
ReadableStreamDefaultController - Web APIs
the readablestreamdefaultcontroller interface of the streams api represents a controller allowing control of a readablestream's state and internal queue. default controllers are for streams that are not byte streams. constructor none. readablestreamdefaultcontroller instances are created automatically during readablestream construction. properties readablestreamdefaultcontroller.desiredsize read only returns the desired size required to fill the stream's internal queue. methods readablestreamdefaultcontroller.close() closes the associated stream. readablestreamdefaultcontroller.enqueue() enqueues a given chunk in the associated stream. ...
...redsize read only returns the desired size required to fill the stream's internal queue. methods readablestreamdefaultcontroller.close() closes the associated stream. readablestreamdefaultcontroller.enqueue() enqueues a given chunk in the associated stream. readablestreamdefaultcontroller.error() causes any future interactions with the associated stream to error. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream. a cancel() function is also provided to stop the generation if readablestream.cancel() is called for any reason. note that a readablestreamdefaultcontroller object i...
Request.cache - Web APIs
Web › API › Request › cache
ache with the downloaded resource. only-if-cached — the browser looks for a matching request in its http cache. if there is a match, fresh or stale, it will be returned from the cache. if there is no match, the browser will respond with a 504 gateway timeout status. the "only-if-cached" mode can only be used if the request's mode is "same-origin". cached redirects will be followed if the request's redirect property is "follow" and the redirects do not violate the "same-origin" mode. example // download a resource with cache busting, to bypass the cache // completely. fetch("some.json", {cache: "no-store"}) .then(function(response) { /* consume the response */ }); // download a resource with cache busting, but update the http // cache with the downloaded resource. f...
... 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; this would be a function that takes a path and a // reference to the controller since it would need to change the value let controller = new abortcontroller(); fetch("some.json", {cache: "only-if-cached", mode: "same-origin", signal: controller.signal}) .catch(e => e instanceof typeerror && e.message === "failed to fetch" ? ({status: 504}) : // workaro...
Request.context - Web APIs
Web › API › Request › context
isions based on whether the url is for an image, or an embeddable object such as a <video>, iframe, etc. ...
...s, csp directives, and platform feature examples in the fetch spec request context section. syntax var mycontext = request.context; value a requestcontext value. ...
Request.credentials - Web APIs
send or receive cookies. same-origin: send user credentials (cookies, basic http auth, etc..) if the url is on the same origin as the calling script. this is the default value. include: always send user credentials (cookies, basic http auth, etc..), even for cross-origin calls. this is similar to xhr’s withcredentials flag, but with three available values instead of two. ...
...(cookies, basic http auth, etc..), even for cross-origin calls. this is similar to xhr’s withcredentials flag, but with three available values instead of two. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request credentials in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.credentials; // returns "same-origin" by default specifications specification status comment fetchthe definition of 'credentials' in that specification. living standard initial definition ...
Request.referrerPolicy - Web APIs
ad-only property of the request interface returns the referrer policy, which governs what referrer information, sent in the referer header, should be included with the request. syntax var myreferrerpolicy = request.referrerpolicy; value a domstring representing the request's referrerpolicy. for more information and possible values, see the referrer-policy http header page. ...
...rrerpolicy; value a domstring representing the request's referrerpolicy. for more information and possible values, see the referrer-policy http header page. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer policy in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrerpolicy; // returns "" by default specifications specification status comment fetchthe definition of 'referrerpolicy' in that specification. living standard initial definition ...
ResizeObserver() - Web APIs
at can be used to access the new dimensions of the element after each change. observer a reference to the resizeobserver itself, so it will definitely be accessible from inside the callback, should you need it. this could be used for example to automatically unobserve the observer when a certain condition is reached, but you can omit it if you don't need it. ...
...it. this could be used for example to automatically unobserve the observer when a certain condition is reached, but you can omit it if you don't need it. ...
ResizeObserver.observe() - Web APIs
the observe() method of the resizeobserver interface starts observing the specified element or svgelement. syntax resizeobserver.observe(target, options); parameters target a reference to an element or svgelement to be observed. options optional an options object allowing you to set options for the observation. currently this only has one possible option that can be set: box sets which box model the observer will observe changes to. possible values are content-box (the default), and border-box. ...
... a reference to an element or svgelement to be observed. options optional an options object allowing you to set options for the observation. currently this only has one possible option that can be set: box sets which box model the observer will observe changes to. possible values are content-box (the default), and border-box. return value void. exceptions none. ...
ResizeObserverEntry - Web APIs
properties resizeobserverentry.borderboxsize read only an object containing the new border box size of the observed element when the callback is run. resizeobserverentry.contentboxsize read only an object containing the new content box size of the observed element when the callback is run. resizeobserverentry.contentrect read only a domrectreadonly object containing the new size of the observed element when the callback is run. ...
...ay 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 sizing data it needs. if not, it uses the older contentrect property. const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentbox...
Resource Timing API - Web APIs
e or software constraints), the browser can represent a the value as a time in milliseconds accurate to a millisecond. resource loading timestamps an application can get timestamps for the various stages used to load a resource. the first property in the processing model is starttime which returns the timestamp immediately before the resource loading process begins. the fetchstart timestamps follows and redirect processing (if applicable) and preceeds dns lookup. the next stages are connectstart and connectend which are the timestamps immediately before and after connecting to the server, respectively. the last three timestamps are, in order: requeststart - the timestamp before the browser starts requesting the resource from the server; responsestart - the timestamp after the browser receiv...
...rowser 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, and resp...
Response.clone() - Web APIs
Web › API › Response › clone
value a response object. ...
...pg path. we then fetch this request using fetch(). when the fetch resolves successfully, we clone it, extract a blob from both responses using two body.blob calls, create object urls out of the blobs using url.createobjecturl, and display them in two separate <img> elements. ...
Response.type - Web APIs
Web › API › Response › type
cors: response was received from a valid cross-origin request. certain headers and the body may be accessed. error: network error. no useful information describing the error is available. the response’s status is 0, headers are empty and immutable. this is the type for a response obtained from response.error(). opaque: response for “no-cors” request to cross-origin resource. severely restricted. ...
...ct using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response type to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.type); // returns basic by default response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'type' in that specification. living standard initial defi...
SVGAElement - Web APIs
htmlhyperlinkelementutils. svgaelement.download see htmlanchorelement.download. svgaelement.href see htmlanchorelement.href. svgaelement.hreflang is a domstring that reflects the hreflang attribute, indicating the language of the linked resource. svgaelement.ping is a domstring that reflects the ping attribute, containing 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. svgaelement.referrerpolicy see htmlanchorelement.referrerpolicy. svgaelement.rel see htmlanchorelement.rel. svgaelement.rellist see htmlanchorelement.rellist. svgaelement.target read only it corresponds to the target attribute of the given element. svgaelement.text is a dom...
...ead only it corresponds to the target attribute of the given element. svgaelement.text is a domstring being a synonym for the node.textcontent property. svgaelement.type is a domstring that reflects the type attribute, indicating the mime type of the linked resource. methods this interface has no methods but inherits methods from its parent, svggraphicselement. example in the example below, the target attribute of the <a> element is set to _blank and when the link is clicked, it logs to notify whether the condition is met or not. var linkref = document.queryselector("a"); linkref.target = "_self"; linkref.onclick = function(){ if (linkref.target === "_blank") { console.log("blank!"); linkref.target = "_self"; } else { console.log("sorry! not _blank"); } } spec...
SVGAnimatedPathData - Web APIs
erface also inherits properties from its parent, svgpathelement. name type description animatednormalizedpathseglist svgpathseglist provides access to the current animated contents of the 'd' attribute in a form where all path data commands are expressed in terms of the following subset of svgpathseg types: svg_pathseg_moveto_abs (m), svg_pathseg_lineto_abs (l), svg_pathseg_curveto_cubic_abs (c) and svg_pathseg_closepath (z). animatedpathseglist svgpathseglist provides access to the current animated contents of the 'd' attribute in a form which matches one-for-one with svg's syntax. if the given attribute or property is...
...n attribute or property is being animated, contains the current animated value of the attribute or property, and both the object itself and its contents are read only. normalizedpathseglist svgpathseglist provides access to the base (i.e., static) contents of the 'd' attribute in a form where all path data commands are expressed in terms of the following subset of svgpathseg types: svg_pathseg_moveto_abs (m), svg_pathseg_lineto_abs (l), svg_pathseg_curveto_cubic_abs (c) and svg_pathseg_closepath (z). pathseglist svgpathseglist provides access to the base (i.e., static) contents of the 'd' attribute in a form which matches one-for-one with svg's syntax. thus, if the d attribute has an "absolute ...
SVGElement - Web APIs
all of the svg dom interfaces that correspond directly to elements in the svg language derive from the svgelement interface. ...
...s from: documentandelementeventhandlers, element, elementcssinlinestyle, globaleventhandlers, htmlorforeignelement, svgelementinstance events listen to these events using addeventlistener() or by assigning an event listener to the equivalent on... handler property defined on globaleventhandlers or windoweventhandlers. abort fired when page loading is stopped before an svg element has been allowed to load completely. also available via the onabort property. error fired when an svg element does not load properly or when an error occurs during script execution. also available via the onerror property. load fires on an svgelement when it is loaded in the browser. also available via the onload property. resize fired when an svg document is being resized. also available via the onre...
SVGSVGElement - Web APIs
<svg> elements, as well as methods to manipulate them. this interface contains also various miscellaneous commonly-used utility methods, such as matrix operations and the ability to control the time of redraw on visual rendering devices. ...
...nments that do not support interactivity (e.g., print media), then redraw shall not be suspended. calls to suspendredraw() and unsuspendredraw() should, but need not be, made in balanced pairs. to suspend redraw actions as a collection of svg dom changes occur, precede the changes to the svg dom with a method call similar to: const suspendhandleid = suspendredraw(maxwaitmilliseconds) and follow the changes with a method call similar to: unsuspendredraw(suspendhandleid) note that multiple suspendredraw() calls can be used at once, and that each such method call is treated independently of the other suspendredraw() method calls. svgsvgelement.unsuspendredraw() cancels a specified suspendredraw() by providing a unique suspend handle id that was returned by a previous suspendredra...
SVGScriptElement - Web APIs
the svgscriptelement interface corresponds to the svg <script> element. ...
...nt-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgscriptelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties svgscriptelement.type read only a domstring corresponding to the type attribute of the given <script> element. a domexception is raised with the code no_modification_allowed_err on an attempt to change the value of a read only attribut. svgscriptelement.crossorigin read only a domstring corresponding to the crossorigin attribute of the given <script> element. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement. specifications specification status comment scalable v...
Screen.availHeight - Web APIs
er 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 following is used. let palettewindow = window.open("panels.html", "pa...
...anels", "left=0, top=0, width=200"); the panels window's html, in panels.html, has javascript code of its own, which is executed as soon as the window is created. it doesn't even need to wait for any particular event (or any event at all). that code handles resizing the window based on the available space: window.outerheight = window.screen.availheight; the result is something similar to the below. note the panels window filling all available vertical space at the left of the screen. on a windows system, this would function similarly, by opening the window and sizing it vertically so it uses all available vertical space, leaving room for the taskbar and any other interface elements that reserve space. specifications specification status comment css object m...
ScrollToOptions - Web APIs
the scrolltooptions dictionary of the cssom view spec contains properties specifying where an element should be scrolled to, and whether the scrolling should be smooth. a scrolltooptions dictionary can be provided as a parameter for the following methods: window.scroll() window.scrollby() window.scrollto() element.scroll() element.scrollby() element.scrollto() properties scrolltooptions.top specifies the number of pixels along the y axis to scroll the window or element. scrolltooptions.left specifies the number of pixels along the x axis to scroll the window or element. scrolltooptions.behavior specifies whether the scrolling should animate smoothly, or happen instantly in a single jump. this is actually defined on the scrolloptions dictionary, which is implemented by scro...
...tooptions.left specifies the number of pixels along the x axis to scroll the window or element. scrolltooptions.behavior specifies whether the scrolling should animate smoothly, or happen instantly in a single jump. this is actually defined on the scrolloptions dictionary, which is implemented by scrolltooptions. examples in our scrolltooptions example (see it live) we include a form that allows the user to enter three values — two numbers representing the left and top properties (i.e. the positions to scroll to along the x and y axes), and a checkbox indicating whether they want smooth scrolling enabled or not. when the form is submitted, an event handler is run that puts the entered values into a scrolltooptions dictionary, and then invokes the window.scrollto() method, passing the...
Selection.modify() - Web APIs
Web › API › Selection › modify
ection or cursor position. you can move by "character", "word", "sentence", "line", "paragraph", "lineboundary", "sentenceboundary", "paragraphboundary", or "documentboundary". note: gecko does not implement "sentence", "paragraph", "sentenceboundary", "paragraphboundary", or "documentboundary". webkit and blink do. note: starting in gecko 5.0, the "word" granularity no longer includes the following space, regardless of the default platform behavior. this makes the behavior more consistent, as well as making it work the same way webkit used to work, but unfortunately they have recently changed their behavior. example this example demonstrates the various granularity options for modifying a selection. click somewhere inside the example (optionally selecting some text), and then click th...
...ell as making it work the same way webkit used to work, but unfortunately they have recently changed their behavior. example this example demonstrates the various granularity options for modifying 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. nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.</p> <label for="granularity">granularity:</label> <select id="granularity"> <option value="character">ch...
ServiceWorkerMessageEvent - Web APIs
important: in modern browsers, this interface has been deprecated. service worker messages will now use the messageevent interface, for consistency with other web messaging features. the serviceworkermessageevent interface of the serviceworker api contains information about an event sent to a serviceworkercontainer target. this extends the default message event to allow setting a serviceworker object as the source of a message. the event object is accessed via the handler function of a message event, when fired by a message received from a service worker. this interface inherits from the event interface. constructor serviceworkermessageevent.serviceworkermessageevent() creates a new serviceworkermessageevent object instance. properties inherits properties from its parent, eve...
...rviceworkermessageevent.lasteventid read only represents, in server-sent events, the last event id of the event source. serviceworkermessageevent.source read only returns a reference to the service worker that sent the message. serviceworkermessageevent.ports read only returns an array of messageport objects. methods inherits methods from its parent, event. examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent. navigator.serviceworker.ready.then(function(reg) { ... // set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = ...
ServiceWorkerRegistration.showNotification() - Web APIs
the shownotification() method of the serviceworkerregistration interface creates a notification on an active service worker. note: this feature is available in web workers. syntax ​serviceworkerregistration.shownotification(title, [options]); parameters title the title that must be shown within the notification options optional an object that allows configuring the notification. it can have the following properties: actions: an array of actions to display in the notification. the members of the array should be an object literal. it may contain the following values: action: a domstring identifying a user action to be displayed on the notification. title: a domstring containing action text to be shown to the user. icon: a usvstring containing the url of an ico...
...ue 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 script if necessary. timestamp: a domtimestamp representing the time when the notification was created. it can be used to indicate the time at which a notification is actual. for example, this could be in the past when a notification is used for a message that couldn’t immediately be delivered because the device was offline, or in the...
SourceBuffer - Web APIs
the sourcebuffer interface represents a chunk of media to be passed into an htmlmediaelement and played, via a mediasource object. this can be made up of one or several media segments. ...
...ls to appendbuffer() will expect the new data to conform to. sourcebuffer.remove() removes media segments within a specific time range from the sourcebuffer. sourcebuffer.removeasync() starts the process of asynchronously removing media segments in the specified range from the sourcebuffer. returns a promise which is fulfilled once all matching segments have been removed. examples the following simple example loads a video chunk by chunk as fast as possible, playing it as soon as it can. this example was written by nick desaulniers and can be viewed live here (you can also download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep c...
SourceBufferList - Web APIs
the sourcebuffers appended to a particular mediasource can be retrieved using the mediasource.sourcebuffers property. the individual source buffers can be accessed using array operator (i.e. []) or functions such as foreach() for example. ...
...length read only returns the number of sourcebuffer objects in the list. event handlers sourcebufferlist.onaddsourcebuffer the event handler for the addsourcebuffer event. sourcebufferlist.onremovesourcebuffer the event handler for the removesourcebuffer event. methods inherits methods from its parent interface, eventtarget. sourcebufferlist: indexed property getter this getter allows the sourcebuffer objects in the list to be accessed with an array operator (i.e. [].) examples tbd. specifications specification status comment media source extensionsthe definition of 'sourcebufferlist' in that specification. recommendation initial definition. ...
SpeechGrammarList.item() - Web APIs
the item getter of the speechgrammarlist interface is a standard getter — it allows individual speechgrammar objects to be retrieved from the speechgrammarlist using array syntax. syntax var myfirstgrammar = speechgrammarlistinstance[0]; returns a speechgrammar object. ...
... specifications specification status comment web speech apithe de...
SpeechGrammarList - Web APIs
e. grammar is defined using jspeech grammar format (jsgf.) other formats may also be supported in the future. constructor speechgrammarlist.speechgrammarlist() creates a new speechgrammarlist object. properties speechgrammarlist.length read only returns the number of speechgrammar objects contained in the speechgrammarlist. methods speechgrammarlist.item() standard getter — allows individual speechgrammar objects to be retrieved from the speechgrammarlist using array syntax. speechgrammarlist.addfromuri() takes a grammar present at a specific uri and adds it to the speechgrammarlist as a new speechgrammar object. speechgrammarlist.addfromstring() takes a grammar present in a specific domstring within the code base (e.g. stored in a variable) and adds it to the speechg...
... draft ...
SpeechRecognitionError.error - Web APIs
error; value a domstring naming the type of error. 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. ...
... naming the type of error. 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. not-allowed the user agent disallowed any speech input from occurring for reasons of security, privacy or user preference. service-not-allowed the user agent disallowed the requested speech recognition service, either because the user agent doesn't support it or because of reasons of security, privacy or user preference. in this case it would allow another more suitable speech recognition service to be used instead. bad-grammar ...
SpeechRecognitionErrorEvent.error - Web APIs
error; value a domstring naming the type of error. 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. ...
... naming the type of error. 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. not-allowed the user agent disallowed any speech input from occurring for reasons of security, privacy or user preference. service-not-allowed the user agent disallowed the requested speech recognition service, either because the user agent doesn't support it or because of reasons of security, privacy or user preference. in this case it would allow another more suitable speech recognition service to be used instead. bad-grammar ...
SpeechRecognitionEvent.resultIndex - Web APIs
syntax var myresultindex = event.resultindex; value a number. ...
... syntax var myresultindex = event.resultindex; value a number. ...
StaticRange - Web APIs
ge of content in the dom whose contents don't update to reflect changes which occur within the dom tree. it offers the same set of properties and methods as abstractrange. abstractrange and staticrange are not available from web workers. ...
...12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">staticrange</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor staticrange() creates a new staticrange object given the staticrangeinit dictionary specifying the default values for its properties. properties the properties below are inherited from its parent interface, abstractrange. staticrange.collapsed read only returns a boolean value which is true if the range's start and end positions are the same, resulting in a range of length 0. staticrange.endcontainer read only returns the dom node which contains the ending point of the range. the offset into the node at which the end position is located is indicated b...
Storage.key() - Web APIs
Web › API › Storage › key
nth key in a given storage object. the order of keys is user-agent defined, so you should not rely on it. syntax var akeyname = storage.key(index); parameters index an integer representing the number of the key you want to get the name of. this is a zero-based index. return value a domstring containing the name of the key. if the index does not exist, null is returned. ...
...resenting the number of the key you want to get the name of. this is a zero-based index. return value a domstring containing the name of the key. if the index does not exist, null is returned. examples the following function iterates over the local storage keys: function foreachkey(callback) { for (var i = 0; i < localstorage.length; i++) { callback(localstorage.key(i)); } } the following function iterates over the local storage keys and gets the value set for each key: for(var i =0; i < localstorage.length; i++){ console.log(localstorage.getitem(localstorage.key(i))); } note: for a real world example, see our web storage demo. specifications specification status comment html living standardthe definition of 'storage.key' in that specification. ...
Using the Storage Access API - Web APIs
the storage access api should be used by embedded cross-origin documents to verify whether they have access to their first-party storage and, if not, to request access. we’ll briefly look at a common storage access scenario. usage notes the storage access api is designed to allow embedded content to request access to storage that would otherwise be blocked when a user’s browser is set to block all third-party cookies. since embedded content won’t know which storage policy is in use by the user, it’s best to always check whether the embedded frame has storage access before attempting to read or write from storage. this is particularly true for document.cookie access, as browsers will often return an empty cookie jar when third-party cookies are blocked. accessing a user's cookies...
...ccess, as browsers will often return an empty cookie jar when third-party cookies are blocked. accessing a user's cookies in an embedded cross-origin iframe in this example we show how an embedded cross-origin <iframe> can access a user’s cookies under a storage access policy that blocks third-party cookies. first of all, if the <iframe> is sandboxed, the embedding website needs to add the allow-storage-access-by-user-activation sandbox token to allow storage access requests to be successful, along with allow-scripts and allow-same-origin to allow it to call the api, and execute in an origin that can have cookies: <iframe sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"> ... </iframe> now on to the code executed insid...
SubtleCrypto.deriveBits() - Web APIs
takes as its arguments the base key, the derivation algorithm to use, and the length of the bit string to derive. it returns a promise which will be fulfilled with an arraybuffer containing the derived bits. this method is very similar to subtlecrypto.derivekey(), except that derivekey() returns a cryptokey object rather than an arraybuffer. essentially derivekey() is composed of derivebits() followed by importkey(). this function supports the same derivation algorithms as derivekey(): ecdh, hkdf, and pbkdf2. see supported algorithms for some more detail on these algorithms. syntax const result = crypto.subtle.derivebits( algorithm, basekey, length ); parameters algorithm is an object defining the derivation algorithm to use. to use ecdh, pass an ecdhkeyderiveparam...
...otherwise it will be the initial key material for the derivation function: for example, for pbkdf2 it might be a password, imported as a cryptokey using subtlecrypto.importkey(). length is a number representing the number of bits to derive. return value result is a promise that fulfills with an arraybuffer containing the derived bits. exceptions the promise is rejected when one of the following exceptions are encountered: invalidaccesserror raised when the base key is not a key for the requested derivation algorithm or if the cryptokey.usages value of that key doesn't contain derivekey. notsupported raised when trying to use an algorithm that is either unknown or isn't suitable for derivation, or if the algorithm requested for the derived key doesn't define a key length. supp...
SubtleCrypto.exportKey() - Web APIs
formats: see supported formats in the subtlecrypto.importkey() page for details. keys are not exported in an encrypted format: to encrypt keys when exporting them use the subtlecrypto.wrapkey() api instead. syntax const result = crypto.subtle.exportkey(format, key); parameters format is a string value describing the data format in which the key should be exported. it can be one of the following: raw: raw format. pkcs8: pkcs #8 format. spki: subjectpublickeyinfo format. jwk: json web key format. key is the cryptokey to export. return value result is a promise. if format was jwk, then the promise fulfills with a json object containing the key. otherwise the promise fulfills with an arraybuffer containing the key. exceptions the promise is r...
.... pkcs8: pkcs #8 format. spki: subjectpublickeyinfo format. jwk: json web key format. key is the cryptokey to export. return value result is a promise. if format was jwk, then the promise fulfills with a json object containing the key. otherwise the promise fulfills with an arraybuffer containing the key. exceptions the promise is rejected when one of the following exceptions is encountered: invalidaccesserror raised when trying to export a non-extractable key. notsupported raised when trying to export in an unknown format. typeerror raised when trying to use an invalid format. examples note: you can try the working examples out on github. raw export this example exports an aes key as an arraybuffer containing the bytes for the key. see th...
SubtleCrypto.importKey() - Web APIs
ortable format and gives you a cryptokey object that you can use in the web crypto api. the function accepts several import formats: see supported formats for details. syntax const result = crypto.subtle.importkey( format, keydata, algorithm, extractable, usages ); parameters format is a string describing the data format of the key to import. it can be one of the following: raw: raw format. pkcs8: pkcs #8 format. spki: subjectpublickeyinfo format. jwk: json web key format. keydata is an arraybuffer, a typedarray, a dataview, or a jsonwebkey object containing the key in the given format. algorithm is a dictionary object defining the type of key to import and providing extra algorithm-specific parameters. for rsassa-pkcs1-v1_5, rsa-pss...
...ay be used to verify signatures. derivekey: the key may be used in deriving a new key. derivebits: the key may be used in deriving bits. wrapkey: the key may be used to wrap a key. unwrapkey: the key may be used to unwrap a key. return value result is a promise that fulfills with the imported key as a cryptokey object. exceptions the promise is rejected when one of the following exceptions is encountered: syntaxerror raised when keyusages is empty but the unwrapped key is of type secret or private. typeerror raised when trying to use an invalid format or if the keydata is not suited for that format. supported formats this api supports four different key import/export formats: raw, pkcs #8, subjectpublickeyinfo, and json web key. raw you can use this format ...
SubtleCrypto.unwrapKey() - Web APIs
pkey() is subtlecrypto.wrapkey(): while unwrapkey is composed of decrypt + import, wrapkey is composed of encrypt + export. syntax const result = crypto.subtle.unwrapkey( format, wrappedkey, unwrappingkey, unwrapalgo, unwrappedkeyalgo, extractable, keyusages ); parameters format is a string describing the data format of the key to unwrap. it can be one of the following: raw: raw format. pkcs8: pkcs #8 format. spki: subjectpublickeyinfo format. jwk: json web key format. wrappedkey is an arraybuffer containing the wrapped key in the given format. unwrappingkey is the cryptokey to use to decrypt the wrapped key. the key must have the unwrapkey usage set. unwrapalgo is an object specifying the algorithm to be used to encrypt the exported ...
...ay be used to verify signatures. derivekey: the key may be used in deriving a new key. derivebits: the key may be used in deriving bits. wrapkey: the key may be used to wrap a key. unwrapkey: the key may be used to unwrap a key return value result is a promise that fulfills with the unwrapped key as a cryptokey object. exceptions the promise is rejected when one of the following exceptions is encountered: invalidaccesserror raised when the unwrapping key is not a key for the requested unwrap algorithm or if the cryptokey.usages value of that key doesn't contain unwrap. notsupported raised when trying to use an algorithm that is either unknown or isn't suitable for encryption or wrapping. syntaxerror raised when keyusages is empty but the unwrapped key is of ty...
SubtleCrypto.wrapKey() - Web APIs
ing key". the inverse of wrapkey() is subtlecrypto.unwrapkey(): while wrapkey is composed of export + encrypt, unwrapkey is composed of import + decrypt. syntax const result = crypto.subtle.wrapkey( format, key, wrappingkey, wrapalgo ); parameters format is a string describing the data format in which the key will be exported before it is encrypted. it can be one of the following: raw: raw format. pkcs8: pkcs #8 format. spki: subjectpublickeyinfo format. jwk: json web key format. key is the cryptokey to wrap. wrappingkey is the cryptokey used to encrypt the exported key. the key must have the wrapkey usage set. wrapalgo is an object specifying the algorithm to be used to encrypt the exported key, and any required extra parameters: to use r...
...se aes-ctr, pass an aesctrparams object. to use aes-cbc, pass an aescbcparams object. to use aes-gcm, pass an aesgcmparams object. to use aes-kw, pass the string "aes-kw", or an object of the form { "name": "aes-kw }. return value result is a promise that fulfills with an arraybuffer containing the encrypted exported key. exceptions the promise is rejected when one of the following exceptions is encountered: invalidaccesserror raised when the wrapping key is not a key for the requested wrap algorithm. notsupported raised when trying to use an algorithm that is either unknown or isn't suitable for encryption or wrapping. typeerror raised when trying to use an invalid format. supported algorithms all algorithms that are usable for encryption are also usable for ...
Text.wholeText - Web APIs
Web › API › Text › wholeText
the text.wholetext read-only property returns the full text of all text nodes logically adjacent to the node. the text is concatenated in document order. this allows to specify any text node and obtain all adjacent text as a single string. ...
... the text.wholetext read-only property returns the full text of all text nodes logically adjacent to the node. the text is concatenated in document order. this allows to specify any text node and obtain all adjacent text as a single string. ...
Text - Web APIs
Web › API › Text
ocuments have a single text node for each block of text. over time, more text nodes may be created as the document's content changes. the node.normalize() method merges adjacent text objects back into a single node for each block of text. ...
... boolean flag indicating whether or not the text node contains only whitespace. text.wholetext read only returns a domstring containing the text of all text nodes logically adjacent to this node, concatenated in document order. text.assignedslot read only returns the htmlslotelement object associated with the element. properties included from slotable the text interface includes the following property, defined on the slotable mixin. slotable.assignedslot read only returns a htmlslotelement representing the <slot> the node is inserted in. methods inherits methods from its parent, characterdata. text.replacewholetext replaces the text of the current node and all logically adjacent nodes with the specified text. text.splittext breaks the node into two nodes at a ...
TextEncoder - Web APIs
.prototype.encode() takes a usvstring as input, and returns a uint8array containing utf-8 encoded text. textencoder.prototype.encodeinto() takes a usvstring to encode and a destination uint8array to put resulting utf-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. this is potentially more performant than the older encode() method. ...
...these sequences are not already precomputed because they serve to aesthetically illustrate how the polyfill works. ...
TextMetrics - Web APIs
beticbaseline. see also the canvasrenderingcontext2d.textbaseline property. ...
...vas'); const ctx = canvas.getcontext('2d'); const baselinesabovealphabetic = ['fontboundingboxascent', 'actualboundingboxascent', 'emheightascent', 'hangingbaseline']; const baselinesbelowalphabetic = ['ideographicbaseline', 'emheightdescent', 'actualboundingboxdescent', 'fontboundingboxdescent']; const baselines = [...baselinesabovealphabetic, ...baselinesbelowalphabetic]; ctx.font = '25px serif'; ctx.strokestyle = 'red'; baselines.foreach(function (baseline, index) { let text = 'abcdefghijklmnop (' + baseline + ')'; let textmetrics = ctx.measuretext(text); let y = 50 + index * 50; ctx.beginpath(); ctx.filltext(text, 0, y); let liney = y - math.abs(textmetrics[baseline]); if (baselinesbelowalphabetic.includes(baseline)) { liney = y + ...
Touch() - Web APIs
Web › API › Touch › Touch
"target", required, of type eventtarget, the item at which the touch point started when it was first placed on the surface. "clientx", optional and defaulting to 0, of type double, that is the horizontal position of the touch on the client window of user's screen, excluding any scroll offset. ...
...float, that is the angle (in degrees) that the ellipse described by radiusx and radiusy is rotated clockwise about its center; 0 if no value is known. the value must be greater than or equal to 0 and less than 90. if the ellipse described by radiusx and radiusy is circular, then rotationangle has no effect. the user agent may use 0 as the value in this case, or it may use any other value in the allowed range. (for example, the user agent may use the rotationangle value from the previous touch event, to avoid sudden changes.). ​"force", optional and defaulting to 0, of type float, that is the relative value of pressure applied, in the range 0 to 1, where 0 is no pressure, and 1 is the highest level of pressure the touch device is capable of sensing; 0 if no value is known. in environments ...
TouchEvent.changedTouches - Web APIs
for the touchmove event, it is a list of the touch points that have changed since the last event. for the touchend event, it is a list of the touch points that have been removed from the surface (that is, the set of touch points corresponding to fingers no longer touching the surface). ...
...ouchevent.changedtouches; return value changes a touchlist whose touch objects include all the touch points that contributed to this touch event. example this example illustrates the touchevent object's touchevent.changedtouches property. the touchevent.changedtouches property is a touchlist object that contains one touch object for each touch point which contributed to the event. in following code snippet, the touchmove event handler iterates through the changedtouches list and prints the identifier of each touch point that changed since the last event. someelement.addeventlistener('touchmove', function(e) { // iterate through the list of touch points that changed // since the last event and print each touch point's identifier. for (var i=0; i < e.changedtouches.length; i...
TouchEvent - Web APIs
d removal of contact points, and so forth. touches are represented by the touch object; each touch is described by a position, size and shape, amount of pressure, and target element. lists of touches are represented by touchlist objects. ...
... read only change in rotation (in degrees) since the event's beginning. positive values indicate clockwise rotation; negative values indicate anticlockwise rotation. initial value: 0.0 touchevent.scale read only distance between two digits since the 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...
Supporting both TouchEvent and MouseEvent - Web APIs
ith mouse input. consequently, even if a browser supports touch, the browser must still emulate mouse events so content that assumes mouse-only input will work as is without direct modification. ideally, a touch-based application does not need to explicitly address mouse input. however, because the browser must emulate mouse events, there may be some interaction issues that need to be handled. below are some details about the interaction and the ramifications for application developers. event firing the touch events standard defines a few browser requirements regarding touch and mouse interaction (see the interaction with mouse events and click section for details), noting the browser may fire both touch events and mouse events in response to the same user input. this section describes the...
...and no additional mouse events will be dispatched. here is a code snippet of the touchmove event handler calling preventdefault(). ...
UIEvent.cancelBubble - Web APIs
use event.stoppropagation() instead of this non-standard method. syntax event.cancelbubble = bool; var bool = event.cancelbubble; specifications this property is not part of any specification. ...
... use event.stoppropagation() instead of this non-standard method. syntax event.cancelbubble = bool; var bool = event.cancelbubble; specifications this property is not part of any specification. ...
ValidityState - Web APIs
nable to convert. customerror read only a boolean indicating whether the element's custom validity message has been set to a non-empty string by calling the element's setcustomvalidity() method. patternmismatch read only a boolean that is true if the value does not match the specified pattern, and false if it does match. if true, the element matches the :invalid css pseudo-class. ...
...if true, the element matches the :invalid and :out-of-range css pseudo-classes. ...
Visual Viewport API - Web APIs
ual viewport lets web developers solve this by positioning elements relative to what's shown on screen. to access a window's visual viewport, you can obtain a visualviewport object from the window.visualviewport property. the object includes a set of properties describing the viewport. it also adds two events, onresize and onscroll, that fire whenever the visual viewport changes. these events allow you to position elements relative to the visual viewport that would normally be anchored to the layout viewport. accessing the api window.visualviewport read only a read-only reference to the window's visualviewport object. if this property doesn't exist, the api is unsupported. interfaces visualviewport represents the visual viewport for a given window. a window's visualviewport obj...
...wport object. if this property doesn't exist, the api is unsupported. interfaces visualviewport represents the visual viewport for a given window. a window's visualviewport object provides information about the viewport's position and size, and receives the resize and event:visualviewport:scroll events you can onitor to know when chances occur to the window's viewport. example the code below is based on the sample the specification, though it adds a few things that make it function better. it shows a function called viewporthandler(). when called it queries the offsetleft and height properties for values it uses in a css translate() method. you invoke this function by passing it to both event calls. one thing that may not be clear in this example is the use of the pendingupdate flag...
WakeLock - Web APIs
Web › API › WakeLock
the wakelock interface of the screen wake lock api prevents device screens from dimming or locking when an application needs to keep running. 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. ...
... unknown initial definition. ...
WebGLQuery - Web APIs
the webglquery interface is part of the webgl 2 api and provides ways to asynchronously query for information. by default, occlusion queries and primitive queries are available. another kind of queries are disjoint timer queries, which allow you to measure performance and profiling of your gpu. disjoint timer queries are available with the ext_disjoint_timer_query extension only. ...
...rt of the webgl 2 api and provides ways to asynchronously query for information. by default, occlusion queries and primitive queries are available. another kind of queries are disjoint timer queries, which allow you to measure performance and profiling of your gpu. disjoint timer queries are available with the ext_disjoint_timer_query extension only. ...
WebGLRenderingContext.blendEquationSeparate() - Web APIs
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, the following values are available additionally: gl.min: minimum of source and destination, gl.max: maximum of source and destination. modealpha a glenum specifying how the alpha component (transparency) 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_sub...
... 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, the following values are available additionally: gl.min: minimum of source and destination, gl.max: maximum of source and destination. return value none. exceptions if mode is not one of the three possible values, a gl.invalid_enum error is thrown. examples to set the blend equations, use: gl.blendequationseparate(gl.func_add, gl.func_subtract); to get the current blend equa...
WebGLRenderingContext.blendFunc() - Web APIs
the webglrenderingcontext.blendfunc() method of the webgl api defines which function is used for blending pixel arithmetic. syntax void gl.blendfunc(sfactor, dfactor); parameters sfactor a glenum specifying a multiplier for the source blending factors. the default value is gl.one. for possible values, see below. dfactor a glenum specifying a multiplier for the destination blending factors. the default value is gl.zero. for possible values, see below. ...
... the formula for the blending color can be described like this: color(rgba) = (sourcecolor * sfactor) + (destinationcolor * dfactor). the rbga values are between 0 and 1. ...
WebGLRenderingContext.bufferSubData() - Web APIs
fersubdata(target, dstbyteoffset, arraybufferview srcdata, srcoffset, length); parameters target a glenum specifying the binding point (target). possible values: gl.array_buffer: buffer containing vertex attributes, such as vertex coordinates, texture coordinate data, or vertex color data. gl.element_array_buffer: buffer used for element indices. when using a webgl 2 context, the following values are available additionally: gl.copy_read_buffer: buffer for copying from one buffer object to another. gl.copy_write_buffer: buffer for copying from one buffer object to another. gl.transform_feedback_buffer: buffer for transform feedback operations. gl.uniform_buffer: buffer used for storing uniform blocks. gl.pixel_pack_buffer: buffer used for pixel transfer op...
...ray types that will be copied into the data store. srcoffset a gluint specifying the element index offset where to start reading the buffer. length optional a gluint defaulting to 0. return value none. exceptions a gl.invalid_value error is thrown if the data would be written past the end of the buffer or if data is null. a gl.invalid_enum error is thrown if target is not one of the allowed enums. examples using buffersubdata var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, 1024, gl.static_draw); gl.buffersubdata(gl.array_buffer, 512, data); specifications specification status comment webgl 1.0the definition of 'b...
WebGLRenderingContext.framebufferTexture2D() - Web APIs
method of the webgl api attaches a texture to a webglframebuffer. syntax void gl.framebuffertexture2d(target, attachment, textarget, texture, level); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. attachment a glenum specifying the attachment point for the texture. possible values: gl.color_attachment0: attaches the t...
... attachment a glenum specifying the attachment point for the texture. possible values: gl.color_attachment0: attaches the texture to the framebuffer's color buffer. gl.depth_attachment: attaches the texture to the framebuffer's depth buffer. gl.stencil_attachment: attaches the texture to the framebuffer's stencil buffer. when using a webgl 2 context, the following values are available additionally: gl.depth_stencil_attachment: depth and stencil buffer. gl.color_attachment1 gl.color_attachment2 gl.color_attachment3 gl.color_attachment4 gl.color_attachment5 gl.color_attachment6 gl.color_attachment7 gl.color_attachment8 gl.color_attachment9 gl.color_attachment10 gl.color_attachment11 gl.col...
WebGLRenderingContext.generateMipmap() - Web APIs
the webglrenderingcontext.generatemipmap() method of the webgl api generates a set of mipmaps for a webgltexture object. mipmaps are used to create distance with objects. a higher-resolution mipmap is used for objects that are closer, and a lower-resolution mipmap is used for objects that are farther away. it starts with the resolution of the texture image and halves the resolution until a 1x1 dimension texture image is created. ...
...ture image and halves the resolution until a 1x1 dimension texture image is created. syntax void gl.generatemipmap(target); parameters target a glenum specifying the binding point (target) of the active texture whose mipmaps will be generated. possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map: a cube-mapped texture. when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture. gl.texture_2d_array: a two-dimensional array texture. return value none. examples gl.generatemipmap(gl.texture_2d); specifications specification status comment webgl 1.0the definition of 'generatemipmap' in that specification. recommendation initial defini...
WebGLRenderingContext.getActiveUniform() - Web APIs
rogram specifying the webgl shader program from which to obtain the uniform variable's information. index a gluint specifying the index of the uniform attribute to get. this value is an index 0 to n - 1 as returned by gl.getprogramparameter(program, gl.active_uniforms). return value a webglactiveinfo object describing the uniform. ...
...urn value a webglactiveinfo object describing the uniform. ...
WebGLRenderingContext.getBufferParameter() - Web APIs
information about the buffer. syntax any gl.getbufferparameter(target, pname); parameters target a glenum specifying the target buffer object. possible values: gl.array_buffer: buffer containing vertex attributes, such as vertex coordinates, texture coordinate data, or vertex color data. gl.element_array_buffer: buffer used for element indices. when using a webgl 2 context, the following values are available additionally: gl.copy_read_buffer: buffer for copying from one buffer object to another. gl.copy_write_buffer: buffer for copying from one buffer object to another. gl.transform_feedback_buffer: buffer for transform feedback operations. gl.uniform_buffer: buffer used for storing uniform blocks. gl.pixel_pack_buffer: buffer used for pixel transfer op...
...fer used for pixel transfer operations. pname a glenum specifying information to query. possible values: gl.buffer_size: returns a glint indicating the size of the buffer in bytes. gl.buffer_usage: returns a glenum indicating the usage pattern of the buffer. this is either: gl.static_draw, gl.dynamic_draw, gl.stream_draw. when using a webgl 2 context, the following values are available additionally: gl.static_read, gl.dynamic_read, gl.stream_read, gl.static_copy, gl.dynamic_copy, gl.stream_copy. return value depends on the requested information (as specified with pname). either a glint or a glenum. examples gl.getbufferparameter(gl.array_buffer, gl.buffer_size); specifications ...
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
ext.getshaderprecisionformat() method of the webgl api returns a new webglshaderprecisionformat object describing the range and precision for the specified shader numeric format. syntax webglshaderprecisionformat gl.getshaderprecisionformat(shadertype, precisiontype); parameters shadertype either a gl.fragment_shader or a gl.vertex_shader. precisiontype a precision type value. ...
...ebgl api returns a new webglshaderprecisionformat object describing the range and precision for the specified shader numeric format. syntax webglshaderprecisionformat gl.getshaderprecisionformat(shadertype, precisiontype); parameters shadertype either a gl.fragment_shader or a gl.vertex_shader. precisiontype a precision type value. either gl.low_float, gl.medium_float, gl.high_float, gl.low_int, gl.medium_int, or gl.high_int. return value a webglshaderprecisionformat object or null, if an error occurs. exceptions gl.invalid_enum if the shader or precision 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 = docum...
WebGLRenderingContext.getUniformLocation() - Web APIs
itespace in it, and you can't use this function to get the location of any uniforms starting with the reserved string "gl_", since those are internal to the webgl layer. the possible values correspond to the uniform names returned by getactiveuniform; see that function for specifics on how declared uniforms map to uniform location names. additionally, for uniforms declared as arrays, the following names are also valid: the uniform name without the [0] suffix. e.g. the location returned for arrayuniform is equivalent to the one for arrayuniform[0]. the uniform name indexed with an integer. e.g. the location returned for arrayuniform[2] would point directly to the third entry of the arrayuniform uniform. return value a webgluniformlocation value indicating the location of ...
...tead. the webgluniformlocation is an opaque value used to uniquely identify the location in the gpu's memory at which the uniform variable is located. with this value in hand, you can call other webgl methods to access the value of the uniform variable. the webgluniformlocation type is compatible with the glint type when specifying the index or location of a uniform attribute. errors the following errors may occur; to check for errors after getuniformlocation() returns, call geterror(). gl_invalid_value the program parameter is not a value or object generated by webgl. gl_invalid_operation the program parameter doesn't correspond to a glsl program generated by webgl, or the specified program hasn't been linked successfully. example in this example, taken from the animatescene()...
WebGLRenderingContext.hint() - Web APIs
e controlled. possible values: gl.generate_mipmap_hint: quality of filtering when generating mipmap images with webglrenderingcontext.generatemipmap(). when using the oes_standard_derivatives extension: ext.fragment_shader_derivative_hint_oes: accuracy of the derivative calculation for the glsl built-in functions: dfdx, dfdy, and fwidth. when using a webgl 2 context, the following values are available additionally: gl.fragment_shader_derivative_hint: same as ext.fragment_shader_derivative_hint_oes mode sets the behavior. the default value is gl.dont_care. the possible values are: gl.fastest: the most efficient behavior should be used. gl.nicest: the most correct or the highest quality option should be used. gl.dont_care: there is no preferen...
...derivative_hint: same as ext.fragment_shader_derivative_hint_oes mode sets the behavior. the default value is gl.dont_care. the possible values are: gl.fastest: the most efficient behavior should be used. gl.nicest: the most correct or the highest quality option should be used. gl.dont_care: there is no preference for this behavior. return value none. examples the following example hints that the quality of filtering when generating mipmap images should be most efficient instead of best quality. gl.hint(gl.generate_mipmap_hint, gl.fastest); specifications specification status comment webgl 1.0the definition of 'hint' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glhint' in that...
WebGLRenderingContext.lineWidth() - Web APIs
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. ...
...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. ...
WebGLRenderingContext.pixelStorei() - Web APIs
the webglrenderingcontext.pixelstorei() method of the webgl api specifies the pixel storage modes. syntax void gl.pixelstorei(pname, param); parameters pname a glenum specifying which parameter to set. see below for possible values. param a glint specifying a value to set the pname parameter to. see below for possible values. return value none. pixel storage parameters parameter name (for pname) description type default value allowed values (for param) specified in gl.pack_alignment packing of pixel data into memory glint 4 1, 2, 4, 8 opengl es 2.0 gl.unpack_alignment unpacking of pixel data from memory. glint 4 1, 2, 4, 8 opengl es 2.0 gl.unpack_flip_y_webgl flips the source data along its...
... webgl gl.unpack_premultiply_alpha_webgl multiplies the alpha channel into the other color channels glboolean false true, false webgl gl.unpack_colorspace_conversion_webgl default color space conversion or no color space conversion. glenum gl.browser_default_webgl gl.browser_default_webgl, gl.none webgl when using a webgl 2 context, the following values are available additionally: constant description type default value allowed values (for param) specified in gl.pack_row_length number of pixels in a row. glint 0 0 to infinity opengl es 3.0 gl.pack_skip_pixels number of pixel locations skipped before the first pixel is written into memory. glint 0 0 to infinity ...
WebGLRenderingContext.renderbufferStorage() - Web APIs
at a glenum specifying the internal format of the renderbuffer. possible values: gl.rgba4: 4 red bits, 4 green bits, 4 blue bits 4 alpha bits. gl.rgb565: 5 red bits, 6 green bits, 5 blue bits. gl.rgb5_a1: 5 red bits, 5 green bits, 5 blue bits, 1 alpha bit. gl.depth_component16: 16 depth bits. gl.stencil_index8: 8 stencil bits. ...
...il_index8: 8 stencil bits. gl.depth_stencil when using a webgl 2 context, the following values are available additionally: gl.r8 gl.r8ui gl.r8i gl.r16ui gl.r16i gl.r32ui gl.r32i gl.rg8 gl.rg8ui gl.rg8i gl.rg16ui gl.rg16i gl.rg32ui gl.rg32i gl.rgb8 gl.rgba8 gl.srgb8_alpha8 (also available as an extension for webgl 1, see below) gl.rgb10_a2 gl.rgba8ui gl.rgba8i gl.rgb10_a2ui gl.rgba16ui gl.rgba16i gl.rgba32i gl.rgba32ui gl.depth_component24 gl.depth_component32f gl.depth24_stencil8 gl.depth32f_stencil8 when using the webgl_color_buffer_float extension: ext.rgba32f_ext: rgba 32-bit floating-point type. ext.rgb32f_ext: rgb 32-bit floating-point type. ...
WebGLRenderingContext.scissor() - Web APIs
default value: 0. width a non-negative glsizei specifying the width of the scissor box. default value: width of the canvas. ...
...default value: 0. width a non-negative glsizei specifying the width of the scissor box. default value: width of the canvas. ...
WebGLRenderingContext.stencilOp() - Web APIs
fail a glenum specifying the function to use when the stencil test fails. the default value is gl.keep. zfail a glenum specifying the function to use when the stencil test passes, but the depth test fails. the default value is gl.keep. ...
...r value of 0. gl.invert inverts the current stencil buffer value bitwise. examples the stencil testing is disabled by default. to enable or disable stencil testing, use the enable() and disable() methods with the argument gl.stencil_test. gl.enable(gl.stencil_test); gl.stencilop(gl.incr, gl.decr, gl.invert); to get the current information about stencil and depth pass or fail, query the following constants with getparameter(). gl.getparameter(gl.stencil_fail); gl.getparameter(gl.stencil_pass_depth_pass); gl.getparameter(gl.stencil_pass_depth_fail); gl.getparameter(gl.stencil_back_fail); gl.getparameter(gl.stencil_back_pass_depth_pass); gl.getparameter(gl.stencil_back_pass_depth_fail); gl.getparameter(gl.stencil_bits); specifications specification status comment ...
WebGLRenderingContext.stencilOpSeparate() - Web APIs
face a glenum specifying whether the front and/or back stencil state is updated. the possible values are: gl.front gl.back gl.front_and_back fail a glenum specifying the function to use when the stencil test fails. ...
...invert inverts the current stencil buffer value bitwise. examples the stencil testing is disabled by default. to enable or disable stencil testing, use the enable() and disable() methods with the argument gl.stencil_test. gl.enable(gl.stencil_test); gl.stencilopseparate(gl.front, gl.incr, gl.decr, gl.invert); to get the current information about stencil and depth pass or fail, query the following constants with getparameter(). gl.getparameter(gl.stencil_fail); gl.getparameter(gl.stencil_pass_depth_pass); gl.getparameter(gl.stencil_pass_depth_fail); gl.getparameter(gl.stencil_back_fail); gl.getparameter(gl.stencil_back_pass_depth_pass); gl.getparameter(gl.stencil_back_pass_depth_fail); gl.getparameter(gl.stencil_bits); specifications specification status comment ...
WebGLRenderingContext.texImage2D() - Web APIs
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.unsigned_short gl.unsigned_int ext.unsigned_int_24_8_webgl (constant provided by the extension) when using the oes_texture_float extension: gl.float when using the oes_texture_half_float extension: ext.half_float_oes (constant provided by the extension) when using a webgl 2 context, the following values are available additionally: gl.byte gl.unsigned_short gl.short gl.unsigned_int gl.int gl.half_float gl.float gl.unsigned_int_2_10_10_10_rev gl.unsigned_int_10f_11f_11f_rev gl.unsigned_int_5_9_9_9_rev gl.unsigned_int_24_8 gl.float_32_unsigned_int_24_8_rev (pixels must be null) pixels one of the following objects can be used...
WebGLRenderingContext.viewport() - Web APIs
default value: 0. ...
...default value: 0. ...
WebGLTransformFeedback - Web APIs
the webgltransformfeedback interface is part of the webgl 2 api and enables transform feedback, which is the process of capturing primitives generated by vertex processing. it allows to preserve the post-transform rendering state of an object and resubmit this data multiple times. ...
... the webgltransformfeedback interface is part of the webgl 2 api and enables transform feedback, which is the process of capturing primitives generated by vertex processing. it allows to preserve the post-transform rendering state of an object and resubmit this data multiple times. ...
Boilerplate 1 - Web APIs
» this 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. boilerplate code for setting up webgl rendering context by now you are quite used to seeing the same pieces of html, css, and javascript repeated again and again. so we are going to hide them from now on. this would allow us to focus on the interesting pieces of code that are most relevant for learning webgl. specifically, the html has a <p> element that contains some descriptive text about the page and may also hold error messages; a <canvas> element; and optionally a <button>. the css contains rules for body, canvas, and button. any additional non-trivial css and html will be displayed on the pages of specific ...
...he interesting pieces of code that are most relevant for learning webgl. specifically, the html has a <p> element that contains some descriptive text about the page and may also hold error messages; a <canvas> element; and optionally a <button>. the css contains rules for body, canvas, and button. any additional non-trivial css and html will be displayed on the pages of specific examples. in following examples, we will use a javascript helper function, getrenderingcontext(), to initialize the webgl rendering context. by now, you should be able to understand what the function does. basically, it gets the webgl rendering context from the canvas element, initializes the drawing buffer, clears it black, and returns the initialized context. in case of error, it displays an error message and retu...
Compressed texture formats - Web APIs
ts. these are useful to increase texture detail while limiting the additional video memory necessary. by default, no compressed formats are available: a corresponding compressed texture format extension must first be enabled. usage unless otherwise specified, this article applies to both webgl 1 and 2 contexts. if supported, textures can be stored in a compressed format in video memory. this allows for additional detail while limiting the added video memory necessary. textures are uncompressed on the fly when being accessed by a shader. note that this advantage doesn't translate to network bandwidth: while the formats are better than uncompressed data, they are in general far worse than standard image formats such as png and jpg. as compressed textures require hardware support, therefore ...
... or compressedtexsubimage[23]d instead of teximage2d calls. note that webgl makes no functionality available to compress or decompress textures: they must already be in a compressed format and can then be directly uploaded to video memory. all formats support 2d textures. which formats support texture_2d_array and texture_3d targets (in combination with compressedteximage3d) are noted in the following table. compressed texture extensions and which targets they support. extension notes texture_2d_array texture_3d webgl_compressed_texture_astc yes yes webgl_compressed_texture_atc not usable with compressedtexsubimage2d/copytexsubimage2d. no no webgl_compressed_texture_etc yes no webgl_compressed_texture...
WebGL constants - Web APIs
turned by functions. all constants are of type glenum. standard webgl constants are installed on the webglrenderingcontext and webgl2renderingcontext objects, so that you use them as gl.constant_name: var canvas = document.getelementbyid('mycanvas'); var gl = canvas.getcontext('webgl'); gl.getparameter(gl.line_width); some constants are also provided by webgl extensions. a list is provided below. var debuginfo = gl.getextension('webgl_debug_renderer_info'); var vendor = gl.getparameter(debuginfo.unmasked_vendor_webgl); the webgl tutorial has more information, examples, and resources on how to get started with webgl. table of contents standard webgl 1 constants standard webgl 2 constants webgl extension constants standard webgl 1 constants these constants are defined on the web...
...bool 0x8b56 bool_vec2 0x8b57 bool_vec3 0x8b58 bool_vec4 0x8b59 float_mat2 0x8b5a float_mat3 0x8b5b float_mat4 0x8b5c sampler_2d 0x8b5e sampler_cube 0x8b60 shader precision-specified types constant name value description low_float 0x8df0 medium_float 0x8df1 high_float 0x8df2 low_int 0x8df3 medium_int 0x8df4 high_int 0x8df5 framebuffers and renderbuffers constant name value description framebuffer 0x8d40 renderbuffer 0x8d41 rgba4 0x8056 rgb5...
Data in WebGL - Web APIs
Web › API › WebGL API › Data
s) and the javascript code. attributes are typically used to store color information, texture coordinates, and any other data calculated or retrieved that needs to be shared between the javascript code and the vertex shader. ...
...he javascript code and the vertex shader. ...
Matrix math for the web - Web APIs
stance from the origin let distance = math.sqrt(point[0] * point[0] + point[1] * point[1]); // the equivalent of 60 degrees, in radians let rotationinradians = math.pi / 3; let transformedpoint = [ math.cos(rotationinradians) * distance, math.sin(rotationinradians) * distance ]; it is possible to encode these type of steps into a matrix, and do it for each of the x, y, and z dimensions. ...
...ive. 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 function that we will be using to compose our matrices is multiplyarrayofmatrices(), which is part of the set of utility functions introduced near the top of this article. it takes an array of matrices and multiplies them together, returning the result. in webgl shader code, this is built i...
Using textures in WebGL - Web APIs
you create your own project based on this code. our sample loads a copy from a cdn in our html's <head>. loading textures the first thing to do is add code to load the textures. in our case, we'll be using a single texture, mapped onto all six sides of our rotating cube, but the same technique can be used for any number of textures. note: it's important to note that the loading of textures follows cross-domain rules; that is, you can only load textures from sites for which your content has cors approval. see cross-domain textures below for details. the code that loads the texture looks like this: // // initialize a texture and load an image. // when the image finished loading copy it into the texture. // function loadtexture(gl, url) { const texture = gl.createtexture(); gl.bindtext...
...must also be set to clamp_to_edge. on the other hand if the texture is a power of 2 in both dimensions then webgl can do higher quality filtering, it can use mipmap, and it can set the wrapping mode to repeat or mirrored_repeat. an example of a repeated texture is tiling 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...
WebGL: 2D and 3D graphics for the web - Web APIs
Web › API › WebGL API
and new features include: 3d textures, sampler objects, uniform buffer objects, sync objects, query objects, transform feedback objects, promoted extensions that are now core to webgl 2: vertex array objects, instancing, multiple render targets, fragment depth. see also the blog post "webgl 2 lands in firefox" and webglsamples.org/webgl2samples for a few demos. guides and tutorials below, you'll find an assortment of guides to help you learn webgl concepts and tutorials that offer step-by-step lessons and examples. guides data in webgl a guide to variables, buffers, and other types of data used when writing webgl code. webgl best practices tips and suggestions to help you improve the quality, performance, and reliability of your webgl content. using extensions a guide to...
...d to represent a 3d object view: the model, view and projection matrices. matrix math for the web a useful guide to how 3d transform matrices work, and can be used on the web — both for webgl calculations and in css3 transforms. resources raw webgl: an introduction to webgl a talk by nick desaulniers that introduces the basics of webgl. this is a great place to start if you've never done low-level graphics programming. khronos webgl site the main web site for webgl at the khronos group. webgl fundamentals a basic tutorial with fundamentals of webgl. webgl playground an online tool for creating and sharing webgl projects. good for quick prototyping and experimenting. webgl academy an html/javascript editor with tutorials to learn basics of webgl programming. webgl stats a site wi...
High-level guides - Web APIs
webrtc (web real-time communications) is a broad, multi-component system for setting up and operating complex audio, video, and data channels across networks among two or more peers on the web. the high-level guides listed below introduce webrtc technology from a top-down perspective, describing the overall architecture, the life cycle of a webrtc connection, and basic security and technological issues you might run into as you explore and build web content or apps using the webrtc api. in addition, you'll find suggestions as to tools, libraries, and frameworks that might be helpful and compatibility information so you know which parts of the overall suite of webrtc features can be safely used given your target audience. there are no subpages at this time. when you're ready to expl...
...eb content or apps using the webrtc api. in addition, you'll find suggestions as to tools, libraries, and frameworks that might be helpful and compatibility information so you know which parts of the overall suite of webrtc features can be safely used given your target audience. there are no subpages at this time. when you're ready to explore webrtc in more depth, be sure to take a look at our low-level guide to webrtc. ...
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
because webrtc doesn't mandate a specific transport mechanism for signaling during the negotiation of a new peer connection, it's highly flexible. however, despite that flexibility in transport and communication of signaling messages, there's still a recommended design pattern you should follow when possible, known as perfect negotiation. this article introduces webrtc perfect negotiation, describing how it works and why it's the recommended way to negotiate a webrtc connection between peers, and provides sample code to demonstrate the technique. after the first deployments of webrtc-capable browsers, it was realized that parts of the negotiation process were more complicated than they needed to be for typical use cases. this was due to a small number of issues with the api and some potenti...
...s isn't appreciably different from older webrtc connection establishment code. the user's camera and microphone are obtained by calling getusermedia(). the resulting media tracks are then added to the rtcpeerconnection by passing them into addtrack(). then, finally, the media source for the self-view <video> element indicated by the selfvideo constant is set to the camera and microphone stream, allowing the local user to see what the other peer sees. handling incoming tracks we next need to set up a handler for track events to handle inbound video and audio tracks that have been negotiatied to be received by this peer connection. to do this, we implement the the rtcpeerconnection's ontrack event handler. pc.ontrack = ({track, streams}) => { track.onunmute = () => { if (remotevideo.sr...
WebXR application life cycle - Web APIs
guide, we'll get a birds-eye view of what's involved in creating and driving a webxr application, without diving down to the code level in detail. this serves as preparation for the next few articles in these webxr guides, which cover starting up and shutting down a webxr session, geometry, simulating cameras, spatial tracking, and more. life cycle outline most applications using webxr will follow a similar overall design pattern: check to see if the user's device and browser are both capable of presenting the xr experience you want to provide. make sure the webxr 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 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.requestsession(), again specifying the string indicating the mode you want to enable: inline, immersive-vr, or immersive-ar. if the promise returned by requestsession() resolves...
Web Audio API best practices - Web APIs
ng 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 event, normally a click event. browser vendors decided that web audio contexts should not be allowed to automatically play audio; they should instead be started by a user. this is because autoplaying audio can be really annoying and obtrusive. but how do we handle this? when you create an audio context (either offline or online) it is created with a state, which can be suspended, running, or closed. when working with an audiocontext, if you create the audio context from inside a click event ...
...'click', function() { // check if context is in suspended state (autoplay policy) if (audioctx.state === 'suspended') { audioctx.resume(); } }, false); you might instead be working with an offlineaudiocontext, in which case you can resume the suspended audio context with the startrendering() method. user control if your website or application contains sound, you should allow the user control over it, otherwise again, it will become annoying. this can be achieved by play/stop and volume/mute controls. the using the web audio api tutorial goes over how to do this. if you have buttons that switch audio on and off, using the aria role="switch" attribute on them is a good option for signalling to assistive technology what the button's exact purpose is, and therefore maki...
Controlling multiple parameters with ConstantSourceNode - Web APIs
easy way to do something that sounds like it might be hard to do. you simply need to create a constantsourcenode and connect it to all of the audioparams whose values should be linked to always match each other. since constantsourcenode's offset value is simply sent straight through to all of its outputs, it acts as a splitter for that value, sending it to each connected parameter. the diagram below shows how this works; an input value, n, is set as the value of the constantsourcenode.offset property. the constantsourcenode can have as many outputs as necessary; in this case, we've connected it to three nodes: two gainnodes and a stereopannernode. so n becomes the value of the specified parameter (gain for the gainnodes and pan for the stereopannernode. as a result, every time you change ...
...g) { playbutton.innerhtml = "▶️"; stoposcillators(); } else { playbutton.innerhtml = "⏸"; startoscillators(); } } if the playing variable indicates we're already playing the oscillators, we change the playbutton's content to be the unicode character "right-pointing triangle" (▶️) and call stoposcillators() to shut down the oscillators. see stopping the oscillators below for that code. if playing is false, indicating that we're currently paused, we change the play button's content to be the unicode character "pause symbol" (⏸) and call startoscillators() to start the oscillators playing their tones. that code is covered under starting the oscillators below. controlling the linked oscillators the changevolume() function—the event handler for the slider cont...
Web audio spatialization basics - Web APIs
the official term for this is spatialization, and this article 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. ...
...ed to do some more maths for this. the rotation is a circle and we need math.sin and math.cos to help us draw that circle. ...
Attestation and Assertion - Web APIs
attestation when an authenticator registers a new key pair with a service, the authenticator signs the public key with an attestation certificate. ...
... android o was android key attestation, which enables the android operating system to attest to keys. android safetynet -prior to android key attestation, the only option for android devices was to create android safetynet attestations fido u2f - security keys that implement the fido u2f standard use this format none - browsers may prompt users whether they want a site to be allowed to see their attestation data and/or may remove attestation data from the authenticator's response if the `attestation` parameter in `navigator.credentials.create()` is set to `none` the purpose of attestation is to cryptographically prove that a newly generated key pair came from a specific device. this provides a root of trust for a newly generated key pair as well as being able to identi...
Web Storage API - Web APIs
data is never transferred to the server. ...
...e usage of web storage. note: access to web storage from third-party iframes is denied if the user has disabled third-party cookies (firefox implements this behaviour from version 43 onwards.) note: web storage is not the same as mozstorage (mozilla's xpcom interfaces to sqlite) or the session store api (an xpcom storage utility for use by extensions). ...
Window.captureEvents() - Web APIs
example <!doctype html> <html lang="en"> <head> <!-- ... ...
...l> notes events raised in the dom by user activity (such as clicking buttons or shifting focus away from the current document) generally pass through the high-level window and document objects first before arriving at the object that initiated the event. when you call the captureevents() method on the window, events of the type you specify (for example, event.click) no longer pass through to "lower" objects in the hierarchy. in order for events to "bubble up" in the way that they normally do, you must call window.releaseevents() ( ) on the window to keep it from trapping events. note that you can pass a list of events to this method using the following syntax: window.captureevents(event.keypress | event.keydown | event.keyup). specification this is not part of any specification. ...
Window.devicePixelRatio - Web APIs
when dealing with the difference between rendering on a standard display versus a hidpi or retina display, which use more screen pixels to draw the same objects, resulting in a sharper image. you can use window.matchmedia() to check if the value of devicepixelratio changes (which can happen, for example, if the user drags the window to a display with a different pixel density). see the example below. ...
...mple below. syntax value = window.devicepixelratio; value a double-precision floating-point value indicating the ratio of the display's resolution in physical pixels to the resolution in css pixels. a value of 1 indicates a classic 96 dpi (76 dpi on some platforms) display, 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> javascri...
Window.personalbar - Web APIs
due to deprecation of enableprivilege this functionality can not be used in web pages. enableprivilege is disabled in firefox 15 and will be removed in firefox 17. ...
...also be aware that dynamically updating the visibilty of the various toolbars can change the size of the window rather dramatically, and may affect the layout of your page. specifications specification status comment html l...
Window: popstate event - Web APIs
nging the current history entry to one we'll refer to as new-entry. the current page's session history stack entry will be referred to as current-entry. if new-entry doesn't currently contain an existing document, fetch the content and create its document before continuing. this will eventually send events such as domcontentloaded and load to the window containing the document, but the steps below will continue to execute in the meantime. if current-entry's title wasn't set using one of the history api methods (pushstate() or replacestate(), set the entry's title to the string returned by its document.title attribute. if the browser has state information it wishes to store with the current-entry before navigating away from it, it then does so. the entry is now said to have "persisted use...
.... any persisted user state is restored, if the browser chooses to do so. if the original and new entry's shared the same document, but had different fragments in their urls, send the hashchange event to the window. as you can see, the popstate event is nearly the last thing done in the process of navigating pages in this way. ...
Window.requestAnimationFrame() - Web APIs
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 call when it's time to update your animation for the next repaint. the callback function is passed one single argument, a domhighrestimestamp similar to the one returned by performance.now(), indicating the point in time when requestanimationframe() starts to execute callback function...
... 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 definition of 'requestanimationframe' in that specification. living standard no change, supersedes the previous one. timing control for script-based animationsthe definition of 'requestanimationf...
Window.self - Web APIs
Web › API › Window › self
ndalone (self). the advantage of the standalone notation is that a similar notation exists for non-window contexts, such as in web workers. by using self, you can refer to the global scope in a way that will work not only in a window context (self will resolve to window.self) but also in a worker context (self will then resolve to workerglobalscope.self). ...
...ext (self will then resolve to workerglobalscope.self). example uses of window.self like the following could just as well be replaced by window. if (window.parent.frames[0] != window.self) { // this window is not the first frame in the list } furthermore, when executing in the active document of a browsing context, window is a reference to the current global object and thus all of the following are equivalent: var w1 = window; var w2 = self; var w3 = window.window; var w4 = window.self; // w1, w2, w3, w4 all strictly equal, but only w2 will function in workers specifications specification status comment html living standardthe definition of 'window.self' in that specification. living standard no difference from the latest snapshot html 5.1 h...
Window.statusbar - Web APIs
Web › API › Window › statusbar
the window.statusbar property returns the statusbar object, whose visibility can be toggled in the window. syntax objref = window.statusbar example the following complete html example shows a way that the visible property of the various "bar" objects is used, and also the change to the privileges necessary to write to the visible property of any of the bars on an existing window. <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>various dom tests</title> <script> // changing bar states on the existing window netscape.security.privilegemanager.enableprivilege("universalbrowserwrite"); window.statusbar.visible=!window.statusbar.visible; </script> </head> <body> <p>various dom tests</p> </body> </html> notes when you load the example page above, the browser di...
...also be aware that dynamically updating the visibilty of the various toolbars can change the size of the window rather dramatically, and may affect the layout of your page. specifications specification status comment html l...
Window.toolbar - Web APIs
Web › API › Window › toolbar
due to deprecation of enableprivilege this functionality can not be used in web pages. enableprivilege is disabled in firefox 15 and will be removed in firefox 17. ...
...irefox 17. <!doctype html> <html> <head> <title>various dom tests</title> <script> // changing bar states on the existing window netscape.security.privilegemanager.enableprivilege("universalbrowserwrite"); window.toolbar.visible=!window.toolbar.visible; </script> </head> <body> <p>various dom tests</p> </body> </html> notes when you load the example page above, the browser displays the following dialog: to toggle the visibility of these bars, you must either sign your scripts or enable the appropriate privileges, as in the example above. also be aware that dynamically updating the visibilty of the various toolbars can change the size of the window rather dramatically, and may affect the layout of your page. see also: window.locationbar, window.menubar, window.personalbar, window.sc...
Window: unload event - Web APIs
the unload event is fired when the document or a child resource is being unloaded. bubbles no cancelable no interface event event handler property onunload it is fired after: beforeunload (cancelable event) pagehide the document is in the following state: all the resources still exist (img, iframe etc.) nothing is visible anymore to the end user ui interactions are ineffective (window.open, alert, confirm, etc.) an error won't stop the unloading workflow please note that the unload event also follows the document tree: parent frame unload will happen before child frame unload (see example below). examples <!doctype html> <html> <head> <title>parent frame</title> <script> window.addeventlistener('beforeunl...
...doctype html> <html> <head> <title>parent frame</title> <script> window.addeventlistener('beforeunload', function(event) { console.log('i am the 1st one.'); }); window.addeventlistener('unload', function(event) { console.log('i am the 3rd one.'); }); </script> </head> <body> <iframe src="child-frame.html"></iframe> </body> </html> below, the content of child-frame.html: <!doctype html> <html> <head> <title>child frame</title> <script> window.addeventlistener('beforeunload', function(event) { console.log('i am the 2nd one.'); }); window.addeventlistener('unload', function(event) { console.log('i am the 4th and last one…'); }); </script> </head> <body> ☻ </body...
Worker.prototype.postMessage() - Web APIs
ts to transfer ownership of. if the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and becomes available only to the worker it was sent to. transferable objects are instances of classes like arraybuffer, messageport or imagebitmap objects that can be transferred. null is not an acceptable value for transfer. returns void. example the following code snippet shows the creation of a worker object using the worker() constructor. when either of two form inputs (first and second) have their values changed, change events invoke postmessage() to send the value of both inputs to the current worker. var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('messag...
...ge to chromeworker'; } } myworker.addeventlistener('message', handlemessagefromworker); // ok lets create the buffer and send it var arrbuf = new arraybuffer(8); console.info('arrbuf.bytelength pre transfer:', arrbuf.bytelength); myworker.postmessage( { atopic: 'do_sendworkerarrbuff', abuf: arrbuf // the array buffer that we passed to the transferrable section 3 lines 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 mess...
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. ...
...er'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('test\n'); this should result in a "test" message being output to the terminal. specifications this method does not appear in any specification. ...
WorkerGlobalScope.location - Web APIs
the location read-only property of the workerglobalscope interface returns the workerlocation associated with the worker. it is a specific location object, mostly a subset of the location for browsing scopes, but adapted to workers. syntax var locationobj = self.location; value a workerlocation object. ...
...location object. ...
WorkerGlobalScope.navigator - Web APIs
the navigator read-only property of the workerglobalscope interface returns the workernavigator associated with the worker. it is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers. syntax var navigatorobj = self.navigator; value a workernavigator object. ...
...bj = self.navigator; value a workernavigator object. ...
WorkerGlobalScope - Web APIs
this interface inherits methods from the eventtarget interface 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.c...
...s an exception when called (see bug 1336043). example you won't access workerglobalscope directly in your code; however, its properties and methods are inherited by more specific global scopes such as dedicatedworkerglobalscope and sharedworkerglobalscope. for example, you could import another script into the worker and print out the contents of the worker scope's navigator object using the following two lines: importscripts('foo.js'); console.log(navigator); since the global scope of the worker script is effectively the global scope of the worker you are running (dedicatedworkerglobalscope or whatever) and all worker global scopes inherit methods, properties, etc. from workerglobalscope, you can run lines such as those above without specifying a parent object. specifications ...
WritableStreamDefaultWriter - Web APIs
defaultwriter interface of the the streams api is the object 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 resolv...
.... if the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. writablestreamdefaultwriter.write() writes a passed chunk of data to a writablestream and its underlying sink, then returns a promise that resolves to indicate the success or failure of the write operation. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. fin...
Sending and Receiving Binary Data - Web APIs
oreq.send(null); you can also read a binary file as a blob by setting the string "blob" to the responsetype property. var oreq = new xmlhttprequest(); oreq.open("get", "/myfile.png", true); oreq.responsetype = "blob"; oreq.onload = function(oevent) { var blob = oreq.response; // ... }; oreq.send(); receiving binary data in older browsers the load_binary_resource() function shown below loads binary data from the specified url, returning it to the caller. function load_binary_resource(url) { var req = new xmlhttprequest(); req.open('get', url, false); //xhr binary charset opt by marcus granado 2006 [http://mgran.blogspot.com] req.overridemimetype('text\/plain; charset=x-user-defined'); req.send(null); if (req.status != 200) return ''; return req.responsetext; } ...
...hes the byte at offset x within the loaded binary data. the valid range for x is from 0 to filestream.length-1. see downloading binary streams with xmlhttprequest for a detailed explanation. see also downloading files. sending binary data the send method of the xmlhttprequest has been extended to enable easy transmission of binary data by accepting an arraybuffer, blob, or file object. the following example creates a text file on-the-fly and uses the post method to send the "file" to the server. this example uses plain text, but you can imagine the data being a binary file instead. var oreq = new xmlhttprequest(); oreq.open("post", url, true); oreq.onload = function (oevent) { // uploaded. }; var blob = new blob(['abc123'], {type: 'text/plain'}); oreq.send(blob); sending typed arra...
XMLHttpRequest.response - Web APIs
itialize the request but before calling send() to send the request to the server. the value is null if the request is not yet complete or was unsuccessful, with the exception that when reading text data using a responsetype of "text" or the empty string (""), the response can contain the response so far while the request is still in the loading readystate (3). the response types are described below. "" an empty responsetype string is treated the same as "text", the default type. arraybuffer the response is a javascript arraybuffer containing binary data. blob the response is a blob object containing the binary data. document 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 abou...
...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 passed into the callback function provided to...
XMLHttpRequest.responseType - Web APIs
sponsetype enum which specifies what type of data the response contains. when setting responsetype to a particular value, the author should make sure that the server is actually sending a response compatible with that format. if the server returns data that is not compatible with the responsetype that was set, the value of response will be null. the values supported by responsetype are the following: "" an empty responsetype string is treated the same as "text", the default type. arraybuffer the response is a javascript arraybuffer containing binary data. blob the response is a blob object containing the binary data. document 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 a...
...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 change the value of responsetype in a synchronou...
XPathEvaluator.evaluate() - Web APIs
ted. contextnode a node representing the context to use for evaluating the expression. resolver optional permits translation of all prefixes, including the xml namespace prefix, within the xpath expression into appropriate namespace uris. type optional specifies the type of result to be returned by evaluating the expression. this must be one of the xpathresult.constants. result optional allows to specify a result object which may be reused and returned by this method. if this is specified as null or the implementation does not reuse the specified result, a new result object will be returned. return value an xpathresult object representing the result of evaluating the xpath expression. exceptions invalid_expression_err if the expression is not legal according to the rules of the ...
...ised. wrong_document_err if the provided context node is from a document that is not supported by the xpathevaluator, a domexception of type wrong_document_err is raised. not_supported_err if the provided context node is not a type permitted as an xpath context node or the request type is not permitted by the xpathevaluator, a domexception of type not_supported_err is raised. example the following example shows the use of the evaluate() method. html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var evaluator = new xpathevaluator(); var result = evaluator.evaluate("//div", document, null, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specif...
XPathExpression.evaluate() - Web APIs
es an xpath expression on the given node or document and returns an xpathresult. syntax xpathresult node.evaluate(contextnode, type, result); parameters contextnode a node representing the context to use for evaluating the expression. type optional specifies the type of result to be returned by evaluating the expression. this must be one of the xpathresult.constants. result optional allows to specify a result object which may be reused and returned by this method. if this is specified as null or the implementation does not reuse the specified result, a new result object will be returned. return value an xpathresult object representing the result of evaluating the xpath expression. exceptions invalid_expression_err if the expression is not legal according to the rules of the ...
...ised. wrong_document_err if the provided context node is from a document that is not supported by the xpathevaluator, a domexception of type wrong_document_err is raised. not_supported_err if the provided context node is not a type permitted as an xpath context node or the request type is not permitted by the xpathevaluator, a domexception of type not_supported_err is raised. example the following example shows the use of the evaluate() method. html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = resul...
XRBoundedReferenceSpace - Web APIs
the webxr device api's xrboundedreferencespace interface describes a virtual world reference space which has preset boundaries. this extends xrreferencespace, which describes an essentially unrestricted space around the viewer's position. these bounds are defined using an array of points, each of which defines a vertex in a polygon inside which the user is allowed to move. 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 ar...
...er 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 of which defines a vertex in the polygon defining the boundaries within which the user will be required to remain. these vertices must be sorted such that they move clockwise around the viewer's position. methods xrboundedreferencespace inherits the methods of its parent interface, xrreferencespace. it has no further ...
XREnvironmentBlendMode - Web APIs
the webxr api's enumerated type xrenvironmentblendmode defines strings used to identify if and how to blend the rendered virtual content with the real world. its values are used by the xrsession interface's environmentblendmode property. values opaque the rendered image is drawn without allowing any pass-through imagery. this is primarily used by fully-immersive vr headsets, which totally obscure the surrounding environment, with none of the real world shown to the user at all. ...
...-immersive vr headsets, which totally obscure the surrounding environment, with none of the real world shown to the user at all. the alpha values specified in the xrsession's renderstate property's baselayer field are ignored since the alpha values for the rendered imagery are all treated as being 1.0 (fully opaque). additive primarily used by ar devices with transparent lenses which directly allow reality to pass through to the user's eyes, the additive blending mode is designed to be used in a situation in which the device has no control over the background and its brightness, since that isn't being digitally controlled. all the device can do is add more light to the image; it can't make things get darker. therefore, black is rendered as fully transparent, and there's no way to make a pix...
XRInputSourceArray - Web APIs
ourcearray represents a live list of webxr input sources, and is used as the return value of the xrsession property inputsources. each entry is an xrinputsource representing one input device connected to the webxr system. in addition to being able to access the input sources in the list using standard array notation (that is, with index numbers insize square brackets), methods are available to allow the use of iterators and the foreach() method is also available. properties the following properties are available on xrinputsourcearray objects. length read only the number of xrinputsource objects in the list. methods the following methods are available on xrinputsourcearray objects. you may also use the features of the symbol type. entries() returns an iterator you can use to wal...
...over each item in the list, in order from first to last. keys() a list of the keys corresponding to the entries in the input source list. values() returns an iterator you can use to go through all the values in the list. each item is a single xrinputsource object. in addition to these methods, you may use array notation to access items in the list by index for example, the snippet of code below calls a function handleinput(), passing into it the first item in the input source list, if the list isn't empty. let sources = xrsession.inputsources; if (sources.length > 0) { handleinput(sources[0]); } examples specifications specification status comment webxr device apithe definition of 'xrinputsourcearray' in that specification. working draft initial ...
XRInputSourceEvent() - Web APIs
eates and returns a new xrinputsourceevent object describing an event (state change) which has occurred on a webxr user input device represented by an xrinputsource. syntax newinputsourceevent = new xrinputsourceevent(type, eventinitdict); parameters type a domstring indicating which of the input source events the new object will represent. permitted values are listed under event types below. eventinitdict an object based on the xrinputsourceeventinit dictionary which contains the values to assign to the new event's properties. return value a new xrinputsourceevent object representing the event described by the given type and eventinitdict. event types select sent to an xrsession when the sending input source has fully completed a primary action. selectend sent to an xr...
...rce has fully completed a primary squeeze action. squeezeend sent 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 */ ...
XRPermissionDescriptor.optionalFeatures - Web APIs
to use them isn't available. while further features may be defined in future editions of webxr, currently all permitted values come from the xrreferencespacetype enumerated type, indicating reference spaces the app rquires to be available. the reference space returned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace. the "interface" column in the table below indicates which of the two types is returned 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 use...
...placed in a safe location for the viewer to stand, where the value of the y axis is 0 at floor level. if that floor level isn't known, the user agent will estimate the floor level. if the estimated floor level is non-zero, the browser is expected to round it such a way as to avoid fingerprinting (likely to the nearest centimeter). xrreferencespace unbounded a tracking space which allows the user total freedom of movement, possibly over extremely long distances from their origin point. the viewer isn't tracked at all; tracking is optimized for stability around the user's current position, so the native origin may drift as needed to accommodate that need. xrreferencespace viewer a tracking space whose native origin tracks the viewer's position and orientation. this...
XRPermissionDescriptor.requiredFeatures - Web APIs
eatures in the list are available for use with the user's permission. currently, all features are members of the xrreferencespacetype enumerated type, indicating the reference space types that your app would like permission to use, but can operate without. future editions 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 sp...
...placed in a safe location for the viewer to stand, where the value of the y axis is 0 at floor level. if that floor level isn't known, the user agent will estimate the floor level. if the estimated floor level is non-zero, the browser is expected to round it such a way as to avoid fingerprinting (likely to the nearest centimeter). xrreferencespace unbounded a tracking space which allows the user total freedom of movement, possibly over extremely long distances from their origin point. the viewer isn't tracked at all; tracking is optimized for stability around the user's current position, so the native origin may drift as needed to accommodate that need. xrreferencespace viewer a tracking space whose native origin tracks the viewer's position and orientation. this...
XRPermissionDescriptor - Web APIs
the webxr features the app needs to use, as well as those features it would like ot use if permision is granted. the xrpermissiondescriptor's name must be set to xr in order to direct the permissions api to correctly handle the request as applying to webxr. properties in addition to inheriting the properties of the parent interface, permissiondescriptor, xrpermissiondescriptor provides the following properties. mode an xrsessionmode value indicating the xr mode (inline, immersive-vr, or immersive-ar) for which the permissions are requested. optionalfeatures an array of strings, each specifying the name of a webxr 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 xrsessioni...
...ing the name of a webxr 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 chec...
XRPermissionStatus.granted - Web APIs
permission api's navigator.permissions.query() method was called. syntax grantedfeatures = xrpermissionstatus.granted; value an array of domstring objects, each identifying a single webxr feature which the app or site has been granted permission to use. currently, all 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 sp...
...placed in a safe location for the viewer to stand, where the value of the y axis is 0 at floor level. if that floor level isn't known, the user agent will estimate the floor level. if the estimated floor level is non-zero, the browser is expected to round it such a way as to avoid fingerprinting (likely to the nearest centimeter). xrreferencespace unbounded a tracking space which allows the user total freedom of movement, possibly over extremely long distances from their origin point. the viewer isn't tracked at all; tracking is optimized for stability around the user's current position, so the native origin may drift as needed to accommodate that need. xrreferencespace viewer a tracking space whose native origin tracks the viewer's position and orientation. this...
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
was called, but with an origin offset indicating the distance from the object to the point given by originoffset. if the object on which you call this method is an xrboundedreferencespace, the returned object is one as well. the boundsgeometry of the new reference space is set to the original object's boundsgeometry with each of its points multiplied by the inverse of originoffset. examples below are some examples showing how to use getoffsetreferencespace(). teleporting or setting the position of the viewer upon first creating a scene, you may need to set the user's position within the 3d world. you can do that using getoffsetreferencespace(). xrsession.requestreferencespace("local") .then((refspace) => { xrreferencespace = refspace; xrreferencespace = xrreferencespace.getoffsetre...
...whose orientation is looking directly along the z azis. then the first animation frame is requested using xrsession's requestanimationframe(). implementing rotation based on non-xr inputs the input controls supported directly by webxr are all dedicated vr or ar input devices. in order to use mouse, keyboard, or other input devices to move or otherwise transform objects in the 3d space—or to allow the user to move through the space—you'll need to write some code to read the inputs and move perform the movements. this is another good use case for getoffsetreferencespace(). in this example, we'll show code that lets the user look around by right-clicking and moving the mouse to change the viewing angle. first, we add an event handler for mousemove events, which calls our code to perform ...
XRReferenceSpace: reset event - Web APIs
reset or reconfigured by changing the reference space's origin, moving and rotating it as indicated by the event's transform property. the event is sent before any animation frame callbacks are executed to render the pending frame, to ensure that those callbacks have the updated coordinate system available. there are a number of reasons why a reset might occur. most common among them are the following: the user has manually reset the coordinate system, such as by requesting that the headset recalibrate itself to ensure that the facing direction and hand controllers are synchronized with the user's actual position and facing. this is primarily an issue for local or local-floor reference spaces. for a bounded-floor reference space, the coordinate system can be reset if the user exits the ...
...otion through the space by expressly changing the position and/or orientation of the viewer (rather than the user's physical movements being used by the xr device to introduce movement). however, if that kind of "teleportation" is being used, you actually want to avoid jumping the user's position after tracking recovery, this can introduce additional and potentially jarring jumping. instead of allowing this to happen, you can integrate the emulatedposition into the teleportation offset calculated prior to calling getoffsetreferencespace() to create a new reference space whose updated effective origin is adjusted by the distance the viewer's position jumped since the previous frame. this way, the user's position only changes once rather than twice. the effect of discontinuity size the reset...
XRReferenceSpaceType - Web APIs
referencespacetype enumerated type defines the strings which identify the types of reference spaces supported by webxr. this type is used when calling the requestreferencespace() method to obtain a reference space for an xrsession. values the reference space returned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace. the "interface" column in the table below indicates which of the two types is returned 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 use...
...placed in a safe location for the viewer to stand, where the value of the y axis is 0 at floor level. if that floor level isn't known, the user agent will estimate the floor level. if the estimated floor level is non-zero, the browser is expected to round it such a way as to avoid fingerprinting (likely to the nearest centimeter). xrreferencespace unbounded a tracking space which allows the user total freedom of movement, possibly over extremely long distances from their origin point. the viewer isn't tracked at all; tracking is optimized for stability around the user's current position, so the native origin may drift as needed to accommodate that need. xrreferencespace viewer a tracking space whose native origin tracks the viewer's position and orientation. this...
XRSession.environmentBlendMode - Web APIs
a stable state. you should use caution when using its features. syntax blendmode = xrsession.environmentblendmode; value a domstring whose value is one of the strings found in the enumerated type xrenvironmentblendmode, defining if—and if so, how—virtual, rendered content is overlaid atop the image of the real world. permitted values are: opaque the rendered image is drawn without allowing any pass-through imagery. this is primarily used by fully-immersive vr headsets, which totally obscure the surrounding environment, with none of the real world shown to the user at all. the alpha values specified in the xrsession's renderstate property's baselayer field are ignored since the alpha values for the rendered imagery are all treated as being 1.0 (fully opaque). additive primarily...
...-immersive vr headsets, which totally obscure the surrounding environment, with none of the real world shown to the user at all. the alpha values specified in the xrsession's renderstate property's baselayer field are ignored since the alpha values for the rendered imagery are all treated as being 1.0 (fully opaque). additive primarily used by ar devices with transparent lenses which directly allow reality to pass through to the user's eyes, the additive blending mode is designed to be used in a situation in which the device has no control over the background and its brightness, since that isn't being digitally controlled. all the device can do is add more light to the image; it can't make things get darker. therefore, black is rendered as fully transparent, and there's no way to make a pix...
XRSession: selectend event - Web APIs
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. ...
... 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 following example uses addeventlistener() to establish handlers for the selection events: selectstart, selectend, and select. this snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. in this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. only after completing those tasks does the onselectionevent() function below dispatch the action out to a specialized function to handle things. after checking to e...
XRSession: selectstart event - Web APIs
hen 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. ...
... 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 snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. in this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. only after completing those tasks does the onselectionevent() function below dispatch the action out to a specialized function to handle things. after checking to e...
XRSession: squeezeend event - Web APIs
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. ...
...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. examples the following example uses addeventlistener() to establish handlers for the squeezeion events: squeezestart, squeezeend, and squeeze. this snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. in this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. only after completing those tasks does the onsqueezeevent() function below dispatch the action out to a specialized function to handle things. after checking to ens...
XRSession: squeezestart event - Web APIs
our hands, and may be simulated using triggers on hand controllers. bubbles yes cancelable no interface xrinputsourceevent event handler property onsqueezestart 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. ...
...ndler property onsqueezestart 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 establish handlers for the squeezeion events: squeezestart, squeezeend, and squeeze. this snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. in this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. only after completing those tasks does the onsqueezeevent() function below dispatch the action out to a specialized function to handle things. after checking to ens...
XRSystem - Web APIs
Web › API › XRSystem
representing a webxr session. with that xrsession in hand, you can use it to interact with the augmented reality (ar) or virtual reality (vr) device. properties while xrsystem directly offers no properties, it does inherit properties from its parent interface, eventtarget. methods in addition to inheriting methods from its parent interface, eventtarget, the xrsystem interface includes the following methods: issessionsupported() returns a promise which resolves to true if the browser supports the given xrsessionmode. resolves to false if the specified mode isn't supported. requestsession() returns a promise that resolves to a new xrsession with the specified xrsessionmode. events devicechange sent when the set of available xr devices has changed. also available using th...
...new xrsession with the specified xrsessionmode. events devicechange sent when the set of available xr devices has changed. also available using the ondevicechange event handler. usage notes thsi interface was previously known as simply xr in earlier versions of the specification; if you see references to xr in code or documentation, simply replace that with xrsystem. examples the following example shows how to use both issessionsupported() and requestsession(). if (navigator.xr) { immersivebutton.addeventlistener("click", onbuttonclicked); navigator.xr.issessionsupported('immersive-vr') .then((issupported) => { if (issupported) { immersivebutton.disabled = false; } else { immersivebutton.disabled = true; }); } function onbuttonclicked() { if (!xrs...
XRView.eye - Web APIs
Web › API › XRView › eye
w.eye; value a domstring whose value is one of the strings enumerated by the xreye type: left the xrview represents the point-of-view of the viewer's left eye. right the view represents the viewer's right eye. none the xrview describes a monoscopic view, or the view otherwise doesn't represent a particular eye's point-of-view. usage notes the primary purpose of this property is to allow the correct area of any pre-rendered stereo content to be presented to the correct eye. for dynamically-rendered 3d content, you can usually ignore this and simply render each of the viewer's views, one after another. examples this code, from the viewer pose's renderer, iterates over the pose's views and renders them. however, we have flags which, if true, indicate that a particular eye has bee...
... updateinjury() returns true if the eye is still injured or false if the eye has been restored to health by the function,. if the result is false, indicating that the eye is now healthy, we render the scene for that eye. otherwise, we don't. specifications specification ...
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
l 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 buffer are 50% what they were before, resulting in a total frame buffer size of 1280 by 720 pixels, with each eye's half of the buffer being 640x720 pixels. now we can see the coordinates of each of the viewports representing these two views: since each eye gets half of the frame buffer, the result is that the left eye gets a 640x720 portion...
...nary, which is an xrwebgllayerinit object. that gets us a new xrwebgllayer object representing a rendering surface we can use for the xrsession; we set it as the rendering surface for xrsession by calling its updaterenderstate() method, passing the new gllayer in using the xrrenderstate dictionary's xrrenderstate.baselayer property. the result is a rendering context that looks like the diagram below: each time the xrviewerpose's views are iterated over for rendering, the rendering loop obtains an xrview for the left eye which has its top-left corner at (0, 0) with its width and height being 1280x1440 pixels. the right eye it obtains has its top-left corner at 1280, 0 with the same width and height: 1280x1440. specifications specification status comment webxr devi...
Introduction - Web APIs
introduction one noticeable trend in w3c standards has been the effort to separate content from style. this would allow the same style to be reused for 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. ...
...tyle 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 new document based on the rules in the xsl stylesheet. this allows xslt to add, remove and reorganize elements from the original xml document and thus allows more fine-grain control of the resulting document's structure. transformation...
Using the alertdialog role - Accessibility
interactive controls. if an alert dialog only contains static content and has no interactive controls at all, alertdialog is likely not the right role to use here. the alert role should be used instead in that case (as the described in the using the alert role technique). possible effects on user agents and assistive technology when the alertdialog role is used, the user agent should do the following: expose the element as a dialog in the operating system's accessibility api. fire an accessible alert event using the operating system's accessibility api if it supports it. when the alert dialog appears, screen readers should announce the alert. when the alert dialog is correctly labeled and focus is moved to a control inside the dialog, screen readers should announce the dialog's acce...
...d to a control inside the dialog, screen readers should announce the dialog's accessible role, name and optionally description before announcing the focused element. 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: a basic alert dialog the code snippet below shows how to mark up an alert dialog that only provides a message and an ok button. <div role="alertdialog" aria-labelledby="dialog1title" aria-describedby="dialog1desc"> <div role="document" tabindex="0"> <h2 id="dialog1title">your login session is about to expire</h2> <p id="dialog1desc">to extend your session, click the ok button</p> <button>ok</button> </div> </div> working ...
Using the aria-valuemax attribute - Accessibility
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. ...
... 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 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. <div role="slider" aria-valuenow="4" aria-valuemin="1" aria-valuemax="10"> working examples: progressbar example slider example spinbutton example notes used with aria roles progressbar scrollbar slider spinbutton related aria techniques aria-valuemin aria-valuenow aria-valuetext compatibility tbd: add support informat...
Using the aria-valuemin attribute - Accessibility
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. aria-valuemin 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 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. ...
...r agents and assistive technology 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 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 minimum value of 1. <div role="slider" aria-valuenow="4" aria-valuemin="1" aria-valuemax="10"> working examples: progressbar example slider example spinbutton example notes used with aria roles progressbar scrollbar slider spinbutton related aria techniques aria-valuemax aria-valuenow aria-valuetext compatibility tbd: add support informati...
Using the link role - Accessibility
also support keyboard and focus requirements by default, without need for additional customization. the tabindex attribute may optionally be used with this role to directly specify the position of the element in the tab order. possible effects on user agents and assistive technology when the link role is added to an element, or such an element becomes visible, the user agent should do the following: expose the element as having a link role in the operating system's accessibility api. fire an accessible link event using the operating system's accessibility api if it supports it. assistive technology products should listen for such an event and notify the user accordingly: screen readers should announce the text of the link or its label when it is focused, along with the fact that...
... that there are still problems with this approach: it is very difficult to detect whether the target of the fake link has been visited before, and therefore use :visited styles (e.g. the default purple color for visited links). opening a page using the open() method counts as being a popup, and certain browsers may issue a warning when you try to activate it, or make you explicitly agree to allowing popups form the domain it exists on. html <h1>role="link" example</h1> <span data-href="https://mozilla.org" tabindex="0" id="link1" role="link" class="link"> fake accessible link created using a span </span> <p><a href="https://mozilla.org" target="_blank">actual real link</a></p> css span[role="link"] { color: blue; text-decoration: underline; cursor: pointer; } span[role="l...
Using the log role - Accessibility
ds to hear the entire live region upon a change aria-atomic="true" should be set. to have announcements made as soon as possible and where the user may be interrupted, aria-live="assertive" can be set for more aggressive updates. possible effects on user agents and assistive technology when the log role is added to an element, or such an element becomes visible, the user agent should do the following: expose the element as having a log role in the operating system's accessibility api. fire an accessible log event using the operating system's accessibility api if it supports it. assistive technology products should listen for such an event and notify the user accordingly: screen readers should announce changes inside a log when the user is idle, unless aria-live=”assertive” has...
... aria-live=”assertive” has been set and in which case the user may be interrupted. screen magnifiers may visually indicate that a log update has occurred. note: opinons 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: adding the role in the html code the snippet below shows how the log role is added directly into the html source code. <div id="liveregion" class="region" role="log"></div> example 2: snippet from an example application this snippet creates the chat log in an ajax chat application. <div id="chatarea" role="log"> <ul id="chatregion" aria-live="polite" aria-atomic="false"> <li>please choose a user name to begin using ajax chat.</li> </...
Using the status role - Accessibility
another part of the page controls what appears in the status, the relationship should be made explicit via the aria-controls attribute. assistive technologies may reserve some cells of a braille display to render the status. possible effects on user agents and assistive technology when the status role is added to an element, or such an element becomes visible, the user agent should do the following: expose the element as having a status role in the operating system's accessibility api. fire an accessible status event using the operating system's accessibility api if it supports it. assistive technology products should listen for such an event and notify the user accordingly: screen readers may provide a special key to announce the current status, and this should present the con...
...d when the user is idle, unless aria-live=”assertive” has been set and in which case the user may be interrupted. screen magnifiers may enlarge the status. note: opinons 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: adding the status role in html the snippet below shows how the status role is added directly into the html source code. <p role="status">your changes were automatically saved.</p> working examples: notes aria attributes used status related aria techniques alert role live region roles live region attributes compatibility the paciello group published some data on compatibility via their 2014 blog post: screen reader s...
Using ARIA: Roles, states, and properties - Accessibility
ion of aria semantics only exposes extra information to a browser's accessibility api, and does not affect a page's dom. roles widget roles button checkbox gridcell link menuitem menuitemcheckbox menuitemradio option progressbar radio scrollbar searchbox separator (when focusable) slider spinbutton switch tab tabpanel textbox treeitem composite roles the techniques below describe each composite role as well as their required and optional child roles. combobox grid (including row, gridcell, rowheader, columnheader roles) listbox (including option role) menu menubar radiogroup (see radio role) tablist (including tab and tabpanel roles) tree treegrid document structure roles application article cell columnheader definition directory document...
...red 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-rowcount aria-rowindex aria-rowspan aria-setsize microsoftedge-specific properties x-ms-aria-flowfrom ...
ARIA: application role - Accessibility
is streamlined to a single-column view. a keyboard interaction model is generated that is very similar to a word processor where users can read line by line, sentence by sentence, or paragraph by paragraph. the at will read any semantics like links, headings, form controls, tables, lists, or images. in addition, a set of so-called quick navigation keys has been established over the years that allows blind users to skim through a page via a certain element type. such elements usually include headings, form fields, lists, tables, links, graphics, or landmark regions. for all of this to work, ats intercept almost all keyboard input and consume it themselves, letting nothing through to the browser or other user agent. to be able to interact with a web page, a standard set of widgets is recogni...
... 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 actually need it and cannot just use a set of other, known, widgets to accomplish the same task. if used, the application role should be added to the lowest common container possible, not on the <body> element, for example. specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'application' in that specification. recommendation precedence order applying the application role will cause this and all of the descendant elements of this element to be treated like appl...
ARIA: Complementary role - Accessibility
section has a role of complementary. if at all possible, prefer using it instead. labeling landmarks multiple landmarks if there is more than one complementary landmark role or <aside> element in a document, provide a label for each landmark using the aria-label attribute, or, if the aside has an appropriately descriptive title, point to it with the aria-labelledby attribute. this label will allow an assistive technology user to be able to quickly understand the purpose of each landmark. <aside aria-label="note about usage"> <!-- content --> </aside> ... <aside id="sidebar" aria-label="sponsors"> <!-- content --> </aside> redundant descriptions screen readers will announce the type of role the landmark is. because of this, you do not need to describe what the landmark is in its l...
...ers will announce the type of role the landmark is. because of this, you do not need to describe what the landmark is in its label. for example, a declaration of role="complementary" with an of aria-label="sidebar" may be announced redundantly as, "complementary sidebar". added benefits certain technologies such as browser extensions can generate lists of all landmark roles present on a page, allowing non-screen reader users to also quickly identify and navigate to large sections of the document. landmarks browser extension specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'aria: complementary role' in that specification. recommendation wai-aria authoring practicesthe definition of 'complementary ...
ARIA: contentinfo role - Accessibility
dant of the <body> element. mega-footers do not nest additional <footer> elements or contentinfo landmarks inside of the document's footer. use other content sectioning elements instead. labeling landmarks multiple landmarks if there is more than one contentinfo landmark role or <footer> element in a document, provide a label with the aria-label attribute for each landmark. this label will allow assitive technology users to quickly understand the purpose of each landmark. <body> ... <article> <h2>everyday pad thai</h2> <!-- article content --> <footer aria-label="everyday pad thai metadata"> <p>posted on <time datetime="2018-09-23 12:17">may 16</time> by <a href="#">lisa</a>.</p> </footer> </article> ... <footer aria-label="footer"> <!-- footer co...
...nt will automatically communicate a section has a role of contentinfo (save for a known issue in voiceover). if at all possible, prefer using <footer> instead. note that a footer element nested within an article, aside, main, nav, or section is not considered contentinfo. added benefits certain technologies such as browser extensions can generate lists of all landmark roles present on a page, allowing non-screen reader users to also quickly identify and navigate to large sections of the document. landmarks browser extension specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'contentinfo landmark role' in that specification. recommendation wai-aria authoring practicesthe definition of 'contentinfo l...
ARIA: form role - Accessibility
it should be declared on the html element that wraps the form elements. ideally, use the <form> element as the wrapping element and do not declare role="form". search if a form is used to search, you should use the more specialized role="search" value. labeling landmarks each <form> element and form role that needs to be exposed as a landmark must be given an accessible name. this name will allow an assitive technology user to be able to quickly understand the purpose of the form landmark. use an aria-labelledby, aria-label or title on the same element that was given the role="form" to provide it an accessible name. using role="form" <div role="form" id="gift-cards" aria-label="purchase a gift card"> <!-- form content --> </div> redundant descriptions screen readers will announce ...
...ation of role="form" with an of aria-label="contact form" may be announced redundantly as, "contact form form". best practices prefer html using the <form> element will automatically communicate a section has a role of form. if at all possible, prefer using it instead. added benefits certain technologies such as browser extensions can generate lists of all landmark roles present on a page, allowing non-screen reader users to also quickly identify and navigate to large sections of the document. landmarks browser extension specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'aria form role' in that specification. recommendation wai-aria authoring practicesthe definition of 'role form' in...
ARIA: Main role - Accessibility
<h1>active <code>main</code> element</h1> <!-- content --> </main <main hidden> <h1>hidden <code>main</code> element</h1> <!-- content --> </main> best practices prefer html using the <main> element will automatically communicate a section has a role of main. if at all possible, prefer using it instead. skip navigation skip navigation, also known as "skipnav", is a technique that allows an assistive technology user to quickly bypass large sections of repeated content (main navigation, info banners, etc.). this allows the user to access the main content of the page faster. adding an id attribute to the element with a declaration of role="main" allows it to be a target of a skip navigation link. <body> <a href="#main-content">skip to main content</a> <!-- navigation and he...
...ws it to be a target of a skip navigation link. <body> <a href="#main-content">skip to main content</a> <!-- navigation and header content --> <div id="main-content" role="main"> <!-- main page content --> </div> </body> webaim: "skip navigation" links added benefits certain technologies such as browser extensions can generate lists of all landmark roles present on a page, allowing non-screen reader users to also quickly identify and navigate to large sections of the document. landmarks browser extension specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'aria navigtion role' in that specification. recommendation wai-aria authoring practicesthe definition of 'navigation landmark...
ARIA: Mark role - Accessibility
the mark landmark role semantically denotes html elements containing text that is marked/highlighted for reference purposes. this is semantically equivalent to the html <mark> element. if possible, you should use this element instead. examples in the following example we have a document section that has been commented. the commented section is marked up using <span role="mark">. ...
...le semantically denotes html elements containing text that is marked/highlighted for reference purposes. this is semantically equivalent to the html <mark> element. if possible, you should use this element instead. examples in the following example we have a document section that has been commented. the commented section is marked up using <span role="mark">. ...
ARIA: Navigation Role - Accessibility
difficult to understand the overall layout of the page. best practices prefer html using the <nav> element will automatically communicate a section has a role of navigation. if at all possible, prefer using it instead. labeling landmarks multiple landmarks if there is more than one navigation landmark role or <nav> element in a document, provide a label for each landmark. this label will allow an assitive technology user to be able to quickly understand the purpose of each landmark. <div id="main-nav" role="navigation" aria-label="main"> <!-- content --> </div> ... <nav id="footer-nav" aria-label="footer"> <!-- content --> </nav> repeated landmarks if a navigation landmark role or <nav> element in a document is repeated in a document, and both landmarks have identical content...
...e the type of role the landmark is. because of this, you do not need to describe what the landmark is in its label. for example, a declaration of role="navigation" with an of aria-label="primary navigation" may be announced redundantly as, "primary navigation navigation". added benefits certain technologies such as browser extensions can generate lists of all landmark roles present on a page, allowing non-screen reader users to also quickly identify and navigate to large sections of the document. landmarks browser extension specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'aria navigtion role' in that specification. recommendation wai-aria authoring practicesthe definition of 'navigation landmark...
ARIA: search role - Accessibility
"noise" in screen readers, making it difficult to understand the overall layout of the page. best practices prefer html using the <form> element in conjunction with a declaration of role="search" will provide the largest amount of support. labeling landmarks multiple landmarks if there is more than one search landmark role in a document, provide a label for each landmark. this label will allow an assitive technology user to be able to quickly understand the purpose of each landmark. <form id="site-search" role="search" aria-label="sitewide"> <!-- search input --> </form> ... <form id="page-search" role="search" aria-label="on this page"> <!-- search input --> </form> repeated landmarks if a search landmark role in a document is repeated in a document, and both landmarks have ...
...s will announce the type of role the landmark is. because of this, you do not need to describe what the landmark is in its label. for example, a declaration of role="search" with an of aria-label="sitewide search" may be announced redundantly as, "sitewide search search". added benefits certain technologies such as browser extensions can generate lists of all landmark roles present on a page, allowing non-screen reader users to also quickly identify and navigate to large sections of the document. landmarks browser extension specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'aria search role' in that specification. recommendation wai-aria authoring practicesthe definition of 'aria search role' in t...
ARIA: switch role - Accessibility
ion. this prevents elements that are used to construct the switch from being interacted with individually by assistive technologies. text in these elements remains visible to the user agent and may be read or otherwise delivered to the user, unless it's expressly hidden using display: none or aria-hidden="true". the assistive technology, if it supports the switch role, responds by doing the following: screen readers should announce the element as a switch, optionally providing instructions as to how to activate the switch. there are 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 sw...
...ple 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" class="switch"> <span>off</span> <span>on</span> </button> <label for="speakerpower" class="switch">speaker power</label> javascript this javascript code defines and applies a function to handle click events on switch widgets. the function changes the aria-checked attribute from true t...
ARIA: table role - Accessibility
</div> </div> </div> description an element with role="table" is a static tabular structure with rows containing cells. the cells are not focusable or selectable, though widgets within individual cells of the table can be interactive. using a native html table element whenever possible is strongly encouraged. if a table maintains a selection state, has two-dimensional navigation, or allows the user to rearrange cell order use grid or treegrid instead. to create an aria table, add role="table" to the container element. within that container, each row has role="row" set and contains child cells. each cell has a role of either columnheader, rowheader, or simply cell. rows can be children of the table or within a rowgroup. the table caption can be defined via aria-labelledby or ari...
...o simply use the <table> element, along with all the related semantic elements and attributes that are all supported by all assistive technologies. to create an interactive widget that has a tabular structure, use the grid pattern instead. if the interaction provides for the selection state of individual cells, if left to right and top to bottom navigation is provided, or if the user interface allows the rearranging of cell order or otherwise changing individual cell order such as through drag and drop, use grid or treegrid instead. note: using a native html table element whenever possible is strongly encouraged. associated wai-aria roles, states, and properties role="rowgroup" an optional child of the table, the row group encapsulates a group of rows, similar to thead, tbody, and tf...
ARIA: button role - Accessibility
pressed" or "mute toggle button not pressed" depending on the value of aria-pressed. if the design were to call for the button label to change from "mute" to "unmute," a toggle button would not be appropriate, so the the aria-pressed attribute would be omitted. keyboard interactions key function enter activates the button. space activates the button following button activation, focus is set depending on the type of action the button performs. for example, if clicking the button opens a dialog, the focus should move to the dialog. if the button closes a dialog, focus should returns to the button that opened the dialog unless the function performed in the dialog context logically leads to a different element. if the button alters the current context,...
...inks are expected to be triggered using the enter key. in other words, when links are used to behave like buttons, adding role="button" alone is not sufficient. it will also be necessary to add a key event handler that listens for the space key in order to be consistent with native buttons. when the button role is used, screen readers announce the element as a button, generally saying "click" followed by the button's accessible name. the accessible name is either the content of the element or the value of an aria-label or element referenced by an aria-labelledby attribute, or description, if included. best practices if a link performs the action of a button, giving the element role="button" helps assistive technology users understand the function of the element. however, a better solution...
Web applications and ARIA FAQ - Accessibility
cript toolkits, and applications now support 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...
...se tools often had partial or buggy aria implementations. for notes on jaws support for aria as of jaws 10, see this article from the paciello group: jaws support for aria. javascript toolkits aria roles, states, and properties have been added to a number of popular javascript user interface toolkits, including: dojo/dijit jquery ui fluid 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 b...
Accessibility Information for Web Authors - Accessibility
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. ...
...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 brightness difference? color contrast analyzer is an excellent tool for such task. effective color cont...
Keyboard-navigable JavaScript widgets - Accessibility
e order. to do this, authors can set tabindex to any positive number. warning: avoid using positive values for tabindex. elements with a positive tabindex are put before the default interactive elements on the page, which means page authors will have to set (and maintain) tabindex values for all focusable elements on the page whenever they use one or more positive values for tabindex. the following table describes tabindex behavior in modern browsers: tabindex attribute focusable with mouse or javascript via element.focus() tab navigable not present follows the platform convention of the element (yes for form controls, links, etc.). follows the platform convention of the element. negative (i.e. tabindex="-1") yes no; author must focus the ele...
...ids, or tree views, the parent element should be in the tab order (tabindex="0"), and each descendent choice/tab/cell/row should be removed from the tab order (tabindex="-1"). users should be able to navigate the descendent elements using arrow keys. (for a full description of the keyboard support that is normally expected for typical widgets, see the wai-aria authoring practices.) the example below shows this technique used with a nested menu control. once keyboard focus lands on the containing <ul> element, the javascript developer must programmatically manage focus and respond to arrow keys. for techniques for managing focus within widgets, see "managing focus inside groups" below. example 2: a menu control using tabindex to control keyboard access <ul id="mb1" tabindex="0"> <li id="m...
Mobile accessibility checklist - Accessibility
o a single orientation, such as portrait or landscape, unless essential. wcag 2.1: orientation examples of when an orientation is esssential is a piano application or a bank cheque. general guidelines an app title must be provided. ...
... an app title must be provided. headings must not break hierarchical structure <h1>top level heading</h1> <h2>secondary heading</h2> <h2>another secondary heading</h2> <h3>low level heading</h3> aria landmark roles should be used to describe an app or document structure, such as banner, complementary, contentinfo, main, navigation, search. ...
Understanding the Web Content Accessibility Guidelines - Accessibility
ason, we have summarised the practical steps you need to take to satisfy the different recommendations, with further links to more details where required. the four principles wcag is broadly broken down into four principles — major things that web content must be to be considered accessible (see understanding the four principles of accessibility for the wcag definitions). each of the links below will take you to pages that further expand on these areas, giving you practical advice on how to write your web content so it conforms to the success criteria outlined in each of the wcag 2.0 and 2.1 guidelines that further sub-divides each principle. perceivable: users must be able to perceive it in some way, using one or more of their senses. operable: users must be able to control ui eleme...
...s an official recommendation on 05 june 2018. the european union (eu) adopted wcag 2.1 as the digital accessibility standard in september 2018. w3c published a press release wcag 2.1 adoption in europe. wcag 2.1 includes: all of wcag 2.0 (verbatim, word-for-word) 17 new success criteria at the a / aa / aaa levels primarily addressing user needs in these areas: mobile accessibility low vision cognitive read more about wcag 2.1: deque: wcag 2.1: what is next for accessibility guidelines tpg: web content accessibility guidelines (wcag) 2.1 legal standing this guide is intended to provide practical information to help you build better, more accessible websites. however, we are not lawyers, and none of this constitutes legal advice. if you are worried ab...
-moz-orient - CSS: Cascading Style Sheets
values inline the element is rendered in the same direction as the axis of the text: horizontally for horizontal writing modes, vertically for vertical writing modes. block the element is rendered orthogonally to the axis of the text: vertically for horizontal writing modes, horizontal for vertical writing modes. horizontal the element is rendered horizontally. ...
...des. horizontal the element is rendered horizontally. vertical the element is rendered vertically. formal definition initial valueinlineapplies toany element; it has an effect on progress and meter, but not on <input type="range"> or other elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax inline | block | horizontal | vertical examples html <p> the following progress meter is horizontal (the default): </p> <progress max="100" value="75"></progress> <p> the following progress meter is vertical: </p> <progress class="vert" max="100" value="75"></progress> css .vert { -moz-orient: vertical; width: 16px; height: 150px; } result specifications not part of any standard. though submitted to the w3c, with positive initial feedback, this ...
-webkit-border-before - CSS: Cascading Style Sheets
corresponds to the border-top, border-right, border-bottom, or border-left property depending on the values defined for writing-mode, direction, and text-orientation. it relates to -webkit-border-after, -webkit-border-start, and -webkit-border-end, which define the other borders of the element. this property is on the standard track as border-block-start. ...
... ...
-webkit-box-reflect - CSS: Cascading Style Sheets
the -webkit-box-reflect css property lets you reflect the content of an element in one specific direction. /* direction values */ -webkit-box-reflect: above; -webkit-box-reflect: below; -webkit-box-reflect: left; -webkit-box-reflect: right; /* offset value */ -webkit-box-reflect: below 10px; /* mask value */ -webkit-box-reflect: below 0 linear-gradient(transparent, white); /* global values */ -webkit-box-reflect: inherit; -webkit-box-reflect: initial; -webkit-box-reflect: unset; note: this feature is not intended to be used by web sites. to achieve reflection on the web, the standard way is to use the css element() function. syntax values above, below, right, left are keywords indicating in which direction the reflection is to happen. <length> indicates the size of th...
...ss element() function. syntax values above, below, right, left are keywords indicating in which direction the reflection is to happen. <length> indicates the size of the reflection. <image> describes the mask to be applied to the reflection. ...
:-moz-ui-invalid - CSS: Cascading Style Sheets
if the control has focus, and the value was valid (including empty) when it gained focus, do not apply the pseudo-class. if the control has focus, and the value was invalid when it gained focus, re-validate on every keystroke. ...
...th it, the validity styling is changed only when the user shifts focus to another control. however, if the user is trying to correct a previously-flagged value, the control shows immediately when the value becomes valid. required items have the pseudo-class applied only if the user changes them or attempts to submit an unchanged valid value. by default, gecko applies a style that creates a red "glow" (using the box-shadow property) around items, which have this pseudo-class applied. see the :invalid pseudo-class for an example that shows how to override the default style. the specification for :user-invalid is still in progress. syntax syntax not found in db! specifications specification status comment selectors level 4the definition of ':user-invalid' in that...
::-moz-range-progress - CSS: Cascading Style Sheets
note: using ::-moz-range-progress with anything but an <input type="range"> doesn't match anything and has no effect. ...
... note: using ::-moz-range-progress with anything but an <input type="range"> doesn't match anything and has no effect. ...
::-webkit-meter-suboptimum-value - CSS: Cascading Style Sheets
syntax ::-webkit-meter-suboptimum-value examples this example will only work in browsers based on webkit or blink. ...
... syntax ::-webkit-meter-suboptimum-value examples this example will only work in browsers based on webkit or blink. ...
::-webkit-scrollbar - CSS: Cascading Style Sheets
the ::-webkit-scrollbar css pseudo-element affects the style of the scrollbar of an element. ::-webkit-scrollbar is only available in blink- and webkit-based browsers (e.g., chrome, edge, opera, safari, all browsers on ios, and others). css scrollbar selectors you can use the following pseudo elements to customize various parts of the scrollbar for webkit browsers: ::-webkit-scrollbar — the entire scrollbar. ::-webkit-scrollbar-button — the buttons on the scrollbar (arrows pointing upwards and downwards). ::-webkit-scrollbar-thumb — the draggable scrolling handle. ::-webkit-scrollbar-track — the track (progress bar) of the scrollbar. ::-webkit-scrollbar-track-piece — the part of the track (progress bar) not covered by the handle. ::-webkit-scrollbar-corner — the b...
...d by the handle. ::-webkit-scrollbar-corner — the bottom corner of the scrollbar, where both horizontal and vertical scrollbars meet. ::-webkit-resizer — the draggable resizing handle that appears at the bottom corner of some elements. ...
::backdrop - CSS: Cascading Style Sheets
dialog::backdrop { background: rgba(255,0,0,.25); } all full-screen elements are placed in a last-in/first out (lifo) stack in the top layer, which is a special layer in the viewport which is always rendered last (and therefore on top) before drawing the viewport's contents to the screen. the ::backdrop pseudo-element makes it possible to obscure, style, or completely hide everything located below the element when it's the topmost one in the top layer. ::backdrop neither inherits from nor is inherited by any other elements. no restrictions are made on what properties apply to this pseudo-element. syntax ::backdrop examples styling the backdrop for full-screen video in this example, the backdrop style used when a video is shifted to full-screen mode is configured to be a grey-blue col...
...nt. syntax ::backdrop examples styling the backdrop for full-screen video in this example, the backdrop style used when a video is shifted to full-screen mode is configured to be a grey-blue color rather than the black it defaults to in most browsers. video::backdrop { background-color: #448; } the resulting screen looks like this: note the dark grey-blue letterbox effect above and below where the backdrop is visible. normally that area is black, but its appearance has been altered by the css above. you can see this example in action or view or remix the code on glitch. specifications specification status comment fullscreen apithe definition of '::backdrop' in that specification. living standard initial definition. ...
::before (:before) - CSS: Cascading Style Sheets
Web › CSS › ::before
here are no icons used, and the check-mark is actually the ::before that has been styled in css. go ahead and get some stuff done. result special characters as this is css; not html, you can not use markup entities in content values. if you need to use a special character, and can not enter it literally into your css content string, use a unicode escape sequence, consisting of a backslash followed by the hexadecimal unicode value. html <ol> <li>crack eggs into bowl</li> <li>add milk</li> <li>add flour</li> <li aria-current='step'>mix thoroughly into a smooth batter</li> <li>pour a ladleful of batter onto a hot, greased, flat frying pan</li> <li>fry until the top of the pancake loses its gloss</li> <li>flip it over and fry for a couple more minutes</li> <li>serve with yo...
...rent='step']::after { content: " \21e6"; /* hexadecimal for unicode leftwards white arrow*/ display: inline; } result specifications specification status comment css pseudo-elements level 4the definition of '::before' in that specification. working draft no significant changes to the previous specification. css animations working draft allows animations on properties defined on pseudo-elements. selectors level 3the definition of '::before' in that specification. recommendation introduces the two-colon syntax. css level 2 (revision 1)the definition of '::before' in that specification. recommendation initial definition, using the one-colon syntax ...
::cue-region - CSS: Cascading Style Sheets
the ::cue-region css pseudo-element matches webvtt cues within a selected element. this can be used to style captions and other cues in media with vtt tracks. ::cue-region { color: yellow; font-weight: bold; } the properties are applied to the entire set of cues as if they were a single unit. the only exception is that background and its shorthand properties apply to each cue individually, to avoid creating boxes and obscuring unexpectedly large areas of the media. ...
... the properties are applied to the entire set of cues as if they were a single unit. the only exception is that background and its shorthand properties apply to each cue individually, to avoid creating boxes and obscuring unexpectedly large areas of the media. ...
::first-line (:first-line) - CSS: Cascading Style Sheets
ote that the length of the first line depends on many factors, including the width of the element, the width of the document, and the font size of the text. /* selects the first line of a <p> */ p::first-line { color: red; } css3 introduced the ::first-line notation (with two colons) to distinguish pseudo-classes from pseudo-elements. browsers also accept :first-line, introduced in css2. ...
...warning: do not use these */ /* many properties are invalid in ::first-line pseudo-elements */ margin-left: 20px; text-indent: 20px; } result specifications specification status comment css pseudo-elements level 4the definition of '::first-line' in that specification. working draft defines more strictly where ::first-letter can occur. generalizes allowed properties to typesetting, text decoration, and inline layout properties and opacity. defines the inheritance of ::first-letter. css text decoration module level 3the definition of 'text-shadow with ::first-line' in that specification. candidate recommendation allows the use of text-shadow with ::first-letter. selectors level 3the definition of '::first-line' in that...
::selection - CSS: Cascading Style Sheets
the ::selection css pseudo-element applies styles to the part of a document that has been highlighted by the user (such as clicking and dragging the mouse across text). ::selection { background-color: cyan; } allowable properties only certain css properties can be used with ::selection: color background-color cursor caret-color outline and its longhands text-decoration and its associated properties text-emphasis-color text-shadow in particular, background-image is ignored. syntax /* legacy firefox syntax (version 61 and below) */ ::-moz-selection ::selection examples html this text has special styles when you highlight it. <p>also try selecting text in this paragraph.</p> css ::-moz-selection { color: gold; background-color: red; } p::-moz-selection { colo...
...etic reasons — users can customize them to suit their needs. for people experiencing 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: c...
::slotted() - CSS: Cascading Style Sheets
Web › CSS › ::slotted
in this demo we use a simple template with three slots: <template id="person-template"> <div> <h2>personal id card</h2> <slot name="person-name">name missing</slot> <ul> <li><slot name="person-age">age missing</slot></li> <li><slot name="person-occupation">occupation missing</slot></li> ...
... 'p { margin: 10px 0; }' + '::slotted(*) { color: gray; font-family: sans-serif; } '; shadowroot.appendchild(style); shadowroot.appendchild(templatecontent.clonenode(true)); } }) you'll see that when filling the style element with content, we select all slotted elements (::slotted(*)) and give them a different font and color. this allows them to stand out better next to the slots that haven't been successfully filled. the element looks like this when inserted into the page: <person-details> <p slot="person-name">dr. shazaam</p> <span slot="person-age">immortal</span> <span slot="person-occupation">superhero</span> </person-details> specifications specification status comment css scoping modu...
:defined - CSS: Cascading Style Sheets
Web › CSS › :defined
tandard element built in to the browser, and custom elements that have been successfully defined (i.e. with the customelementregistry.define() method). /* selects any defined element */ :defined { font-style: italic; } /* selects any instance of a specific custom element */ simple-custom:defined { display: block; } syntax :defined examples hiding elements until they are defined the following snippets are taken from our defined-pseudo-class demo (see it live also). in this demo we define a very simple trivial custom element: customelements.define('simple-custom', class extends htmlelement { constructor() { super(); let divelem = document.createelement('div'); divelem.textcontent = this.getattribute('text'); let shadowroot = this.attachshadow({mode:...
....createelement('div'); divelem.textcontent = this.getattribute('text'); let shadowroot = this.attachshadow({mode: 'open'}) .appendchild(divelem); } }) then insert a copy of this element into the document, along with a standard <p>: <simple-custom text="custom element example text"></simple-custom> <p>standard paragraph example text</p> in the css we first include the following rules: // give the two elements distinctive backgrounds p { background: yellow; } simple-custom { background: cyan; } // both the custom and the built-in element are given italic text :defined { font-style: italic; } then provide the following two rules to hide any instances of our custom element that are not defined, and display instances that are defined as block level elements: s...
:is() (:matches(), :any()) - CSS: Cascading Style Sheets
Web › CSS › :is
), including older versions of chrome, firefox, and safari. :any() works in exactly the same way as :matches()/:is(), except that it requires vendor prefixes and doesn't support complex selectors. ...
...e.log('your browser doesn\'t support :is(), :matches(), or :any()'); } } } } matcheditems.foreach(applyhandler); function applyhandler(elem) { elem.addeventlistener('click', function(e) { alert('this paragraph is inside a ' + e.target.parentnode.nodename); }); } simplifying list selectors the :is() pseudo-class can greatly simplify your css selectors. ...
@charset - CSS: Cascading Style Sheets
Web › CSS › @charset
d, only the first one is used, and it cannot be used inside a style attribute on an html element or inside the <style> element where the character set of the html page is relevant. @charset "utf-8"; this at-rule is useful when using non-ascii characters in some css properties, like content. as there are several ways to define the character encoding of a style sheet, the browser will try the following methods in the following order (and stop as soon as one yields a result) : the value of the unicode byte-order character placed at the beginning of the file. the value given by the charset attribute of the content-type: http header or the equivalent in the protocol used to serve the style sheet. the @charset css at-rule. use the character encoding defined by the referring document: the c...
...referring document: the charset attribute of the <link> element. 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, wron...
@counter-style - CSS: Cascading Style Sheets
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 to be appended or prepended to the ...
...s. how the symbols are used to construct the marker representation is up to the algorithm specified in the system descriptor. for example, if the system specified is fixed, then each of the n symbols specified in the descriptor will be used to represent the first n counter symbols. once the specified set of symbols have exhausted, the fallback style will be used for the rest of the list. the below @counter-style rule uses images instead of character symbols. image values for symbols is currently an 'at risk' feature, and is not implemented in any browser. @counter-style winners-list { system: fixed; symbols: url(gold-medal.svg) url(silver-medal.svg) url(bronze-medal.svg); suffix: " "; } additive-symbols while the symbols specified in the symbols descriptor is used for constru...
font-variation-settings - CSS: Cascading Style Sheets
if the <string> has more or fewer characters or contains characters outside the u+20 - u+7e codepoint range, the whole property is invalid. ...
...e default settings */ font-variation-settings: normal; /* set values for opentype axis names */ font-variation-settings: "xhgt" 0.7; values normal text is laid out using default settings. <string> <number> when rendering text, the list of opentype axis names is passed to the text layout engine to enable or disable font features. each setting is always a <string> of 4 ascii characters, followed by a <number> indicating the axis value. if the <string> has more or fewer characters or contains characters outside the u+20 - u+7e codepoint range, the whole property is invalid. the <number> can be fractional or negative. formal definition related at-rule@font-faceinitial valuenormalcomputed valueas specified formal syntax normal | [ <string> <number> ]# examples setting font weight a...
-ms-high-contrast - CSS: Cascading Style Sheets
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 when the system is placed in high contrast mode with a black-on-white color variation. whi...
...n. black-on-white indicates that the subsequent styling rules will be applied when the system is placed in high contrast mode with a black-on-white color variation. white-on-black indicates that the subsequent styling rules will be applied when the system is placed in high contrast mode with a white-on-black color variation. formal syntax syntax not found in db! examples the following declarations will match applications that are being displayed in high contrast mode with any color variation, a black-on-white color variation, and a white-on-black color variation, respectively. @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'); } } @m...
-webkit-device-pixel-ratio - CSS: Cascading Style Sheets
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) { ... } /* 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...
...esolution: 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 standard initial standardization safari css reference 'media query extensions' in that document. non-standard unofficial documentation initial documentation ...
forced-colors - CSS: Cascading Style Sheets
not being forced into a limited palette. active indicates that forced colors mode is active. the browser provides the color palette to authors through the css system color keywords and, if appropriate, it triggers the appropriate value of prefers-color-scheme so that authors can adapt the page. usage notes properties affected by forced-color mode in forced colors mode, the values of the following properties are treated as if they have no author-level values specified. that is, user-specified values (if any) or browser-specified values are used instead. color fill stroke text-decoration-color text-emphasis-color border-color outline-color column-rule-color scrollbar-color -webkit-tap-highlight-color box-shadow text-shadow you can use system color keywords with any proper...
...ith the restricted color palette available in forced colors mode. 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 system in use. examples note: no browser currently implements this feature so the following example will not work. this example has an annoying color palette by default. this example does not take advantage of the colors provided by the user agent. html <div class="colors">weird color box</div> css .colors { background-color: red; color: grey; } @media (forced-colors: active) { .colors { background-color: white; color: black; } } result specifications ...
inverted-colors - CSS: Cascading Style Sheets
the inverted-colors css media feature can be used to test whether the user agent or underlying os is inverting colors. syntax the inverted-colors feature is specified as a keyword value chosen from the list below. none colors are displayed normally. inverted all pixels within the displayed area have been inverted. examples html <p>if you're using inverted colors, this text should be blue on white (the inverse of yellow on black). ...
...area have been inverted. examples html <p>if you're using inverted colors, this text should be blue on white (the inverse of yellow on black). if you're not, it should be red on light gray.</p> <p>if the text is gray, your browser doesn't support the `inverted-colors` media feature.</p> css p { color: gray; } @media (inverted-colors: inverted) { p { background: black; color: yellow; } } @media (inverted-colors: none) { p { background: #eee; color: red; } } result specifications specification status comment media queries level 5the definition of 'inverted-colors' in that specification. editor's draft ...
orientation - CSS: Cascading Style Sheets
f the viewport (or the page box, for paged media). note: this feature does not correspond to device orientation. opening the soft keyboard on many devices in portrait orientation will cause the viewport to become wider than it is tall, thereby causing the browser to use landscape styles instead of portrait. syntax the orientation feature is specified as a keyword value chosen from the list below. ...
... candidate recommendation no change. ...
prefers-contrast - CSS: Cascading Style Sheets
the prefers-contrast css media feature is used to detect if the user has requested that the web content is presented with a higher (or lower) contrast. syntax no-preference indicates that the user has made no preference known to the system. this keyword value evaluates as false in a boolean context. more indicates that user has notified the system that they prefer an interface that has a higher level of contrast. less indicates that user has notified the system that they prefer an interface that has a lower level of contrast. user preferences various operating systems do support such preferences and user agents are likely to rely on the settings provided by the operating system. examples this example has an annoying low contrast by default. html <div class="contrast...
...s a higher level of contrast. less indicates that user has notified the system that they prefer an interface that has a lower level of contrast. user preferences various operating systems do support such preferences and user agents are likely to rely on the settings provided by the operating system. examples this example has an annoying low contrast by default. html <div class="contrast">low contrast box</div> css .contrast { width: 100px; height: 100px; outline: 2px dashed black; } @media (prefers-contrast: high) { .contrast { outline: 2px solid black; } } result specifications specification status comment media queries level 5the definition of 'prefers-contrast' in that specification. editor's draft initial definition. ...
Attribute selectors - CSS: Cascading Style Sheets
name of attr. [attr=value] represents elements with an attribute name of attr whose value is exactly value. [attr~=value] represents elements with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value. [attr|=value] represents elements with an attribute name of attr whose value can be exactly value or can begin with value immediately followed by a hyphen, - (u+002d). it is often used for language subcode matches. [attr^=value] represents elements with an attribute name of attr whose value is prefixed (preceded) by value. [attr$=value] represents elements with an attribute name of attr whose value is suffixed (followed) by value. [attr*=value] represents elements with an attribute name of attr whose value contains at least one ...
...cification requires the type attribute to be matched case-insensitively due to it primarily being used in the <input> element, trying to use attribute selectors to with the type attribute of an ordered list doesn't work without the case-sensitive modifier. css /* list types require the case sensitive flag due to a quirk in how html treats the type attribute. */ ol[type="a"] { list-style-type: lower-alpha; background: red; } ol[type="a" s] { list-style-type: lower-alpha; background: lime; } ol[type="a" s] { list-style-type: upper-alpha; background: lime; } html <ol type="a"> <li>example list</li> </ol> result specifications specification status comment selectors level 4the definition of 'attribute selectors' in that specification. working...
CSS Animations tips and tricks - CSS: Cascading Style Sheets
ant (the style of the "run" button itself) isn't shown here, for brevity. .runbutton { cursor: pointer; width: 300px; border: 1px solid black; font-size: 16px; text-align: center; margin-top: 12px; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; font: 14px "open sans", "arial", sans-serif; } @keyframes colorchange { 0% { background: yellow } 100% { background: blue } } .box { width: 100px; height: 100px; border: 1px solid black; } .changing { animation: colorchange 2s; } there are two classes here. the "box" class is the basic description of the box's appearance, without any animation information included. the animation details are included in the "changing" class, which says that the @keyframes named "colorchange" sho...
...ou have to try a different approach. the main tricks are: make your animation as self-contained as possible. this means you should not rely on animation-direction: alternate. instead you should explicitly write a keyframe animation that goes through the full animation in one forward repetition. use javascript and clear the animation being used when the animationiteration event fires. ...
Using multiple backgrounds - CSS: Cascading Style Sheets
he first background you provide on top and the last background listed in the back. only the last background can include a background color. specifying multiple backgrounds is easy: .myclass { background: background1, background 2, ..., backgroundn; } you can do this with both the shorthand background property and the individual properties thereof except for background-color. that is, the following background properties can be specified as a list, one per background: background, background-attachment, background-clip, background-image, background-origin, background-position, background-repeat, background-size. example in this example, three backgrounds are stacked: the firefox logo, an image of bubbles, and a linear gradient: html <div class="multi-bg-example"></div> css .multi-bg-...
...each subsequent sub-property (background-repeat and background-position) applies to the corresponding backgrounds. so the first listed value for background-repeat applies to the first (frontmost) background, and so forth. ...
Using URL values for the cursor property - CSS: Cascading Style Sheets
gecko 1.8 supports url values for the css cursor property on windows and linux. mac support was added in gecko 2 (firefox 4). this allows specifying arbitrary images as mouse cursors — any image format supported by gecko can be used. syntax the basic (css 2.1) syntax for this property is: cursor: [ <url> , ]* <keyword> this means that zero or more urls may be specified (comma-separated), which must be followed by one of the keywords defined in the css specification, such as auto or pointer. for example, the following value would be allowed: cursor: url(foo.cur), url(http://www.example.com/bar.gif), auto; this will first try loading foo.cur. if that file does not exist or is not valid for some other reason, bar.gif is tried, and if that can't be used either, auto will be used. suppo...
...if none are specified, the coordinates of the hotspot are read from the file itself (for cur and xbm files) or are set to the top left corner of the image. ...
Box alignment in grid layout - CSS: Cascading Style Sheets
e direction runs horizontally. should you be in a vertical writing mode the inline axis will run vertically. to align things on the inline axis you use the properties that start with justify-, justify-content, justify-items and justify-self. the block axis crosses the inline axis in the direction that blocks are displayed down the page — for example paragraphs in english are displayed one below the other vertically. this, therefore is the block dimension. to align things on the block axis you use the properties that start with align-, align-content, align-items and align-self. self alignment justify-self align-self place-self justify-items align-items place-items these properties deal with aligning the item inside the grid area it is placed into. the properties align-items...
...otal less than the total width of the grid container. gap and legacy grid-gap properties row-gap column-gap gap grid-row-gap grid-column-gap grid-gap the grid specification originally contained the definition for the properties grid-row-gap, grid-column-gap and grid-gap. these have since been moved into the box alignment specification and renamed to row-gap, column-gap, and gap. this allows them to be used for other layout methods where a gap between items makes sense. the updated properties have not yet been implemented in all browsers. therefore, to use the gap properties in grid layout, you should use the grid-row-gap, grid-column-gap and grid-gap versions to ensure full compatibility. you could double up the properties and use both as you would for vendor prefixes. reference ...
Mastering margin collapsing - CSS: Cascading Style Sheets
recommendation initial definition. ...
... recommendation initial definition. ...
Basic Concepts of Multicol - CSS: Cascading Style Sheets
mns to create a multicol container you must use at least one of the column-* properties, these being column-count and column-width. the column-count property the column-count property specifies the number of columns that you would like the content to be displayed as. the browser will then assign the correct amount of space to each column box to create the requested number of columns. in the below example we use the column-count property to create three columns on the .container element. the content, including the children of .container is then split between the three columns. in the above example the content is wrapped in paragraph p tags with default styling. therefore, there is a margin above each paragraph. you can see how this margin causes the first line of text to be pushed down...
...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 space shared equally. using column-count and column-width together if you specify both properties on a multicol container then column-count will act as a maximum number of columns. therefore the behaviour as described for column-width will happen, until th...
CSS Flexible Box Layout - CSS: Cascading Style Sheets
css flexible box layout is a module of css that defines a css box model optimized for user interface design, and the layout of items in one dimension. in the flex layout model, the children of a flex container can be laid out in any direction, and can “flex” their sizes, either growing to fill unused space or shrinking to avoid overflowing the parent. both horizontal and vertical alignment of the children can be easily manipulated. basic example in the following example a container has been set to display: flex, which means that the three child items become flex items. the value of justify-content has been set to space-between in order to space the items out evenly on the main axis. an equal amount of space is placed between each item with the left and right items being flush with the ...
...between each item with the left and right items being flush with the edges of the flex container. you can also see that the items are stretching on the cross axis, due to the default value of align-items being stretch. the items stretch to the height of the flex container, making them each appear as tall as the tallest item. reference css properties flex flex-basis flex-direction flex-flow flex-grow flex-shrink flex-wrap order alignment properties the properties align-content, align-self, align-items and justify-content initially appeared in the flexbox specification, but are now defined in box alignment. the flexbox spec now refers to the box alignment specification for up to date definitions. also additional alignment properties are now defined in box alignment. justi...
CSS Grid Layout and Accessibility - CSS: Cascading Style Sheets
rom mark-up, however is it possible to go too far with this idea? is it possible that we could create an accessibility issue through our use of grids? re-ordering content in css grid layout we’ve already seen in these guides that grid gives us power to re-order the content of our page in various ways. we can use the order property, which will change how items auto-place. we can use grid-auto-flow: dense which will take items visually out of dom order. we can also position items using line-based placement of grid template areas, without considering their location in the source. the specification includes a section that covers reordering and accessibility. in the introduction to that section are details of what the specification expects browsers to do when the content is visually reordered...
...tic elements in order to make the layout work if you actually have to go into the document and do so! further reading there is not a lot of existing material regarding accessibility and css grid layout. many of the issues are similar to those raised regarding css flexbox, which also gives methods of reordering content with flex-direction and the order property. the concept of visual display following document source order is detailed in the wcag techniques for success criteria – technique c27. as a way to start thinking about these issues, as you use css grid layout i would suggest reading flexbox & the keyboard navigation disconnect from léonie watson. also the video of léonie’s presentation from ffconf is helpful to understand more about how screen readers work with the visual rep...
CSS Grid Layout - CSS: Cascading Style Sheets
of a control built from html primitives. like tables, grid layout 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: #d9480...
...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-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 gri...
CSS Motion Path - CSS: Cascading Style Sheets
with offset-path you can define a specific path of any shape you want. you then animate it along that path by animating offset-distance, and can choose to rotate it at any point using offset-rotate. ...
...with offset-path you can define a specific path of any shape you want. you then animate it along that path by animating offset-distance, and can choose to rotate it at any point using offset-rotate. ...
CSS Properties Reference - CSS: Cascading Style Sheets
for more css properties see the main css reference and mozilla css extensions. the reference articles also include examples on how to use all the properties. ...
...tterspacing line-height lineheight list-style liststyle list-style-image liststyleimage list-style-position liststyleposition list-style-type liststyletype margin margin margin-bottom marginbottom margin-left marginleft margin-right marginright margin-top margintop overflow overflow padding padding padding-bottom paddingbottom padding-left paddingleft padding-right paddingright padding-top paddingtop page-break-after pagebreakafter page-break-before pagebreakbefore position position stroke-dasharray strokedasharray stroke-dashoffset strokedashof...
Browser compatibility and Scroll Snap - CSS: Cascading Style Sheets
d firefox implementation of the specification, with the properties that are detailed in scroll snap points, you should update your code to use the new specification. this will ensure your scroll snapping works in all browsers which implement the specification, including firefox. if you do not do this your scroll snapping will no longer work in firefox 68 and up. ...
...scroll-snap-type property has become a longhand, so the old shorthand syntax like scroll-snap-type:mandatory will stop working can i use the old implementation as a fallback? if you have already used the old implementation as a fallback, or feel you want to support users of old firefox (or -webkit prefixed safari), then you can continue to use the old specification as outlined in the example below. in this initial example we have used the old specification alongside the current specification in order to make scroll snapping work in all browsers which support some form of scroll snapping. the example adds the scroll-snap-points-y and scroll-snap-destination properties, which are deprecated, to make scroll snapping work in firefox. we also added the scroll-snap-type property twice, once wi...
CSS selectors - CSS: Cascading Style Sheets
ax: a b example: div span will match all <span> elements that are inside a <div> element. child combinator the > combinator selects nodes that are direct children of the first element. syntax: a > b example: ul > li will match all <li> elements that are nested directly inside a <ul> element. general sibling combinator the ~ combinator selects siblings. this means that the second element follows the first (though not necessarily immediately), and both share the same parent. syntax: a ~ b example: p ~ span will match all <span> elements that follow a <p>, immediately or not. adjacent sibling combinator the + combinator selects adjacent siblings. this means that the second element directly follows the first, and both share the same parent. syntax: a + b example: h2 + p will match al...
...ily immediately), and both share the same parent. syntax: a ~ b example: p ~ span will match all <span> elements that follow a <p>, immediately or not. adjacent sibling combinator the + combinator selects adjacent siblings. this means that the second element directly follows the first, and both share the same parent. syntax: a + b example: h2 + p will match all <p> elements that directly follow an <h2>. column combinator the || combinator selects nodes which belong to a column. syntax: a || b example: col || td will match all <td> elements that belong to the scope of the <col>. pseudo pseudo classes the : pseudo allow the selection of elements based on state information that is not contained in the document tree. example: a:visited will match all <a> elements that have been...
Using CSS transforms - CSS: Cascading Style Sheets
this guide provides an introduction to using transforms. css transforms are implemented using a set of css properties that let you apply affine linear transformations to html elements. these transformations include rotation, skewing, scaling, and translation both in the plane and in the 3d space. only elements positioned by the box model can be transformed. as a rule of thumb, an element is positioned by the box model if it has display: block. ...
...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 perspective this example shows a cube with the perspective set at different positions. how quick the cube shrinks is defined by the perspective property. the smaller its value is, the deeper the perspective is. html the html below creates four copies of the same box, with the perspective set at different values. <table> <tbody> <tr> <th><code>perspective: 250px;</code> </th> <th><code>perspective: 350px;</code> </th> </tr> <tr> <td> <div class="container"> <div class="cube pers250"> <div class="face front">1</div> <div class="face back">...
Introducing the CSS Cascade - CSS: Cascading Style Sheets
Web › CSS › Cascade
ines 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 followed by !important, and by their origin. the cascade is in ascending order, which means that !important values from a user-defined style sheet have precedence over normal values originated from a user-agent style sheet: origin importance 1 user agent normal 2 user normal 3 author normal ...
...last one that is then selected: margin-left: 3px note that the declaration defined in the user css, though having a greater specificity, is not chosen as the cascade algorithm is applied before the specificity algorithm. specifications specification status comment css cascading and inheritance level 4 candidate recommendation added the revert keyword, which allows rolling a property back a cascade level. css cascading and inheritance level 3 candidate recommendation removed the override cascade origin, as it was never used in a w3c standard. css level 2 (revision 1)the definition of 'the cascade' in that specification. recommendation css level 1the definition of 'the cascade' in that specification. recommendation...
Comments - CSS: Cascading Style Sheets
Web › CSS › Comments
a css comment is used to add explanatory notes to the code or to prevent the browser from interpreting specific parts of the style sheet. by design, comments have no effect on the layout of a document. syntax comments can be placed wherever white space is allowed within a style sheet. they can be used on a single line, or traverse multiple lines. /* comment */ examples /* a one-line comment */ /* a comment which stretches over several lines */ /* the comment 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...
...t 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 ...
Layout and the containing block - CSS: Cascading Style Sheets
value other than static (fixed, absolute, relative, or sticky). if the position property is fixed, the containing block is established by the viewport (in the case of continuous media) or the page area (in the case of paged media). if the position property is absolute or fixed, the containing block may also be formed by the edge of the padding box of the nearest ancestor element that has the following: a transform or perspective value other than none a will-change value of transform or perspective a filter value other than none or a will-change value of filter (only works on firefox). a contain value of paint (e.g. contain: paint;) note: the containing block in which the root element (<html>) resides is a rectangle called the initial containing block. it has the dime...
...e height, top, and bottom properties compute percentage values from the height of the containing block. the width, left, right, padding, and margin properties compute percentage values from the width of the containing block. some examples the html code for all our examples is: <body> <section> <p>this is a paragraph!</p> </section> </body> only the css is altered in each instance below. example 1 in this example, the paragraph is statically positioned, so its containing block is <section> because it's the nearest ancestor that is a block container. <body> <section> <p>this is a paragraph!</p> </section> </body> body { background: beige; } section { display: block; width: 400px; height: 160px; background: lightgray; } p { width: 50%; /* == 400px * ...
Grid wrapper - CSS: Cascading Style Sheets
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. ...
... ...
CSS Layout cookbook - CSS: Cascading Style Sheets
item horizontally and vertically. flexbox, box alignment sticky footers creating a footer which sits at the bottom of the container or viewport when the content is shorter. css grid, flexbox split navigation a navigation pattern where some links are visually separated from the others. flexbox, margin breadcrumb navigation creating a list of links to allow the visitor to navigate back up through the page hierarchy. flexbox list group with badges a list of items with a badge to display a count. flexbox, box alignment pagination links to pages of content (such as search results). flexbox, box alignment card a card component, which displays in a grid of cards. grid layout grid wrapper for ali...
...y. flexbox list group with badges a list of items with a badge to display a count. flexbox, box alignment pagination links to pages of content (such as search results). flexbox, box alignment card a card component, which displays in a grid of cards. grid layout grid wrapper for aligning grid content within a central wrapper, while also allowing items to break out. css grid contribute a recipe as with all of mdn we would love you to contribute a recipe in the same format as the ones shown above. see this page for a template and guidelines for writing your own example. ...
Viewport concepts - CSS: Cascading Style Sheets
/* 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 flush against the top and bottom of the window. but what if we had pinched-zoomed on a tablet? what if a dynamic keybo...
... if a mobile screen has a width of 320px, a website might be rendered with a virtual viewport of 980px, and then it will be shrunk down to fit into the 320px space, which, depending on the design, is illegible for many if not everyone. to tell a mobile browser to use the viewport width instead of the default 980px as the width of the screen, developers can include a viewport meta tag, like the following: <meta name="viewport" content="width=device-width"> the width property controls the size of the viewport. 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 ...
animation-fill-mode - CSS: Cascading Style Sheets
e first relevant keyframe as soon as it is applied to the target, and retain this during the animation-delay period. the first relevant keyframe depends on the value of animation-direction: animation-direction first relevant keyframe normal or alternate 0% or from reverse or alternate-reverse 100% or to both the animation will follow the rules for both forwards and backwards, thus extending the animation properties in both directions. note: when you specify multiple comma-separated values on an animation-* property, they will be assigned to the animations specified in the animation-name property in different ways depending on how many there are. for more information, see setting multiple animation property values. formal...
...ormation, see setting multiple animation property values. formal definition initial valuenoneapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <single-animation-fill-mode>#where <single-animation-fill-mode> = none | forwards | backwards | both examples you can see the effect of animation-fill-mode in the following example. it demonstrates how, for an animation that runs for an infinite time, you can cause it to remain in its final state rather than reverting to the original state (which is the default). html <p>move your mouse over the gray box!</p> <div class="demo"> <div class="growsandstays">this grows and stays big.</div> <div class="grows">this just grows.</div> </div> css .demo { border-t...
background-attachment - CSS: Cascading Style Sheets
ps://github.com/mdn/interactive-examples and send us a pull request. syntax /* keyword values */ background-attachment: scroll; background-attachment: fixed; background-attachment: local; /* global values */ background-attachment: inherit; background-attachment: initial; background-attachment: unset; the background-attachment property is specified as one of the keyword values from the list below. values fixed the background is fixed relative to the viewport. even if an element has a scrolling mechanism, the background 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 pain...
... again. suddenly she came upon a little three-legged table, all made of solid glass; there was nothing on it except a tiny golden key, and alice's first thought was that it might belong to one of the doors of the hall; but, alas! either the locks were too large, or the key was too small, but at any rate it would not open any of them. ...
background-position-x - CSS: Cascading Style Sheets
left edge of the background position layer. center aligns the center of the background image with the center of the background position layer. right aligns the right edge of the background image with the right edge of the background position layer. <length> the offset of the given background image's left vertical edge from the background position layer's left vertical edge. (some browsers allow assigning the right edge for offset). <percentage> the offset of the given background image's horizontal position relative to the container. a value of 0% means that 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% horizo...
... html <div></div> css div { width: 300px; height: 300px; background-color: skyblue; background-image: url(https://media.prod.mdn.mozit.cloud/attachments/2020/07/29/17350/3b4892b7e820122ac6dd7678891d4507/...
background-position-y - CSS: Cascading Style Sheets
ion layer. center aligns the vertical center of the background image with the vertical center of the background position layer. bottom aligns the bottom edge of the background image with the bottom edge of the background position layer. <length> the offset of the given background image's horizontal edge from the corresponding background position layer's top horizontal edge. (some browsers allow assigning the bottom edge for offset). <percentage> the offset of the given background image's vertical position relative to the container. a value of 0% means 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% vertica...
... html <div></div> css div { width: 300px; height: 300px; background-color: skyblue; background-image: url(https://media.prod.mdn.mozit.cloud/attachments/2020/07/29/17350/3b4892b7e820122ac6dd7678891d4507/...
background-position - CSS: Cascading Style Sheets
in each example, the star is in a different position. the third example illustrates how to specify positions for two different background images within one element. html <div class="exampleone">example one</div> <div class="exampletwo">example two</div> <div class="examplethree">example three</div> css /* shared among all <div>s */ div { backgro...
...mment css backgrounds and borders module level 3the definition of 'background-position' in that specification. candidate recommendation adds support for multiple backgrounds and the four-value syntax. modifies the percentage definition to match implementations. css level 2 (revision 1)the definition of 'background-position' in that specification. recommendation allows for keyword values and <length> and <percentage> values to be mixed. css level 1the definition of 'background-position' in that specification. recommendation initial definition. 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 an...
background-repeat - CSS: Cascading Style Sheets
d as much as possible without clipping. the first and last images are pinned to either side of the element, and whitespace is distributed evenly between the images. the background-position property is ignored unless only one image can be displayed without clipping. the only case where clipping happens using space is when there isn't enough room to display one image. round as the allowed space increases in size, the repeated images will stretch (leaving no gaps) until there is room (space left >= half of the image width) for another one to be added. when the next image is added, all of the current ones compress to allow room. example: an image with an original width of 260px, repeated three times, might stretch until each repetition is 300px wide, and then another image will be...
...at-y; height: 144px; } result in this example, each list item is matched with a different value of background-repeat. specifications specification status comment css backgrounds and borders module level 3the definition of 'background-repeat' in that specification. candidate recommendation adds support for multiple background images, the two-value syntax allowing distinct repetition behavior for the horizontal and vertical directions, the space and round keywords, and for backgrounds on inline-level elements by precisely defining the background painting area. css level 2 (revision 1)the definition of 'background-repeat' in that specification. recommendation no significant changes. css level 1the definition of 'background-repeat'...
background - CSS: Cascading Style Sheets
erty sets all background style properties at once, such as color, image, origin and size, or repeat method. 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. ...
...ground: green; /* using a <bg-image> and <repeat-style> */ background: url("test.jpg") repeat-y; /* using a <box> and <background-color> */ background: border-box red; /* a single image, centered and scaled */ background: no-repeat center/80% url("../img/image.png"); the background property is specified as one or more background layers, separated by commas. the syntax of each layer is as follows: each layer may include zero or one occurrences of any of the following values: <attachment> <bg-image> <position> <bg-size> <repeat-style> the <bg-size> value may only be included immediately after <position>, separated with the '/' character, like this: "center/80%". the <box> value may be included zero, one, or two times. if included once, it sets both background-o...
<blend-mode> - CSS: Cascading Style Sheets
values normal the final color is the top color, regardless of what the bottom color is. the effect is like two opaque pieces of paper overlapping. ...
...org/files/8545/tr.png'); background-blend-mode: luminosity; } description for each pixel among the layers to which it is applied, a blend mode takes the colors of the foreground and the background, perfoms a calculation on them, and returns a new color value. changes between blend modes are not interpolated. any change occurs immediately. examples blend mode comparison in the following example, we have a <div> with two background images set on it — a firefox logo on top of a linear gradient. below it we have a provided a <select> menu that allows you to change the background-blend-mode applied to the <div>, allowing you to compare the different blend mode effects. html <div></div> <p>choose a blend-mode:</p> <select> <option selected>normal</option> <option>multiply<...
border-block-color - CSS: Cascading Style Sheets
ines the color of the logical block borders of an element, which maps to a physical border color depending on the element's writing mode, directionality, and text orientation. it corresponds to the border-top-color and border-bottom-color, or border-right-color and border-left-color property depending on the values defined for writing-mode, direction, and text-orientation. border-block-color: yellow; border-block-color: #f5f6f7; the border color in the other dimension can be set with border-inline-color which sets border-inline-start-color, and border-inline-end-color. syntax values <'color'> the color of the border. see color. formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typediscrete formal syntax <'border-top...
...d border-inline-end-color. syntax values <'color'> the color of the border. see color. formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typediscrete formal syntax <'border-top-color'>{1,2} examples border with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 10px solid blue; border-block-color: red; } results specifications specification status comment css logical properties and values level 1the definition of 'border-block-color' in that specification. editor's draft initial definition ...
border-block-end-color - CSS: Cascading Style Sheets
r, border-bottom-color, or border-left-color property depending on the values defined for writing-mode, direction, and text-orientation. 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 border-block-end-color: yellow; border-block-end-color: #f5f6f7; related properties are border-block-start-color, border-inline-start-color, and border-inline-end-color, which define the other border colors of the element. values <'color'> the color of the border. see color. formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typea color formal syntax <'...
...ther border colors of the element. values <'color'> the color of the border. see color. formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typea color formal syntax <'border-top-color'> examples border color with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 10px solid blue; border-block-end-color: red; } results specifications specification status comment css logical properties and values level 1the definition of 'border-block-end-color' in that specification. editor's draft initial definition ...
border-block - CSS: Cascading Style Sheets
ectionality, and text orientation. it corresponds to the border-top and border-bottom or border-right, and border-left properties depending on the values defined for writing-mode, direction, and text-orientation. the borders in the other dimension can be set with border-inline, which sets border-inline-start, and border-inline-end. constituent properties this property is a shorthand for the following css properties: border-block-color border-block-style border-block-width syntax values the border-block is specified with one or more of the following, in any order: <'border-width'> the width of the border. see border-width. <'border-style'> the line style of the border. see border-style. <'color'> the color of the border. see color. formal definition initial valueas ea...
... editor's draft initial definition ...
border-bottom-width - CSS: Cascading Style Sheets
der-bottom-width: thick; /* <length> values */ border-bottom-width: 10em; border-bottom-width: 3vmax; border-bottom-width: 6px; /* global keywords */ border-bottom-width: inherit; border-bottom-width: initial; border-bottom-width: unset; values <line-width> defines the width of the border, either as an explicit nonnegative <length> or a keyword. ...
... formal definition initial valuemediumapplies toall elements. ...
border-collapse - CSS: Cascading Style Sheets
behaves like ridge. when cells are separated, the distance between cells is defined by the border-spacing property. syntax /* keyword values */ border-collapse: collapse; border-collapse: separate; /* global values */ border-collapse: inherit; border-collapse: initial; border-collapse: unset; the border-collapse property is specified as a single keyword, which may be chosen from the list below. values collapse adjacent cells have shared borders (the collapsed-border table rendering model). separate adjacent cells have distinct borders (the separated-border table rendering model). formal definition initial valueseparateapplies totable and inline-table elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax collapse | separate examples a colorful ...
... recommendation initial definition ...
border-color - CSS: Cascading Style Sheets
using border-top-color, border-right-color, border-bottom-color, and border-left-color; or using the writing mode-aware border-block-start-color, border-block-end-color, border-inline-start-color, and border-inline-end-color. you can find more information about border colors in borders in applying color to html elements using css. ...
... when one value is specified, it applies the same color to all four sides. ...
border-image-slice - CSS: Cascading Style Sheets
pse. it also applies to ::first-letter.inheritednopercentagesrefer to the size of the border imagecomputed valueone to four percentage(s) (as specified) or absolute length(s), plus the keyword fill if specifiedanimation typeby computed value type formal syntax <number-percentage>{1,4} && fill?where <number-percentage> = <number> | <percentage> examples adjustable border width and slice the folowing example shows a simple <div> with a border image set on it. the source image for the borders is as follows: the diamonds are 30px across, therefore setting 30 pixels as the value for both border-width and border-image-slice will get you complete and fairly crisp diamonds in your border: border-width: 30px; border-image-slice: 30; these are the default values we have used in this example. ...
...mage set on it. the source image for the borders is as follows: the diamonds are 30px across, therefore setting 30 pixels as the value for both border-width and border-image-slice will get you complete and fairly crisp diamonds in your border: border-width: 30px; border-image-slice: 30; these are the default values we have used in this example. however, we have also provided two sliders to allow you to dynamically change the values of the above two properties, allowing you to appreciate the effect they have: border-image-slice changes the size of the image slice sampled for use in each border and border corner (and the content area, if the fill keyword is used) — varying this away from 30 causes the border to look somewhat irregular, but can have some interesting effects. border-widt...
border-image-width - CSS: Cascading Style Sheets
al */ border-image-width: 2em 3em; /* top | horizontal | bottom */ border-image-width: 5% 15% 10%; /* top | right | bottom | left */ border-image-width: 5% 2em 10% auto; /* global values */ border-image-width: inherit; border-image-width: initial; border-image-width: unset; the border-image-width property may be specified using one, two, three, or four values chosen from the list of values below. when one value is specified, it applies the same width to all four sides. when two values are specified, the first width applies to the top and bottom, the second to the left and right. when three values are specified, the first width applies to the top, the second to the left and right, the third to the bottom. when four values are specified, the widths apply to the top, right, bottom, an...
... html <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 lorem ips...
border-image - CSS: Cascading Style Sheets
ontribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. note: you should specify a separate border-style in case the border image fails to load. indeed, this is required according to the specification, although not all browsers implement this requirement. ...
..., blue) 27; /* source | slice | repeat */ border-image: url("/images/border.png") 27 space; /* source | slice | width */ border-image: linear-gradient(red, blue) 27 / 35px; /* source | slice | width | outset | repeat */ border-image: url("/images/border.png") 27 23 / 50px 30px / 1rem round space; the border-image property may be specified with anywhere from one to five of the values listed below. note: if the computed value of border-image-source is none, or if the image cannot be displayed, the border-style will be displayed instead. values <'border-image-source'> the source image. see border-image-source. <'border-image-slice'> the dimensions for slicing the source image into regions. up to four values may be specified. see border-image-slice. <'border-image-width'> the wid...
border-inline-color - CSS: Cascading Style Sheets
es the color of the logical inline borders of an element, which maps to a physical border color depending on the element's writing mode, directionality, and text orientation. it corresponds to the border-top-color and border-bottom-color, or border-right-color and border-left-color property depending on the values defined for writing-mode, direction, and text-orientation. border-inline-color: yellow; border-inline-color: #f5f6f7; the border color in the other dimension can be set with border-block-color which sets border-block-start-color, and border-block-end-color. syntax values <'color'> the color of the border. see color. formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typediscrete formal syntax <'border-top-c...
...der-block-end-color. syntax values <'color'> the color of the border. see color. formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typediscrete formal syntax <'border-top-color'>{1,2} examples border color with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 10px solid blue; border-inline-color: red; } results specifications specification status comment css logical properties and values level 1the definition of 'border-inline-color' in that specification. editor's draft initial definition ...
border-left-width - CSS: Cascading Style Sheets
h: medium; border-left-width: thick; /* <length> values */ border-left-width: 10em; border-left-width: 3vmax; border-left-width: 6px; /* global keywords */ border-left-width: inherit; border-left-width: initial; border-left-width: unset; values <line-width> defines the width of the border, either as an explicit nonnegative <length> or a keyword. ...
... formal definition initial valuemediumapplies toall elements. ...
border-right-width - CSS: Cascading Style Sheets
um; border-right-width: thick; /* <length> values */ border-right-width: 10em; border-right-width: 3vmax; border-right-width: 6px; /* global keywords */ border-right-width: inherit; border-right-width: initial; border-right-width: unset; values <line-width> defines the width of the border, either as an explicit nonnegative <length> or a keyword. ...
... formal definition initial valuemediumapplies toall elements. ...
border-top-width - CSS: Cascading Style Sheets
op-width: medium; border-top-width: thick; /* <length> values */ border-top-width: 10em; border-top-width: 3vmax; border-top-width: 6px; /* global keywords */ border-top-width: inherit; border-top-width: initial; border-top-width: unset; values <line-width> defines the width of the border, either as an explicit nonnegative <length> or a keyword. ...
... formal definition initial valuemediumapplies toall elements. ...
box-decoration-break - CSS: Cascading Style Sheets
erty specifies how an element's fragments should be rendered when broken across multiple lines, columns, or pages. 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 specified value will impact the appearance of the following properties: background border border-image box-shadow clip-path margin padding syntax /* keyword values */ box-decoration-break: slice; box-decoration-break: clone; /* global values */ box-decoration-break: initial; box-decoration-break: inherit; box-decoration-break: unset; the box-decoration-break property is specified as one of the keyword values listed below. values slic...
...hat a background image with background-repeat: no-repeat may nevertheless repeat multiple times. formal definition initial valuesliceapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax slice | clone examples inline box fragments an inline element that contains line breaks styled with: .example { background: linear-gradient(to bottom right, yellow, green); box-shadow: 8px 8px 10px 0px deeppink, -5px -5px 5px 0px blue, 5px 5px 15px 0px yellow; padding: 0em 1em; border-radius: 16px; border-style: solid; margin-left: 10px; font: 24px sans-serif; line-height: 2; } ... <span class="example">the<br>quick<br>orange fox</span> ... results in: adding box-decoration-break: clone to the above styles: -webkit-box-decora...
box-flex-group - CSS: Cascading Style Sheets
oup. if the space of all flexible children within the group has been increased to the maximum, the process repeats for the children within the next flex group, using any space left over from the previous flex group. 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 <i...
...ted, 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>. ...
box-ordinal-group - CSS: Cascading Style Sheets
teger> values */ box-ordinal-group: 1; box-ordinal-group: 5; /* global values */ box-ordinal-group: inherit; box-ordinal-group: initial; box-ordinal-group: unset; ordinal groups may be used in conjunction with the box-direction property to control the order in which the direct children of a box appear. when 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 ...
...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 you to change the display order of flex children inside a flex container: article:nth-child(1) { -webkit-box-ordinal-group: 2 -moz-box-ordinal-group: 2 box-ordinal-group: 2 } article:nth-child(2) { -webkit-box-ordinal-group: 1 -moz-box-ordinal-group: 1 box-ordinal-group: 1 } the modern flexbox equivalent is order. specifications not part of any standard. ...
content - CSS: Cascading Style Sheets
Web › CSS › content
are anonymous replaced elements. ...
...p://www.mozilla.org/">mozilla home page</a> css a::before { content: url("https://mozorg.cdn.mozilla.net/media/img/favicon.ico") / " mozilla: "; font: x-small arial, sans-serif; color: gray; } result targeting classes this example inserts additional text after special items in a list. ...
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 incremen...
...decrement "counter2" by 4 */ counter-increment: counter1 counter2 -4; /* do not increment/decrement anything: used to override less specific rules */ counter-increment: none; /* global values */ counter-increment: inherit; counter-increment: initial; counter-increment: unset; the counter-increment property is specified as either one of the following: a <custom-ident> naming the counter, followed optionally by an <integer>. 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 default value, or to cance...
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 ...
...-counter -1; /* set "counter1" to 1, and "counter2" to 4 */ counter-reset: counter1 1 counter2 4; /* cancel any reset that could have been set in less specific rules */ counter-reset: none; /* global values */ counter-reset: inherit; counter-reset: initial; counter-reset: unset; the counter-reset property is specified as either one of the following: a <custom-ident> naming the counter, followed optionally by an <integer>. 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 performed. this can be u...
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 i...
...er-set: my-counter -1; /* set "counter1" to 1, and "counter2" to 4 */ counter-set: counter1 1 counter2 4; /* cancel any counter that could have been set in less specific rules */ counter-set: none; /* global values */ counter-set: inherit; counter-set: initial; counter-set: unset; the counter-set property is specified as either one of the following: a <custom-ident> naming the counter, followed optionally by an <integer>. 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 the given name on the e...
counters() - CSS: Cascading Style Sheets
Web › CSS › counters
<li> <ol> <li></li> <li></li> <li></li> </ol> </li> </ol> </li> </ol> css ol { counter-reset: listcounter; } li { counter-increment: listcounter; } li::marker { content: counters(listcounter, '.', upper-roman) ') '; } li::before { content: counters(listcounter, ".") " == " counters(listcounter, ".", lower-roman) ; } result decimal-leading-zero compared to lower-alpha html <ol> <li> <ol> <li></li> <li></li> <li></li> </ol> </li> <li></li> <li></li> <li> <ol> <li></li> <li> <ol> <li></li> <li></li> <li></li> </ol> </li> </ol> </li> </ol> css ol {...
... working draft no change css level 2 (revision 1)the definition of 'css counters' in that specification. recommendation initial definition ...
direction - CSS: Cascading Style Sheets
Web › CSS › direction
use rtl for languages written from right to left (like hebrew or arabic), and ltr for those written from left to right (like english and most other languages). 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 text direction is usually defined within a document (e.g., with html's dir attribute) rather than through direct use of the direction property. ...
...ll request. note that text direction is usually defined within a document (e.g., with html's dir attribute) rather than through direct use of the direction property. the property sets the base text direction of block-level elements and the direction of embeddings created by the unicode-bidi property. it also sets the default alignment of text, block-level elements, and the direction that cells flow within a table row. unlike the dir attribute in html, the direction property is not inherited from table columns into table cells, since css inheritance follows the document tree, and table cells are inside of rows but not inside of columns. the direction and unicode-bidi properties are the two only properties which are not affected by the all shorthand property. syntax /* keyword values */ d...
<display-legacy> - CSS: Cascading Style Sheets
css 2 used a single-keyword syntax for the display property, requiring separate keywords for block-level and inline-level variants of the same layout mode. this page details those values. syntax valid <display-legacy> values: inline-block the element generates a block element box that will be flowed with surrounding content as if it were a single inline box (behaving much like a replaced element would). it is equivalent to inline flow-root. inline-table the inline-table value does not have a direct mapping in html. it behaves like an html <table> element, but as an inline box, rather than a block-level box. inside the table box is a block-level context. it is equivalent to inline table. inline-flex the element behaves like an inline element and lays out its content accordin...
...side the table box is a block-level context. it is equivalent to inline table. inline-flex the element behaves like an inline element and lays out its content according to the flexbox model. it is equivalent to inline flex. inline-grid the element behaves like an inline element and lays out its content according to the grid model. it is equivalent to inline grid. examples in the below example, we are creating an inline flex container with the legacy keyword inline-flex. html <div class="container"> <div>flex item</div> <div>flex item</div> </div> not a flex item css .container { display: inline-flex; } result in the new syntax the inline flex container would be created using two values, inline for the outer display type, and flex for the inner display type.
element() - CSS: Cascading Style Sheets
Web › CSS › element
z-element(). a somewhat realistic example this example uses a hidden <div> as a background. the background element uses a gradient, but also includes text that is rendered as part of the background. <div style="width:400px; height:400px; background:-moz-element(#mybackground1) no-repeat;"> <p>this box uses the element with the #mybackground1 id as its background!</p> </div> <div style="overflow:hidden; height:0;"> <div id="mybackground1" style="width:1024px; height:1024px; background-image: linear-gradient(to right, red, orange, yellow, white);"> <p style="transform-origin:0 0; transform: rotate(45deg); color:white;">this text is part of the background. cool, huh?</p> </div> </div> the <div> element with the id "mybackground1" is used as the background for the content including t...
...he #mybackground1 id as its background!". a somewhat more bizarre example this example uses a hidden <button> element in a repeating pattern as its background. this demonstrates that you can use arbitrary elements as background, but doesn't necessarily demonstrate good design practices. <div style="width:400px; height:100px; background:-moz-element(#mybackground2);"> </div> <div style="overflow:hidden; height:0;"> <button id="mybackground2" type="button">evil button!</button> </div> specifications specification status comment css images module level 4the definition of 'using elements as images: the element() notation' in that specification. working draft deferred from css3 images. browser compatibility the compatibility table on this page...
<filter-function> - CSS: Cascading Style Sheets
each function requires an argument which, if invalid, results in no filter being applied. blur() blurs the image. brightness() makes the image brighter or darker. contrast() increases or decreases the image's contrast. ...
...rayscale. hue-rotate()​​​​​​​​​​​​​​ changes the overall hue of the image. invert() inverts the colors of the image. opacity() makes the image transparent. saturate() super-saturates or desaturates the input image. sepia() converts the image to sepia. examples filter function comparison this example provides a simple graphic, along with a select menu to allow you to choose between the different types of filter function, and a slider to allow you to vary the values used inside the filter function. updating the controls updates the filter effect in real time, allowing you to investigate the effects of different filters. html <div></div> <ul> <li> <label for="filter-select">choose a filter function:</label> <select id="filter-select"> <...
flex-shrink - CSS: Cascading Style Sheets
-examples and send us a pull request. syntax /* <number> values */ flex-shrink: 2; flex-shrink: 0.6; /* global values */ flex-shrink: inherit; flex-shrink: initial; flex-shrink: unset; the flex-shrink property is specified as a single <number>. values <number> see <number>. negative values are invalid. defaults to 1. formal definition initial value1applies toflex items, including in-flow pseudo-elementsinheritednocomputed valueas specifiedanimation typea number formal syntax <number> examples setting flex item shrink factor html <p>the width of content is 500px; the flex-basis of the flex items is 120px.</p> <p>a, b, c have flex-shrink:1 set. d and e have flex-shrink:2 set</p> <p>the width of d and e is less than the others.</p> <div id="content"> <div class="box" style=...
...or html <p>the width of content is 500px; the flex-basis of the flex items is 120px.</p> <p>a, b, c have flex-shrink:1 set. ...
font-feature-settings - CSS: Cascading Style Sheets
eature-settings: unset; whenever possible, web authors should instead use the font-variant shorthand property or an associated longhand property such as font-variant-ligatures, font-variant-caps, font-variant-east-asian, font-variant-alternates, font-variant-numeric or font-variant-position. these lead to more effective, predictable, understandable results than font-feature-settings, which is a low-level feature designed to handle special cases where no other way exists to enable or access an opentype font feature. in particular, font-feature-settings shouldn't be used to enable small caps. values normal text is laid out using default settings. <feature-tag-value> when rendering text, the list of opentype feature tag value is passed to the text layout engine to enable or disable font...
...applies toall elements. ...
font-smooth - CSS: Cascading Style Sheets
the font on the level of the pixel, as opposed to the subpixel. switching from subpixel rendering to antialiasing for light text on dark backgrounds makes it look lighter. subpixel-antialiased - on most non-retina displays, this will give the sharpest text. firefox implements a similar property, but with different values: -moz-osx-font-smoothing. it only works on mac os x/macos. auto - allow the browser to select an optimization for font smoothing, typically grayscale. grayscale - render text with grayscale antialiasing, as opposed to the subpixel. switching from subpixel rendering to antialiasing for light text on dark backgrounds makes it look lighter. formal definition initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal ...
... antialiasing for light text on dark backgrounds makes it look lighter. formal definition initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | never | always | <absolute-size> | <length>where <absolute-size> = xx-small | x-small | small | medium | large | x-large | xx-large | xxx-large examples basic usage example the following example shows the safari/chromium and firefox equivalents that turn on font-smoothing on macos. in both cases the smoothed font should look slightly lighter in weight. for those of you not on a macos system, here is a screenshot (the live version appears later on): html <p>without font smoothing</p> <p class="smoothed">with font smoothing</p> css html { background-color: black; col...
font-variant-alternates - CSS: Cascading Style Sheets
font-variant-alternates: swash(ident1) annotation(ident2); /* global values */ font-variant-alternates: initial; font-variant-alternates: inherit; font-variant-alternates: unset; the @font-feature-values at-rule can define names for alternative glyph functions (stylistic, styleset, character-variant, swash, ornament or annotation), associating the name with opentype parameters. this property allows those human-readable names (defined in @font-feature-values) in the stylesheet. syntax this property may take one of two forms: either the keyword normal or one or more of the other keywords and functions listed below, space-separated, in any order. values normal this keyword deactivates alternate glyphs. historical-forms this keyword enables historical forms — glyphs that were c...
...nables ornaments, like fleurons and other dingbat glyphs. the parameter is a font-specific name mapped to a number. it corresponds to the opentype value ornm, like ornm 2. note: in order to preserve text semantics, font designers should include ornaments that don't match unicode dingbat characters as ornamental variants of the bullet character (u+2022). be aware that some existing fonts don't follow this advice. annotation() this function enables annotations, like circled digits or inverted characters. the parameter is a font-specific name mapped to a number. it corresponds to the opentype value nalt, like nalt 2. formal definition initial valuenormalapplies toall elements. it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete ...
font-variant-numeric - CSS: Cascading Style Sheets
values normal this keyword leads to the deactivation of the use of such alternate glyphs. ordinal this keyword forces the use of special glyphs for the ordinal markers, like 1st, 2nd, 3rd, 4th in english or a 1a in italian. it corresponds to the opentype values ordn. slashed-zero this keyword forces the use of a 0 with a slash; this is useful when a clear...
...escenders. it corresponds to the opentype values onum. <numeric-spacing-values> these values controls the sizing of figures used for numbers. two values are possible: proportional-nums activating the set of figures where numbers are not all of the same size. it corresponds to the 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-fractio...
font-variant - CSS: Cascading Style Sheets
the font-variant css shorthand property allows you to set all the font variants for a font. you can also set the css level 2 (revision 1) values of font-variant, (that is, normal or small-caps), by using the font shorthand. 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. ...
... level 2 (revision 1) values of font-variant, (that is, normal or small-caps), by using the font shorthand. 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. ...
<frequency> - CSS: Cascading Style Sheets
Web › CSS › frequency
as with all css dimensions, there is no space between the unit literal and the number. units hz represents a frequency in hertz. examples: 0hz, 1500hz, 10000hz. khz represents a frequency in kilohertz. examples: 0khz, 1.5khz, 10khz. note: although the number 0 is always the same regardless of unit, the unit may not be omitted. ...
...ed in the si. examples valid frequency values 12hz positive integer 4.3hz non-integer 14khz the unit is case-insensitive, though non-si capitalization is not recommended. +0hz zero, with a leading + and a unit -0khz zero, with a leading - and a unit invalid frequency values 12.0 this is a <number>, not an <frequency>, because it is missing a unit. 7 hz no space is allowed between the number and the unit. 0 although unitless zero is an allowable <length>, it's an invalid <frequency>. specifications specification status comment css values and units module level 3the definition of '<frequency>' in that specification. candidate recommendation initial definition. note: this data type was initially introduced in css l...
<gradient> - CSS: Cascading Style Sheets
Web › CSS › gradient
tribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. a css gradient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. its concrete size will match the size of the element to which it applies. syntax the <gradient> data type is defined with one of the function types listed below. linear gradient linear gradients transition colors progressively along an imaginary line. they are generated with the linear-gradient() function. radial gradient radial gradients transition colors progressively from a center point (origin). they are generated with the radial-gradient() function. repeating gradient repeating gradients duplicate a gradient as much as necessary to fill a...
...y from appearing when both the color and the opacity are changing. (be aware that older browsers may not use this behavior when using the transparent keyword.) examples linear gradient example a simple linear gradient. <div class="linear-gradient">linear gradient</div> div { width: 240px; height: 80px; } .linear-gradient { background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet); } radial gradient example a simple radial gradient. <div class="radial-gradient">radial gradient</div> div { width: 240px; height: 80px; } .radial-gradient { background: radial-gradient(red, yellow, rgb(30, 144, 255)); } repeating gradient examples simple repeating linear and radial gradient examples. <div class="linear-repeat">repeating linea...
grid-area - CSS: Cascading Style Sheets
Web › CSS › grid-area
om-ident>; otherwise, it is set to auto. when grid-column-start is omitted, if grid-row-start is a <custom-ident>, all four longhands are set to that value. otherwise, it is set to auto. the grid-area property can also be set to a <custom-ident> which acts as a name for the area, which can then be placed using grid-template-areas. ...
... candidate recommendation initial definition ...
grid-column - CSS: Cascading Style Sheets
automatic) to its grid placement, thereby specifying the inline-start and inline-end edge of its grid 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. constituent properties this property is a shorthand for the following css properties: grid-column-end grid-column-start syntax this property is specified as one or two <grid-line> values. if two <grid-line> values are given they are separated by "/". the grid-column-start longhand is set to the value before the slash, and the grid-column-end longhand is set to the value after the slash. each <grid-line> value can be specified as: either the auto keyw...
... candidate recommendation initial definition ...
grid-row - CSS: Cascading Style Sheets
Web › CSS › grid-row
pository. 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. if two <grid-line> values are specified, the grid-row-start longhand is set to the value before the slash, and the grid-row-end longhand is set to the value after the slash. ...
... candidate recommendation initial definition ...
grid-template-columns - CSS: Cascading Style Sheets
ties. fit-content( [ <length> | <percentage> ] ) represents the formula min(max-content, max(auto, argument)), 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. repeat( [ <positive-integer> | auto-fill | auto-fit ] , <track-list> ) represents a repeated fragment of the track list, allowing a large number of columns that exhibit a recurring pattern to be written in a more compact form. subgrid the subgrid value indicates that the grid will adopt the spanned portion of its parent grid in that axis. rather than being specified explicitly, the sizes of the grid rows/columns will be taken from the parent grid’s definition. the subgrid value is from level 2 of the grid specific...
... candidate recommendation initial definition css grid layout module level 2the definition of 'subgrid' in that specification. working draft adds subgrid ...
grid-template-rows - CSS: Cascading Style Sheets
ties. fit-content( [ <length> | <percentage> ] ) represents the formula min(max-content, max(auto, argument)), 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. repeat( [ <positive-integer> | auto-fill | auto-fit ] , <track-list> ) represents a repeated fragment of the track list, allowing a large number of rows that exhibit a recurring pattern to be written in a more compact form. subgrid the subgrid value indicates that the grid will adopt the spanned portion of its parent grid in that axis. rather than being specified explicitly, the sizes of the grid rows/columns will be taken from the parent grid’s definition. the subgrid value is from level 2 of the grid specificati...
... candidate recommendation initial definition css grid layout module level 2the definition of 'subgrid' in that specification. working draft adds subgrid ...
<image> - CSS: Cascading Style Sheets
Web › CSS › image
the <image> css data type represents a two-dimensional image. syntax the <image> data type can be represented with any of the following: an image denoted by the <url> data type a <gradient> data type a part of the webpage, defined by the element() function an image, image fragment or solid patch of color, defined by the image() function a blending of two or more images defined by the cross-fade() function. a selection of images chosed based on resolution defined by the image-set() function. description css can handle the following kinds of images: images with intrinsic dimensions (a natural size), like a jpeg, png, or other raster format. images with multiple intrinsic dimensions, existing in multiple versions inside a single file, like some .ico formats. (in this case, the ...
...he client's system mask-image ? shape-outside ? mask-border-source ? symbols for @counter-style at risk feature. if supported, the browser-defined size matching the usual cursor size on the client's system content for a pseudo-element (::after/::before) a 300px × 150px rectangle the concrete object size is calculated using the following algorithm: if the specified size defines both the width and the height, these values are used as the concrete object size. if the specified size defines only the width or only the height, the missing value is determined using the intrinsic ratio, if there is any, the intrinsic dimensions if the specified value matches, or the default object size for that missing value. if the specified si...
initial-letter - CSS: Cascading Style Sheets
<integer> defines the number of lines the initial letter should sink when the size of it is given. values must be greater than zero. if omitted, it duplicates the size value, fl...
... <integer> defines the number of lines the initial letter should sink when the size of it is given. values must be greater than zero. ...
inset-block - CSS: Cascading Style Sheets
formal definition initial valueautoapplies topositioned elementsinheritednopercentageslogical-height of containing blockcomputed valuesame as box offsets: top, right, bottom, left properties except that directions are logicalanimation typea length, perc...
... editor's draft initial definition ...
inset-inline - CSS: Cascading Style Sheets
formal definition initial valueautoapplies topositioned elementsinheritednopercentageslogical-width of containing blockcomputed valuesame as box offsets: top, right, bottom, left properties except that directions are logicalanimation typea length, pe...
... editor's draft initial definition ...
<length-percentage> - CSS: Cascading Style Sheets
the <length-percentage> css data type represents a value that can be either a <length> or a <percentage>. syntax refer to the documentation for <length> and <percentage> for details of the individual syntaxes allowed by this type. examples length-percentage examples the following simple example demonstrates several properties that use <length-percentage> values. html <p>you can use percentages and lengths in so many places.</p> css p { /* length-percentage examples */ width: 75%; height: 200px; margin: 3rem; padding: 1%; border-radius: 10px 10%; font-size: 250%; line-height: 1.5em; /* length examples */ text-shadow: 1px 1px 1px red; border: 5px solid red; letter-spacing: 3px; /* percentage example */ text-size-adjust: 20%; } result use in calc() wh...
... /* length-percentage examples */ width: 75%; height: 200px; margin: 3rem; padding: 1%; border-radius: 10px 10%; font-size: 250%; line-height: 1.5em; /* length examples */ text-shadow: 1px 1px 1px red; border: 5px solid red; letter-spacing: 3px; /* percentage example */ text-size-adjust: 20%; } result use in calc() where a <length-percentage> is specified as an allowable type, this means that the percentage resolves to a length and therefore can be used in a calc() expression. therefore, all of the following values are acceptable for width: width: 200px; width: 20%; width: calc(100% - 200px); specifications specification status comment css values and units module level 4the definition of '<length-percentage>' in that specificat...
line-height-step - CSS: Cascading Style Sheets
the line-height-step css property sets the step unit for line box heights. when the property is set, line box heights are rounded up to the closest multiple of the unit. /* point values */ line-height-step: 18pt; syntax the line-height-step property is specified as any one of the following: a <length>. values <length> the specified <length> is used in the calculation of the line box height step. formal definition initial value0applies toblock containersinheritedyescomputed valueabsolute <length>animation typediscrete formal syntax <length> examples setting step unit for line box height in the following example, the height of line box in each paragraph is rounded up to the step unit. the line box in <h1> does not fit into one step unit and thus occupies two, but it is st...
...g example, the height of line box in each paragraph is rounded up to the step unit. the line box in <h1> does not fit into one step unit and thus occupies two, but it is still centered within the two step unit. :root { font-size: 12pt; --my-grid: 18pt; line-height-step: var(--my-grid); } h1 { font-size: 20pt; margin-top: calc(2 * var(--my-grid)); } the result of these rules is shown below in the following screenshot: specifications specification status comment css rhythmic sizingthe definition of 'line-height-step' in that specification. working draft initial definition. ...
margin-block - CSS: Cascading Style Sheets
d end values */ /* keyword values */ margin-block: auto; /* global values */ margin-block: inherit; margin-block: initial; margin-block: unset; these values corresponds to the margin-top and margin-bottom, or margin-right, and margin-left property depending on the values defined for writing-mode, direction, and text-orientation. constituent properties this property is a shorthand for the following css properties: margin-block-end margin-block-start syntax values the margin-block property takes the same values as the margin-left property. formal definition initial value0applies tosame as margininheritednopercentagesdepends on layout modelcomputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, autoa...
... editor's draft initial definition. ...
margin-inline - CSS: Cascading Style Sheets
lues */ /* keyword values */ margin-inline: auto; /* global values */ margin-inline: inherit; margin-inline: initial; margin-inline: unset; this property corresponds to the margin-top and margin-bottom, or margin-right, and margin-left properties, depending on the values defined for writing-mode, direction, and text-orientation. constituent properties this property is a shorthand for the following css properties: margin-inline-end margin-inline-start syntax values the margin-inline property takes the same values as the margin-left property. formal definition initial value0applies tosame as margininheritednopercentagesdepends on layout modelcomputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, au...
... editor's draft initial definition. initial value0applies tosame ...
mask - CSS: Cascading Style Sheets
Web › CSS › mask
the mask css shorthand property hides an element (partially or fully) by masking or clipping the image at specific points. as well as the properties listed below, the mask shorthand also resets mask-border to its initial value. it is therefore recommended to use the mask shorthand rather than other shorthands or the individual properties to override any mask settings earlier in the cascade. this will ensure that mask-border has also been reset to allow the new styles to take effect. ...
...d below, the mask shorthand also resets mask-border to its initial value. it is therefore recommended to use the mask shorthand rather than other shorthands or the individual properties to override any mask settings earlier in the cascade. this will ensure that mask-border has also been reset to allow the new styles to take effect. ...
max-block-size - CSS: Cascading Style Sheets
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 max-block-size is equivalent to horizontal-tb, lr , lr-tb , rl , rb , rb-rl max-height vertical-rl, vertical-lr, sideways-rl , sideways-lr , tb , tb-rl max-width the writing-mode values sideways-lr and sideways-rl were removed from the css writing modes level 3 specification late in its design process. they may b...
...ontal-tb, lr , lr-tb , rl , rb , rb-rl max-height vertical-rl, vertical-lr, sideways-rl , sideways-lr , tb , tb-rl max-width the writing-mode values sideways-lr and sideways-rl were removed from the css writing modes level 3 specification late in its design process. they may be restored in level 4. the writing modes lr, lr-tb, rl, rb, and rb-tl are no longer allowed in html contexts; they may only be used in svg 1.x contexts. formal definition initial value0applies tosame as width and heightinheritednopercentagesblock-size of containing blockcomputed valuesame as max-width and max-heightanimation typea length, percentage or calc(); formal syntax <'max-width'> examples setting max-block-size with horizontal and vertical text in this example, the sam...
<number> - CSS: Cascading Style Sheets
Web › CSS › number
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. ...
...es 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 notation invalid numbers 12. decimal points must be followed by at least one digit. +-12.2 only one leading +/- is allowed. 12.1.1 only one decimal point is allowed. specifications specification status comment css values and units module level 4the definition of '<number>' in that specification. editor's draft no significant change. css values and units module level 3the definition of '<number>' in ...
offset-anchor - CSS: Cascading Style Sheets
each <div> is given the same offset-path (a horizontal line 200 pixels long) and animated to move along it. the three are then given different background-color and offset-anchor values. each <section> has been styled with a linear gradient to give it a horizontal line running through its center, to give you a visual display ...
...ction> elements. each <div> is given the same offset-path (a horizontal line 200 pixels long) and animated to move along it. the three are then given different background-color and offset-anchor values. each <section> has been styled with a linear gradient to give it a horizontal line running through its center, to give you a visual display of where the <div>'s offset paths are running. this allows you to see what effect the different offset-anchor values have — the first one, auto, causes the <div>'s center point to move along the path. the other two cause the <div>'s top-right and bottom-left points to move along the path, respectively. html <section> <div class="offset-anchor1"></div> </section> <section> <div class="offset-anchor2"></div> </section> <section> <div class="offs...
offset-rotate - CSS: Cascading Style Sheets
the offset-rotate css property defines the orientation/direction of the element as it is positioned along the offset-path. note: early versions of the spec called this property motion-rotation. syntax /* follow the path direction, with optional additional angle */ offset-rotate: auto; offset-rotate: auto 45deg; /* follow the path direction but facing the opposite direction of `auto` */ offset-rotate: reverse; /* keep a constant rotation regardless the position on the path */ offset-rotate: 90deg; offset-rotate: .5turn; auto the element is rotated by the angle of the direction of the offset-path, relative to the positive x-axis. this is the default value. <angle> the element has a constant clockwise rotation transformation applied to it by the specified rotation angle. ...
...onstant rotation regardless the position on the path */ offset-rotate: 90deg; offset-rotate: .5turn; auto the element is rotated by the angle of the direction of the offset-path, relative to the positive x-axis. this is the default value. <angle> the element has a constant clockwise rotation transformation applied to it by the specified rotation angle. auto <angle> if auto is followed by an <angle>, the computed value of the angle is added to the computed value of auto. reverse the element is rotated similar to auto, except it faces the opposite direction. it is the same as specifying a value of auto 180deg. formal definition initial valueautoapplies totransformable elementsinheritednocomputed valueas specifiedanimation typeas <angle>, <basic-shape> or <path()> ...
outline-color - CSS: Cascading Style Sheets
ase clone https://github.com/mdn/interactive-examples and send us a pull request. syntax /* <color> values */ outline-color: #f92525; outline-color: rgb(30,222,121); outline-color: blue; /* keyword value */ outline-color: invert; /* global values */ outline-color: inherit; outline-color: initial; outline-color: unset; the outline-color property is specified as any one of the values listed below. values <color> the color of the outline, specified as a <color>. invert to ensure the outline is visible, performs a color inversion of the background. note that browsers are not required to support this value; if they don't, this keyword is considered invalid. description an outline is a line that is drawn around an element, outside the border. unlike the element's border, the outline...
...s often more convenient to use the shorthand property outline when defining the appearance 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 ...
outline-style - CSS: Cascading Style Sheets
values */ outline-style: auto; outline-style: none; outline-style: dotted; outline-style: dashed; outline-style: solid; outline-style: double; outline-style: groove; outline-style: ridge; outline-style: inset; outline-style: outset; /* global values */ outline-style: inherit; outline-style: initial; outline-style: unset; the outline-style property is specified as any one of the values listed below. values auto permits the user agent to render a custom outline style. none no outline is used. the outline-width is 0. dotted the outline is a series of dots. dashed the outline is a series of short line segments. solid the outline is a single line. double the outline is two single lines. the outline-width is the sum of the two lines and the space between th...
...s 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 described in detail in css, e.g. a rounded edge outline with semi-translucent outer pixels that appears to glow. html <div> <p class="auto">outline demo</p> </div> css .auto { outline-style: auto; /* same result as "outline: auto" */ } /* to make the demo clearer */ * { outline-width: 10px; padding: 15px; } result setting outline style to dashed and dotted html <div> <div class="dotted"> <p class="dashed">outline demo</p> </div> </div> css .dotted { outline-style: dotted; /* s...
outline - CSS: Cascading Style Sheets
Web › CSS › outline
the outline css shorthand property set all the outline properties in a single declaration. 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. constituent properties this property is a shorthand for the following css properties: outline-color outline-style outline-width syntax /* style */ outline: solid; /* color | style */ outline: #f66 dashed; /* style | width */ outline: inset thick; /* color | style | width */ outline: green solid 3px; /* global values */ outline: inherit; outline: initial; outline: unset; the outline property may be specified using one, two, or three of the values listed below. the ...
...-color'> sets the color of the outline. defaults to currentcolor if absent. see outline-color. <'outline-style'> sets the style of the outline. defaults to none if absent. see outline-style. <'outline-width'> sets the thickness of the outline. defaults to medium if absent. see outline-width. description borders and outlines are very similar. however, outlines differ from borders in the following ways: outlines never take up space, as they are drawn outside of an element's content. according to the spec, outlines don't have to be rectangular, although they usually are. as with all shorthand properties, any omitted sub-values will be set to their initial value. accessibility concerns assigning outline a value of 0 or none will remove the browser's default focus style. if an elem...
padding-block - CSS: Cascading Style Sheets
relative to the nearest block container's width */ /* global values */ padding-block: inherit; padding-block: initial; padding-block: unset; these values corresponds to the padding-top and padding-bottom, or padding-right, and padding-left property depending on the values defined for writing-mode, direction, and text-orientation. constituent properties this property is a shorthand for the following css properties: padding-block-end padding-block-start syntax values the padding-block property takes the same values as the padding-left property. formal definition initial value0applies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueas <length>animation typediscrete formal syntax <'padding-left'>{1,2} examples setting block padding for vertica...
...y takes the same values as the padding-left property. formal definition initial value0applies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueas <length>animation typediscrete formal syntax <'padding-left'>{1,2} examples setting block padding for vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; padding-block: 20px 40px; background-color: #c8c800; } result specifications specification status comment css logical properties and values level 1the definition of 'padding-block' in that specification. editor's draft initial definition ...
padding-inline - CSS: Cascading Style Sheets
description values for this property correspond to the padding-top and padding-bottom, or padding-right, and padding-left property depending on the values defined for writing-mode, direction, and text-orientation. formal definition in...
...d for writing-mode, direction, and text-orientation. formal definition initial value0applies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueas <length>animation typediscrete formal syntax <'padding-left'>{1,2} examples setting inline padding for vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; padding-inline: 20px 40px; background-color: #c8c800; } result specifications specification status comment css logical properties and values level 1the definition of 'padding-inline' in that specification. editor's draft initial definition ...
page-break-inside - CSS: Cascading Style Sheets
forced nor forbidden). avoid avoid page breaks inside the element. page break aliases the page-break-inside property is now a legacy property, replaced by break-inside. for compatibility reasons, page-break-inside should be treated by browsers as an alias of break-inside. this ensures that sites using page-break-inside continue to work as designed. a subset of values should be aliased as follows: page-break-inside break-inside auto auto avoid avoid formal definition initial valueautoapplies toblock-level elements in the normal flow of the root element. user agents may also apply it to other elements like table-row elements.inheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | avoid examples avoiding page bre...
... css level 2 (revision 1)the definition of 'page-break-inside' in that specification. recommendation initial definition. ...
place-content - CSS: Cascading Style Sheets
the place-content css shorthand property allows you to align content along both the block and inline directions at once (i.e. the align-content and justify-content properties) in a relevant layout system such as grid or flexbox. 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. ...
...i.e. the align-content and justify-content properties) in a relevant layout system such as grid or flexbox. 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. ...
place-items - CSS: Cascading Style Sheets
the css place-items shorthand property allows you to align items along both the block and inline directions at once (i.e. the align-items and justify-items properties) in a relevant layout system such as grid or flexbox. if the second value is not set, the first value is also used for it. 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. ...
...layout system such as grid or flexbox. if the second value is not set, the first value is also used for it. 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. ...
pointer-events - CSS: Cascading Style Sheets
/* svg only */ pointer-events: painted; /* svg only */ pointer-events: fill; /* svg only */ pointer-events: stroke; /* svg only */ pointer-events: all; /* svg only */ /* global values */ pointer-events: inherit; pointer-events: initial; pointer-events: unset; the pointer-events property is specified as a single keyword chosen from the list of values below. values auto the element behaves as it would if the pointer-events property were not specified. in svg content, this value and the value visiblepainted have the same effect. none the element is never the target of pointer events; however, pointer events may target its descendant elements if those descendants have pointer-events set to some other value. in these circumstances, pointer event...
...e value none instructs the pointer event to go "through" the element and target whatever is "underneath" that element instead. note that preventing an element from being the target of pointer events by using pointer-events does not necessarily mean that pointer event listeners on that element cannot or will not be triggered. if one of the element's children has pointer-events explicitly set to allow that child to be the target of pointer events, then any events targeting that child will pass through the parent as the event travels along the parent chain, and trigger event listeners on the parent as appropriate. of course any pointer activity at a point on the screen that is covered by the parent but not by the child will not be caught by either the child or the parent (it will go "through" t...
<position> - CSS: Cascading Style Sheets
at preceeds it */ formal syntax [ [ left | center | right ] || [ top | center | bottom ] | [ left | center | right | <length> | <percentage> ] [ top | center | bottom | <length> | <percentage> ]? | [ [ 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. 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...
...e level 3 is supported, its definition of <position> must also be used. css backgrounds and borders module level 3the definition of '<bg-position>' in that specification. candidate recommendation defines <position> explicitly and extends it to support offsets from any edge. css level 2 (revision 1)the definition of '<position>' in that specification. recommendation allows combination of a keyword with a <length> or <percentage> value. css level 1the definition of '<position>' in that specification. recommendation defines <position> anonymously as the value of background-position. ...
repeating-linear-gradient() - CSS: Cascading Style Sheets
fied, it defaults to to bottom. the values to top, to bottom, to left, and to right are equivalent to the angles 0deg, 180deg, 270deg, and 90deg respectively. the other values are translated into an angle. <angle> the gradient line's angle of direction. a value of 0deg is equivalent to to top; increasing values rotate clockwise from there. <linear-color-stop> a color-stop's <color> value, followed by one or two optional stop positions, (each being either a <percentage> or a <length> along the gradient's axis). a percentage of 0%, or a length of 0, represents the start of the gradient; the value 100% is 100% of the image size, meaning the gradient will not repeat. <color-hint> th color-hint is an interpolation hint defining how the gradient progresses between adjacent color stops. the l...
...eat. <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 color stops. note: rendering of color stops in css gradients follows the same rules as color stops in svg gradients. formal syntax repeating-linear-gradient( [ <angle> | to <side-or-corner> ,]? <color-stop-list> ) \---------------------------------/ \---------------/ definition of the gradient line list of color stops where <side-or-corner> = [left | right] || [top | bottom] and <color-stop-li...
scroll-padding-block - CSS: Cascading Style Sheets
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 scroll-padding properties define offsets for the optimal viewing region of the scrollport: the region used as the target region for placing things in view of the user. ...
...f the scrollport: the region used as the target region for placing things in view of the user. this allows the author to exclude regions of the scrollport that are obscured by other content (such as fixed-positioned toolbars or sidebars) or simply to put more breathing room between a targeted element and the edges of the scrollport. ...
scroll-padding-inline - CSS: Cascading Style Sheets
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 scroll-padding properties define offsets for the optimal viewing region of the scrollport: the region used as the target region for placing things in view of the user. ...
... the scrollport: the region used as the target region for placing things in view of the user. this allows the author to exclude regions of the scrollport that are obscured by other content (such as fixed-positioned toolbars or sidebars) or simply to put more breathing room between a targetted element and the edges of the scrollport. ...
scroll-padding - CSS: Cascading Style Sheets
urce 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 scroll-padding-* properties define offsets for the optimal viewing region of the scrollport: the region used as the target region for placing things in view of the user. ...
... the scrollport: the region used as the target region for placing things in view of the user. this allows the author to exclude regions of the scrollport that are obscured by other content (such as fixed-positioned toolbars or sidebars), or simply to put more breathing room between a targeted element and the edges of the scrollport. ...
scroll-snap-points-x - CSS: Cascading Style Sheets
ll-snap-points-x: initial; scroll-snap-points-x: unset; syntax values none the scroll container does not define any snap points. elements within the scroll container may still define snap points on behalf of the scroll container. repeat(<length-percentage>) defines an interval at which snap points are defined, starting from the container's relevant start edge. only positive lengths are allowed. percentages refer to the width of the container. formal definition initial valuenoneapplies toscroll containersinheritednopercentagesrelative to same axis of the padding-box of the scroll containercomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typediscrete formal syntax none | repeat( <length-percentage> )where <length-percentage> = <length>...
... scroll containercomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typediscrete formal syntax none | repeat( <length-percentage> )where <length-percentage> = <length> | <percentage> examples setting horizontal scroll snap points html <div id="container"> <div>1</div> <div>2</div> <div>3</div> </div> css #container { width: 200px; overflow: auto; white-space: nowrap; scroll-snap-points-x: repeat(100%); scroll-snap-type: mandatory; font-size: 0; } #container > div { width: 200px; height: 200px; display: inline-block; line-height: 200px; text-align: center; font-size: 100px; } #container > div:nth-child(even) { background-color: #87ea87; } #container > div:nth-child(odd) { background-color: #87ccea; } resu...
scroll-snap-points-y - CSS: Cascading Style Sheets
l-snap-points-y: initial; scroll-snap-points-y: unset; syntax values none the scroll container does not define any snap points. elements within the scroll container may still define snap points on behalf of the scroll container. repeat(<length-percentage>) defines an interval at which snap points are defined, starting from the container's relevant start edge. only positive lengths are allowed. percentages refer to the width of the container. formal definition initial valuenoneapplies toscroll containersinheritednopercentagesrelative to same axis of the padding-box of the scroll containercomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typediscrete formal syntax none | repeat( <length-percentage> )where <length-percentage> = <length>...
...ercomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typediscrete formal syntax none | repeat( <length-percentage> )where <length-percentage> = <length> | <percentage> examples setting vertical scroll snap points html <div id="container"> <div>1</div> <div>2</div> <div>3</div> </div> css #container { height: 200px; width: 220px; overflow-x: hidden; overflow-y: auto; scroll-snap-points-y: repeat(200px); scroll-snap-type: mandatory; font-size: 0; } #container > div { width: 200px; height: 200px; display: inline-block; line-height: 200px; text-align: center; font-size: 100px; } #container > div:nth-child(even) { background-color: #87ea87; } #container > div:nth-child(odd) { background-color: #87ccea; } re...
scrollbar-color - CSS: Cascading Style Sheets
gumbo beet greens corn soko endive gumbo gourd. parsley shallot courgette tatsoi pea sprouts fava bean collar...
...gumbo beet greens corn soko endive gumbo gourd. parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. dandelion cucumber earthnut pea pe...
text-decoration-line - CSS: Cascading Style Sheets
s */ text-decoration-line: underline overline; /* two decoration lines */ text-decoration-line: overline underline line-through; /* multiple decoration lines */ /* global values */ text-decoration-line: inherit; text-decoration-line: initial; text-decoration-line: unset; the text-decoration-line property is specified 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 deprecat...
...ormal 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">here's some text with wavy red underline!</p> <p class="both">this text has lines both above and below it.</p> .wavy { text-decoration-line: underline; text-decoration-style: wavy; text-decoration-color: red; } .both { text-decoration-line: underline overline; } specifications specification status comment css text decoration module level 3the definition of 'text-decoration-line' in that specification. candidate recommendation initial definition. the ...
text-decoration - CSS: Cascading Style Sheets
e rule p { text-decoration: underline; } would cause the entire paragraph to be underlined. the style rule em { text-decoration: none; } would not cause any change; the entire paragraph would still be underlined. however, the rule em { text-decoration: overline; } would cause a second decoration to appear on "some emphasized words". constituent properties this property is a shorthand for the following css properties: text-decoration-color text-decoration-line text-decoration-style text-decoration-thickness syntax the text-decoration property is specified as one or more space-separated values representing the various longhand text-decoration properties. values text-decoration-line sets the kind of decoration used, such as underline or line-through. text-decoration-color sets ...
..."over">this text has a line over it.</p> <p class="line">this text has a line going through it.</p> <p>this <a class="plain" href="#">link will not be underlined</a>, as links generally are by default. ...
text-emphasis - CSS: Cascading Style Sheets
when the current leading is not enough for the marks. text-emphasis doesn't reset the value of text-emphasis-position. this is because if the style and the color of emphasis marks may vary in a text, it is extremely unlikely that their position will. in the very rare cases when this is needed, the property text-emphasis-position. constituent properties this property is a shorthand for the following css properties: text-emphasis-color text-emphasis-style syntax /* initial value */ text-emphasis: none; /* no emphasis marks */ /* <string> value */ text-emphasis: 'x'; text-emphasis: '点'; text-emphasis: '\25b2'; text-emphasis: '*' #555; text-emphasis: 'foo'; /* should not use. it may be computed to or rendered as 'f' only */ /* keywords value */ text-emphasis: filled; text-emphasis...
...pen; text-emphasis: filled sesame; text-emphasis: open sesame; /* keywords value combined with a color */ text-emphasis: filled sesame #555; /* global values */ text-emphasis: inherit; text-emphasis: initial; text-emphasis: unset; values none no emphasis marks. filled the shape is filled with solid color. if neither filled nor open is present, this is the default. open the shape is hollow. dot display small circles as marks. the filled dot is '•' (u+2022), and the open dot is '◦' (u+25e6). circle display large circles as marks. the filled circle is '●' (u+25cf), and the open circle is '○' (u+25cb). this is the default shape in horizontal writing modes when no other shape is given. double-circle display double circles as marks. the filled double-circle is '◉' (u+25c...
text-underline-offset - CSS: Cascading Style Sheets
erline or line-through. syntax /* single keyword */ text-underline-offset: auto; /* length */ text-underline-offset: 0.1em; text-underline-offset: 3px; /* percentage */ text-underline-offset: 20%; /* global values */ text-underline-offset: inherit; text-underline-offset: initial; text-underline-offset: unset; the text-underline-offset property is specified as a single value from the list below. values auto the browser chooses the appropriate offset for underlines. <length> specifies the offset of underlines as a <length>, overriding the font file suggestion and the browser default. it is recommended to use em units so the offset scales with the font size. <percentage> specifies the offset of underlines as a <percentage> of 1 em in the element's font. a percentage inherits as a...
...applies toall elements. it also applies to ::first-letter and ::first-line.inheritedyespercentagesrefer to the font size of the element itselfcomputed valueas specifiedanimation typeby computed value type formal syntax auto | <length> | <percentage> examples <p class="oneline">here's some text with an offset wavy red underline!</p> <br> <p class="twolines">this text has lines both above and below it. only the bottom one is offset.</p> p { text-decoration: underline wavy red; text-underline-offset: 1em; } .twolines { text-decoration-color: purple; text-decoration-line: underline overline; } specifications specification status comment css text decoration module level 4the definition of 'text-underline-offset' in that specification. working draft ...
top - CSS: Cascading Style Sheets
Web › CSS › top
and send us a pull request. the effect of top depends on how the element is positioned (i.e., the value of the position property): when position is set to absolute or fixed, the top property specifies the distance between the element's top edge and the top edge of its containing block. when position is set to relative, the top property specifies the distance the element's top edge is moved below its normal position. when position is set to sticky, the top property is used to compute the sticky-constraint rectangle. when position is set to static, the top property has no effect. when both top and bottom are specified, position is set to absolute or fixed, and height is unspecified (either auto or 100%) both the top and bottom distances are respected. in all other situations, if height...
...ge>s of the height of the containing block */ top: 10%; /* keyword value */ top: auto; /* global values */ top: inherit; top: initial; top: unset; values <length> a negative, null, or positive <length> that represents: for absolutely positioned elements, the distance to the top edge of the containing block. for relatively positioned elements, the distance that the element is moved below its normal position. <percentage> a <percentage> of the containing block's height. auto specifies that: for absolutely positioned elements, the position of the element is based on the bottom property, while height: auto is treated as a height based on the content; or if bottom is also auto, the element is positioned where it should vertically be positioned if it were a static element.
unicode-bidi - CSS: Cascading Style Sheets
the unicode-bidi css property, together with the direction property, determines how bidirectional text in a document is handled. 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. /* keyword values */ unicode-bidi: normal; unicode-bidi: embed; unicode-bidi: isolate; unicode-bidi: bidi-override; unicode-bidi: isolate-override;...
...f the isolate keyword to the surrounding content and the override behavior of the bidi-override keyword to the inner content. plaintext this keyword makes the elements directionality calculated without considering its parent bidirectional state or the value of the direction property. the directionality is calculated using the p2 and p3 rules of the unicode bidirectional algorithm. this value allows the display of data that is already formatted using a tool following the unicode bidirectional algorithm. formal definition initial valuenormalapplies toall elements, though some values have no effect on non-inline elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax normal | embed | isolate | bidi-override | isolate-override | plaintext examples css .bible-q...
url() - CSS: Cascading Style Sheets
Web › CSS › url()
ss, or pointer, to the web resource to be included, or a data uri, optionally in single or double quotes. quotes are required if the url includes parentheses, whitespace, or quotes, unless these characters are escaped, or if the address includes control characters above 0x7e. double quotes cannot occur inside double quotes and single quotes cannot occur inside single quotes unless escaped. the following are all valid and equivalent: <css_property>: url("https://example.com/image.png") <css_property>: url('https://example.com/image.png') <css_property>: url(https://example.com/image.png) path references the id of an svg shape -- circle, ellipse, line, path, polygon, polyline, or rect -- using the shape's geometry as the path. <url-modifier> in the future, the url() function ma...
...ned in the specification. ...
user-select - CSS: Cascading Style Sheets
webkit/chromium-based browsers do implement the property as inherited, which violates the behavior described in the spec, an...
...he 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
d us a pull request. to both hide an element and remove it from the document layout, set the display property to none instead of using visibility. syntax /* keyword values */ visibility: visible; visibility: hidden; visibility: collapse; /* global values */ visibility: inherit; visibility: initial; visibility: unset; the visibility property is specified as one of the keyword values listed below. values visible the element box is visible. hidden the element box is invisible (not drawn), but still affects layout as normal. descendants of the element will be visible if they have visibility set to visible. the element cannot receive focus (such as when navigating through tab indexes). collapse for <table> rows, columns, column groups, and row groups, the row(s) or column(s) are ...
...gating through tab indexes). collapse for <table> rows, columns, column groups, and row groups, the row(s) or column(s) are hidden and the space they would have occupied is removed (as if display: none were applied to the column/row of the table). however, the size of other rows and columns is still calculated as though the cells in the collapsed row(s) or column(s) are present. this value allows for the fast removal of a row or column from a table without forcing the recalculation of widths and heights for the entire table. collapsed flex items are hidden, and the space they would have occupied is removed. for xul elements, the computed size of the element is always zero, regardless of other styles that would normally affect the size, although margins still take effect. for other ele...
Event reference
e has been changed. moztouchdown mozilla specific a touch point is placed on the touch surface (use touchstart instead). moztouchmove mozilla specific a touch point is moved along the touch surface (use touchmove instead). moztouchup mozilla specific a touch point is removed from the touch surface (use touchend instead). overflow uievent mozilla specific an element has been overflowed by its content or has been rendered for the first time in this state (only works for elements styled with overflow != visible). smartcard-insert mozilla specific a smartcard has been inserted. smartcard-remove mozilla specific a smartcard has been removed. stkcommand firefox os s...
...smartcard-remove mozilla specific a smartcard has been removed. stkcommand firefox os specific the stk proactive command is issued from icc. stksessionend firefox os specific the stk session is terminated by icc. touchenter touchevent touch events removed touchleave touchevent touch events removed underflow uievent mozilla specific an element is no longer overflowed by its content (only works for elements styled with overflow != visible). uploadprogress progressevent mozilla specific upload is in progress (see progress). ussdreceived firefox os specific a new ussd message is received mscontentzoom microsoft specific ...
Orientation and motion data explained - Developer guides
oordinate frames to consider when using orientation and motion events: earth coordinate frame the earth coordinate frame is the coordinate frame fixed on the center of the earth; that is, the axes are aligned based on the pull of gravity and the standard magnetic north orientation. we use upper-case letters ("x", "y", and "z") to describe the axes of the earth coordinate frame. the x axis follows along the ground plane, perpendicular to the y axis and positive toward the east (and therefore negative toward the west). the y axis follows along the ground plane, and is positive toward true north (that is, the north pole, not magnetic north) and negative toward true south. the z axis is perpendicular to the ground plane; think of it as a line drawn between the device and the center of the ...
...ue south. the z axis is perpendicular to the ground plane; think of it as a line drawn between the device and the center of the earth. the value of the z coordinate is positive upward (away from the center of the earth) and negative downward (toward the center of the earth). device coordinate frame the device coordinate frame is the coordination frame fixed on the center of the device. we use lower-case letters ("x", "y", and "z") to describe the axes of the device coordinate frame. the x axis is in the plane of the screen and is positive toward the right and negative toward the left. the y axis is in the plane of the screen and is positive toward the top and negative toward the bottom. the z axis is perpendicular to the screen or keyboard, and is positive extending outward from th...
Content categories - Developer guides
portions of the html specification. main content categories metadata content elements belonging to the metadata content category modify the presentation or the behavior of the rest of the document, set up links to other documents, or convey other out of band information. elements belonging to this category are <base>, <command>, <link>, <meta>, <noscript>, <script>, <style> and <title>. flow content elements belonging to the flow content category typically contain text or embedded content. they are: <a>, <abbr>, <address>, <article>, <aside>, <audio>, <b>,<bdo>, <bdi>, <blockquote>, <br>, <button>, <canvas>, <cite>, <code>, <command>, <data>, <datalist>, <del>, <details>, <dfn>, <div>, <dl>, <em>, <embed>, <fieldset>, <figure>, <footer>, <form>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, ...
...<img>, if the usemap attribute is present <input>, if the type attribute is not in the hidden state <menu>, if the type attribute is in the toolbar state <object>, if the usemap attribute is present <video>, if the controls attribute is present palpable content content is palpable when it's neither empty or hidden; it is content that is rendered and is substantive. elements whose model is flow content or phrasing content should have at least one node which is palpable. form-associated content form-associated content comprises elements that have a form owner, exposed by a form attribute. a form owner is either the containing <form> element or the element whose id is specified in the form attribute. <button> <fieldset> <input> <keygen> <label> <meter> <object> <output> <pro...
XHTML - Developer guides
Web › Guide › HTML › XHTML
xhtml is a term that was historically used to describe html documents written to conform with xml syntax rules. the following example shows an html document and corresponding "xhtml" document, and the accompanying http content-type headers they should be served with. html document content-type: text/html <!doctype html> <html lang=en> <head> <meta charset=utf-8> <title>html</title> </head> <body> <p>i am a html document</p> </body> </html> xhtml document content-type: application/xhtml+xml <?xml version="1.0" encoding="utf-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>xhtml</title> </head> <body> <p>i am a xhtml document</p> </body> </html> in practice, very few "xhtml" documents are served over the web with ...
...ed over the web with a content-type: application/xhtml+xml header. ...
Mobile-friendliness - Developer guides
reat example of this is alaska air’s website. their desktop site focuses on getting visitors to book trips. mobile users, however, are probably more interested in checking-in for a flight or seeing if their flight is delayed. they’ve adjusted their site’s content to reflect this, and it meets the needs of mobile users. goal #3 (performance) “give your users a smooth experience, even on a slow connection.” though things have been getting better in recent years, browsing the internet over a wireless 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 tar...
...eep 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 approaches aim to achieve each of these goals by different means. separate sites responsive design a hybrid approach original document information originally published on 4 may, 2011 on the mozilla webdev blog as "approaches to mobile web development part 1 - what is mobile friendliness?", by jason grlicky. ...
Parsing and serializing XML - Developer guides
ocument or document as appropriate based on the input data. xmlhttprequest loads content from a url; xml content is returned as an xml document object with a dom tree built from the xml itself. xpath a technology for creating strings that contain addresses for specific portions of an xml document, and locating xml nodes based on those addresses. creating an xml document using one of the following approaches to create an xml document (which is an instance of document. parsing strings into dom trees this example converts an xml fragment in a string into a dom tree using a domparser: var smystring = '<a id="a"><b id="b">hey!</b></a>'; var oparser = new domparser(); var odom = oparser.parsefromstring(smystring, "application/xml"); // print the name of the root element or error message ...
... some practical benefits as well. note: there is in fact an htmldocument interface as well, but it is not necessarily an independent type. in some browsers it is, while in others it is simply an alias for the document interface. serializing an xml document given a document, you can serialize the document's dom tree back into xml using the xmlserializer.serializetostring() method. use the following approaches to serialize the contents of the xml document you created in the previous section. serializing dom trees to strings first, create a dom tree as described in how to create a dom tree. alternatively, use a dom tree obtained from xmlhttprequest. to serialize the dom tree doc into xml text, call xmlserializer.serializetostring(): var oserializer = new xmlserializer(); var sxml = ose...
The Unicode Bidirectional Text Algorithm - Developer guides
verride the default behavior of the algorithm; include info about isolating ranges etc. overiding bidi using unicode control characters unicode provides a number of special control characters that make it possible to control directionality of ranges of text. there are two sets of control characters; one set opens the override, and another restores the original directionality. you must always follow each opening character with an appropriate closing character. initial unicode bidi algorithm control characters character code point html entity markup equivalent description left-to-right isolate (lri) u+2066 &#x2066; dir="ltr" sets the base direction to ltr, isolating the embedded content from the surrounding text right-to-left isolate (l...
...se direction to rtl, isolating the embedded content from the surrounding text first strong isolate (fsi) u+2068 &#x2068; dir="auto" isolates the content and sets the base direction according to the first strongly-typed directional character in the embedded content left-to-right embedding (lre) u+202a &#x202a; dir="ltr" sets the base direction to ltr but allows the embedded text to interact with the surrounding content; this risks the effect spilling over to the outer content right-to-left embedding (rle) u+202b &#x202b; dir="rtl" sets the base direction to rtl, but lets the embedded text interact with the surrounding content, risking spillover effects left-to-right override (lro) u+202d &#x202d; <bdo dir="ltr"> ...
HTML attribute: crossorigin - HTML: Hypertext Markup Language
and <video> elements, provides support for cors, defining how the element handles crossorigin requests, thereby enabling the configuration of the cors requests for the element's fetched data. depending on the element, the attribute can be a cors settings attribute. the crossorigin content attribute on media elements is a cors settings attribute. these attributes are enumerated, and have the following possible values: keyword description anonymous cors requests for this element will have the credentials flag set to 'same-origin'. use-credentials cors requests for this element will have the credentials flag set to 'include'. "" setting the attribute name to an empty value, like crossorigin or crossorigin="", is the same as anonymous. by...
... 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/example-framework.js" crossorigin="anonymous"></script> example: webmanifest with credentials the use-credentials value must be used when fetching a manifest that requires credentials, even if the file is from the same origin. ...
HTML attribute: multiple - HTML: Hypertext Markup Language
="emails"> if and only if the multiple attribute is specified, the value can be a list of properly-formed comma-separated e-mail addresses. any trailing and leading whitespace is removed from each address in the list. when multiple is set on the file input type, the user can select one or more files. the user can choose multiple files from the file picker in any way that their chosen platform allows (e.g. by holding down shift or control, and then clicking). <input type="file" multiple name="uploads" id="uploads"> when the attribute is omitted, the user can only select a single file per <input>. the multiple attribute on the <select> element represents a control for selecting zero or more options from the list of options. otherwise, the <select> element represents a control for selecting...
... html5the definition of 'multiple attribute' in that specification. recommendation accessibility concerns provide instructions to help users understand how to complete the form and use individual form controls. indicate any required 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 c...
HTML attribute: step - HTML: Hypertext Markup Language
Web › HTML › Attributes › step
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 stepping value for time is 1 second, with 900 being equal to 15 minutes. default values for step input type value example date 1 (day) <input type="date" min="2019-1...
... ...
DASH Adaptive Streaming for HTML 5 Video - HTML: Hypertext Markup Language
see bug 778617 for details. ...
... 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. using dash - server side first you'll need to convert your webm video to a dash manifest with the accompanying video files in various bit rates. to start with you'll only need the ffpmeg program from ffmpeg.org, with libvpx and libvorbis support for webm video and audio, at least version 2.5 (probably; this w...
<h1>–<h6>: The HTML Section Heading elements - HTML: Hypertext Markup Language
the html <h1>–<h6> elements represent six levels of section headings. <h1> is the highest section level and <h6> is the lowest. 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, heading content, palpable content. permitted content phrasing content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content; don't use a heading element as a child of the <hgroup> element — it is now deprecated. implicit aria role heading permitted aria roles tab, p...
...l not result in an error, but using only one is seen as a best practice. it makes logical sense — <h1> is the most important heading, and tells you what the purpose of the overall page is. you wouldn't have a book with more than one title, or a movie with more than one name! having a single top-level title is also arguably better for screenreader users, and seo. examples all headings the following code shows all the heading levels, in use. <h1>heading level 1</h1> <h2>heading level 2</h2> <h3>heading level 3</h3> <h4>heading level 4</h4> <h5>heading level 5</h5> <h6>heading level 6</h6> here is the result of this code: example page the following code shows a few headings with some content under them. <h1>heading elements</h1> <h2>summary</h2> <p>some text here...</p> <h2>exampl...
<address>: The Contact Address element - HTML: Hypertext Markup Language
Web › HTML › Element › address
oordinates, and so forth. the <address> element should include the name of the person, people, or organization to which the contact information refers. <address> can be used in a variety of contexts, such as providing a business's contact information in the page header, or indicating the author of an article by including an <address> element within the <article>. content categories flow content, palpable content. permitted content flow content, but with no nested <address> element, no heading content (<hgroup>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>), no sectioning content (<article>, <aside>, <section>, <nav>), and no <header> or <footer> element. tag omission none, both the starting and ending tag are mandatory. permitted parents any element tha...
...alpable content. permitted content flow content, but with no nested <address> element, no heading content (<hgroup>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>), no sectioning content (<article>, <aside>, <section>, <nav>), and no <header> or <footer> element. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content, but always excluding <address> elements (according to the logical principle of symmetry, if <address> tag, as a parent, can not have nested <address> element, then the same <address> content can not have <address> tag as its parent). implicit aria role no corresponding role permitted aria roles any dom interface htmlelement prior to gecko 2.0 (firefox ...
<aside>: The Aside element - HTML: Hypertext Markup Language
Web › HTML › Element › aside
nt whose content is only indirectly related to the document's main content. asides are frequently presented as sidebars or call-out boxes. 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, sectioning content, palpable content. permitted content flow content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. note that an <aside> element must not be a descendant of an <address> element. implicit aria role complementary permitted aria roles fee...
...be a descendant of an <address> element. implicit aria role complementary permitted aria roles feed, none, note, presentation, region, search dom interface htmlelement attributes this element only includes the global attributes. usage notes do not use the <aside> element to tag parenthesized text, as this kind of text is considered part of the main flow. examples using <aside> this example uses <aside> to mark up a paragraph in an article. the paragraph is only indirectly related to the main article content: <article> <p> the disney movie <cite>the little mermaid</cite> was first released to theatres in 1989. </p> <aside> <p> the movie earned $87 million during its initial release. </p> </aside> <p> more ...
<base>: The Document Base URL element - HTML: Hypertext Markup Language
Web › HTML › Element › base
n empty element. tag omission there must be no closing tag. permitted parents a <head> that doesn't contain another <base> element. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlbaseelement attributes this element's attributes include the global attributes. if either of the following attributes are specified, this element must come before other elements with attribute values of urls, such as <link>’s href attribute. href the base url to be used throughout the document for relative urls. absolute and relative urls are allowed. target a keyword or author-defined name of the default browsing context to show the results of navigation from <a>, <area>, or <form> elemen...
... _blank: show the result in a new, unnamed browsing context. ...
<blockquote>: The Block Quotation element - HTML: Hypertext Markup Language
ce of the quotation may be given using the cite attribute, while a text representation of the source can be given using the <cite> 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. content categories flow content, sectioning root, palpable content. permitted content flow content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. implicit aria role no corresponding role permitted aria roles any dom interface htmlquoteelement attributes this elemen...
...argin shorthand property. to include shorter quotes inline rather than in a separate block, use the <q> (quotation) element. example this example demonstrates the use of the <blockquote> element to quote a passage from rfc 1149, a standard for the transmission of ip datagrams on avian carriers. <blockquote cite="https://tools.ietf.org/html/rfc1149"> <p>avian carriers can provide high delay, low throughput, and low altitude service. the connection topology is limited to a single point-to-point path for each carrier, used with standard carriers, but many carriers can be used without significant interference with each other, outside of early spring. this is because of the 3d ether space available to the carriers, in contrast to the 1d ether used by ieee802.3. the carriers ...
<body>: The Document Body element - HTML: Hypertext Markup Language
Web › HTML › Element › body
permitted parents it must be the second element of an <html> element. ...
... permitted parents it must be the second element of an <html> element. ...
<br>: The Line Break element - HTML: Hypertext Markup Language
Web › HTML › Element › br
reate a line break in a block of text. as such, it has no dimensions or visual output of its own, and there is very little you can do to style it. you can set a margin on <br> elements themselves to increase the spacing between the lines of text in the block, but this is a bad practice — you should use the line-height property that was designed for that purpose. examples simple br in the following example we use <br> elements to create line breaks between the different lines of a postal address: mozilla<br> 331 e. evelyn avenue<br> mountain view, ca<br> 94041<br> usa<br> the result looks like so: accessibility concerns creating separate paragraphs of text using <br> is not only bad practice, it is problematic for people who navigate with the aid of screen reading technology. scre...
...blematic for people who navigate with the aid of screen reading technology. screen readers may announce the presence of the element, but not any content contained within <br>s. this can be a confusing and frustrating experience for the person using the screen reader. use <p> elements, and use css properties like margin to control their spacing. technical summary content categories flow content, phrasing content. permitted content none, it is an empty element. tag omission must have a start tag, and must not have an end tag. in xhtml documents, write this element as <br />. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles none, presentation ...
<cite>: The Citation element - HTML: Hypertext Markup Language
Web › HTML › Element › cite
title of that work. the reference may be in an abbreviated form according to context-appropriate conventions related to citation metadata. 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. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement up to gecko 1.9.2 (firefox...
... no corresponding role permitted aria roles any dom interface htmlelement up to gecko 1.9.2 (firefox 4) inclusive, firefox implements the htmlspanelement interface for this element. attributes this element only includes the global attributes. ...
<col> - HTML: Hypertext Markup Language
Web › HTML › Element › col
ml <col> element defines a column within a table and is used for defining common semantics on all common cells. it is generally found within a <colgroup> 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. <col> allows styling columns using css, but only a few properties will have an effect on the column (see the css 2.1 specification for a list). content categories none. permitted content none, it is an empty element. tag omission it must have start tag, but must not have an end tag. permitted parents <colgroup> only, though it can be implicitly defined as its ...
... implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmltablecolelement attributes this element includes the global attributes. span this attribute contains a positive integer indicating the number of consecutive columns the <col> element spans. if not present, its default value is 1. deprecated attributes the following attributes are deprecated and should not be used. they are documented below for reference when updating existing code and for historical interest only. align this enumerated attribute specifies how horizontal 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 righ...
<colgroup> - HTML: Hypertext Markup Language
Web › HTML › Element › colgroup
categories none. permitted content if the span attribute is present: none, it is an empty element. if the attribute is not present: zero or more <col> element tag omission the start tag may be omitted, if it has a <col> element as its first child and if it is not preceded by a <colgroup> whose end tag has been omitted. the end tag may be omitted, if it is not followed by a space or a comment. permitted parents a <table> element. the <colgroup> must appear after any optional <caption> element but before any <thead>, <th>, <tbody>, <tfoot> and <tr> element. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmltablecolelement attributes this element's attributes...
...oup> element spans. if not present, its default value is 1. note: this attribute is applied on the attributes of the column group, it has no effect on the css styling rules associated with it or, even more, to the cells of the column's members of the group. the span attribute is not permitted if there are one or more <col> elements within the <colgroup>. deprecated attributes the following attributes are deprecated and should not be used. they are documented below for reference when updating existing code and for historical interest only. align this enumerated attribute specifies how horizontal 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 righ...
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › content
sent in early draft of the specifications and implemented in several browsers, this element has been removed in later versions of the spec, and should not be used. it is documented here to assist in adapting code written during the time it was included in the spec to work with newer versions of the specification. content categories transparent content. permitted content flow content. tag omission none, both the starting and ending tag are mandatory. permitted parent elements any element that accepts flow content. dom interface htmlcontentelement attributes this element includes the global attributes. select a comma-separated list of selectors. these have the same syntax as css selectors. they select the content to inser...
...ocument.queryselector('div'); // create a shadow dom on the <div> var shadowroot = mycontent.createshadowroot(); // insert into the shadow dom a new heading and // part of the original content: the <p> tag. shadowroot.innerhtml = '<h2>inserted heading</h2> <content select="p"></content>'; </script> </body> </html> if you display this in a web browser it should look like the following. specifications this element is no longer defined by any specifications. 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. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfi...
<data> - HTML: Hypertext Markup Language
Web › HTML › Element › data
nks a given piece of content with a machine-readable translation. if the content is time- or date-related, the <time> element must be used. 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. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmldataelement attributes thi...
... permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted 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...
<del>: The Deleted Text element - HTML: Hypertext Markup Language
Web › HTML › Element › del
ded to the document. 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 element is often (but need not be) rendered by applying a strike-through style to the text. content categories phrasing content or flow content. permitted content transparent. tag omission 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 any dom interface htmlmodelement attributes this element's attributes include the global ...
...been deleted.</p></del> result accessibility concerns the presence of the del element is not announced by most screen reading technology in its default configuration. it can be made to be announced by using the css content property, along with the ::before and ::after pseudo-elements. del::before, del::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } del::before { content: " [deletion start] "; } del::after { content: " [deletion end] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity. because of this, it is important to not abuse this technique and only apply it in situations where not knowing content has be...
<details>: The Details disclosure element - HTML: Hypertext Markup Language
Web › HTML › Element › details
send us a pull request. note: the common use of a triangle which rotates or twists around to represent opening or closing the widget is why these are sometimes called "twisties." a <details> widget can be in one of two states. the default closed state displays only the triangle and the label inside <summary> (or a user agent-defined default string if no <summary>). this might look like the following: here we see a standard disclosure widget with the label "system requirements", in its default closed state. when the user clicks on the widget or focuses it then presses the space bar, it "twists" open, revealing its contents: from there, you can use css to style the disclosure widget, and you can programmatically open and close the widget by setting/removing its open attribute. by def...
...details contained within. note: unfortunately, at this time there's no built-in way to animate the transition between open and closed. fully standards-compliant implementations automatically apply the css display: list-item to the <summary> element. you can use this to customize its appearance further. see customizing the disclosure widget for further details. content categories flow content, sectioning root, interactive content, palpable content. permitted content one <summary> element followed by flow content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. implicit aria role group permitted aria roles no role permitted dom interfa...
<div>: The Content Division element - HTML: Hypertext Markup Language
Web › HTML › Element › div
the html content division element (<div>) is the generic container for flow content. it has no effect on the content or layout until styled using css. 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. as a "pure" container, the <div> element does not inherently represent anything. instead, it's used to group content so it can be easily styled using the class or id attributes, marking a section of a document as being written in a different language (using the lang attribute), and so on. content categories flow content, palpable content. permitted content flow content. or (in whatwg html):...
...ead, it's used to group content so it can be easily styled using the class or id attributes, marking a section of a document as being written in a different language (using the lang attribute), and so on. content categories flow content, palpable content. permitted content flow content. or (in whatwg html): if the parent is a <dl> element: one or more <dt> elements followed by one or more <dd> elements, optionally intermixed with <script> and <template> elements. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. or (in whatwg html): <dl> element. implicit aria role no corresponding role permitted aria roles any dom interface htm...
<dt>: The Description Term element - HTML: Hypertext Markup Language
Web › HTML › Element › dt
the html <dt> element specifies a term in a description or definition list, and as such must be used inside a <dl> element. it is usually followed by a <dd> element; however, multiple <dt> elements in a row indicate several terms that are all defined by the immediate next <dd> element. the subsequent <dd> (description details) element provides the definition or other related text associated with the term specified using <dt>. 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. ...
...) element provides the definition or other related text associated with the term specified using <dt>. 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 none. permitted content flow content, but with no <header>, <footer>, sectioning content or heading content descendants. tag omission must have a start tag. the end tag may be omitted if this element is immediately followed by another <dt> or a <dd> element, or if there is no more content in the parent element. permitted parents before a <dt> or a <dd> element, inside a <dl> or (in whatwg html) a <div...
<em>: The Emphasis element - HTML: Hypertext Markup Language
Web › HTML › Element › em
nt marks text that has stress emphasis. the <em> element can be nested, with each level of nesting indicating a greater degree of emphasis. 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. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement up to gecko 1.9.2 (firefox...
...asis or importance on the word "queen mary". it is merely indicated that the object in question is not a queen named mary, but a ship named queen mary. another example for <i> could be: "the word the is an article". example the <em> element is often used to indicate an implicit or explicit contrast. <p> in html 5, what was previously called <em>block-level</em> content is now called <em>flow</em> content. </p> result specifications specification status comment html living standardthe definition of '<em>' in that specification. living standard html5the definition of '<em>' in that specification. recommendation html 4.01 specificationthe definition of '<em>' in that specification. recommendation ...
<embed>: The Embed External Content element - HTML: Hypertext Markup Language
Web › HTML › Element › embed
ote: 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 omission must have a start tag, and must not have an end tag. permitted parents any element that accepts embedded content. implicit aria role no corresponding role permitted aria roles application, docum...
...hat accepts embedded content. implicit aria role no corresponding role permitted aria roles application, document, img, none, presentation dom interface htmlembedelement attributes this element's attributes include the global attributes. height the displayed height of the resource, in css pixels. this must be an absolute value; percentages are not allowed. src the url of the resource being embedded. type the mime type to use to select the plug-in to instantiate. width the displayed width of the resource, in css pixels. this must be an absolute value; percentages are not allowed. usage notes you can use the object-position property to adjust the positioning of the embedded object within the element's frame, and the object-fit property to...
<fieldset>: The Field Set element - HTML: Hypertext Markup Language
Web › HTML › Element › fieldset
active examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. as the example above shows, the <fieldset> element provides a grouping for a part of an html form, with a nested <legend> element providing a caption for the <fieldset>. it takes few attributes, the most notable of which are form, which can contain the id of a <form> on the same page, allowing you to make the <fieldset> part of that <form> even if it is not nested inside it, and disabled, which allows you to disable the <fieldset> and all its contents in one go. attributes this element includes the global attributes. disabled if this boolean attribute is set, all form controls that are descendants of the <fieldset>, are disabled, meaning they are not editable and won't be subm...
...led <fieldset>. <form action="#"> <fieldset disabled> <legend>disabled fieldset</legend> <div> <label for="name">name: </label> <input type="text" id="name" value="chris"> </div> <div> <label for="pwd">archetype: </label> <input type="password" id="pwd" value="wookie"> </div> </fieldset> </form> technical summary content categories flow content, sectioning root, listed, form-associated element, palpable content. permitted content an optional <legend> element, followed by flow content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. implicit aria role group permitted aria roles radiogroup, presen...
<header> - HTML: Hypertext Markup Language
Web › HTML › Element › header
ntroductory or navigational aids. it may contain some heading elements but also a logo, a search form, an author name, and other elements. 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, palpable content. permitted content flow content, but with no <header> or <footer> descendant. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. note that a <header> element must not be a descendant of an <address>, <footer> or another <header> element. implicit aria rol...
...ed to usually contain the surrounding section's heading (an h1–h6 element), but this is not required. historical usage although the <header> element didn't make its way into specifications until html5, it actually existed at the very beginning of html. as seen in the very first website, it was originally used as the <head> element. at some point, it was decided to use a different name. this allowed <header> to be free to fill a different role later on. attributes this element only includes the global attributes. examples page header <header> <h1>main page title</h1> <img src="mdn-logo-sm.png" alt="mdn logo"> </header> article header <article> <header> <h2>the planet earth</h2> <p>posted on wednesday, <time datetime="2017-10-04">4 october 2017</time> by jane smith</p>...
<input type="submit"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › submit
you don't specify a value, the button will have a default label, chosen by the user agent. this label is likely to be something along the lines of "submit" or "submit query." here's an example of a submit button with a default label in your browser: <input type="submit"> additional attributes in addition to the attributes shared by all <input> elements, submit button inputs support the following attributes: attribute description formaction the url to which to submit the form's data; overrides the form's action attribute, if any formenctype a string specifying the encoding type to use for the form data formmethod the http method (get or post) to use when submitting the form. formnovalidate a boolean which, if present, mea...
..."> and <button> elements. formenctype a string that identifies the encoding method to use when submitting the form data to the server. there are three permitted values: application/x-www-form-urlencoded this, the default value, sends the form data as a string after url encoding the text using an algorithm such as encodeuri(). multipart/form-data uses the formdata api to manage the data, allowing for files to be submitted to the server. you must use this encoding type if your form includes any <input> elements of type file (<input type="file">). text/plain plain text; mostly useful only for debugging, so you can easily see the data that's to be submitted. if specified, the value of the formenctype attribute overrides the owning form's action attribute. this attribute is also avail...
<ins> - HTML: Hypertext Markup Language
Web › HTML › Element › ins
ocument. you can use the <del> element to similarly represent a range of text that has been deleted from the document. 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 phrasing content or flow content. permitted content transparent. tag omission 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 any dom interface htmlmodelement attributes this element includes the global attributes. ...
...s been inserted</ins> result accessibility concerns the presence of the <ins> element is not announced by most screen reading technology in its default configuration. it can be made to be announced by using the css content property, along with the ::before and ::after pseudo-elements. ins::before, ins::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } ins::before { content: " [insertion start] "; } ins::after { content: " [insertion end] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity. because of this, it is important to not abuse this technique and only apply it in situations where not knowing content has ...
<main> - HTML: Hypertext Markup Language
Web › HTML › Element › main
l 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. tag omission none; both the starting and ending tags are mandatory. permitted parents where flow content is expected, but only if it is a hierarchically correct main element. implicit aria role main permitted aria roles no role permitted dom interface htmlelement ...
... --> accessibility concerns landmark the <main> element behaves like a main landmark role. landmarks can be used by assistive technology to quickly identify and navigate to large sections of the document. prefer using the <main> element over declaring role="main", unless there are legacy browser support concerns. skip navigation skip navigation, also known as "skipnav", is a technique that allows an assistive technology user to quickly bypass large sections of repeated content (main navigation, info banners, etc.). this lets the user access the main content of the page faster. adding an id attribute to the <main> element lets it be a target of a skip navigation link. <body> <a href="#main-content">skip to main content</a> <!-- navigation and header content --> <main id="main-co...
<map> - HTML: Hypertext Markup Language
Web › HTML › Element › map
the html <map> element is used with <area> elements to define an image map (a clickable link 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. content categories flow content, phrasing content, palpable content. permitted content any transparent element. tag omission 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 htmlmapelement attributes this element includes ...
...attributes must have the same value. examples <map name="primary"> <area shape="circle" coords="75,75,75" href="left.html"> <area shape="circle" coords="275,75,75" href="right.html"> </map> <img usemap="#primary" src="https://udn.realityripple.com/samples/6a/7e559101b3.png" alt="350 x 150 pic"> result expected live example output the live example above should appear similar to the following images (when using your keyboard tab key): for the left.html link: for the right.html link specifications specification status comment html living standardthe definition of '<map>' in that specification. living standard html5the definition of '<map>' in that specification. recommendation html 4.01 specificationthe definition o...
<mark>: The Mark Text element - HTML: Hypertext Markup Language
Web › HTML › Element › mark
is marked or highlighted for reference or notation purposes, due to the marked passage's relevance or importance in the enclosing context. 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. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this el...
... the results look like this: accessibility concerns the presence of the mark element is not announced by most screen reading technology in its default configuration. it can be made to be announced by using the css content property, along with the ::before and ::after pseudo-elements. mark::before, mark::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } mark::before { content: " [highlight start] "; } mark::after { content: " [highlight end] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity. because of this, it is important to not abuse this technique and only apply it in situations where not knowing content ha...
<noframes>: The Frame Fallback element - HTML: Hypertext Markup Language
Web › HTML › Element › noframes
ames or frame fallback element, <noframes>, provides content to be presented in browsers that don't support (or have disabled support for) the <frame> element. although most commonly-used browsers support frames, there are exceptions, including certain special-use browsers including some mobile browsers, as well as text-mode browsers. a <noframes> element can contain any html elements that are allowed within the body of an html document, with the exception of the <frameset> and <frame> elements, since using frames when they aren't supported doesn't make sense. <noframes> can be used to present a message explaining that the user's browser doesn't support frames, but ideally should be used to present an alternate form of the site that doesn't use frames but still offers the same or similar fu...
... see a frameset with two frames. in addition, <noframes> is used to present an explanatory message if the user agent doesn't support frames. <frameset cols="50%,50%"> <frame src="https://developer.mozilla.org/en/html/element/frameset" /> <frame src="https://developer.mozilla.org/en/html/element/frame" /> <noframes><p>it seems your browser does not support frames or is configured to not allow them.</p></noframes> </frameset> specifications specification status comment html5the definition of 'noframes' in that specification. recommendation html 4.01 specificationthe definition of '<noframes>' in that specification. recommendation ...
<object> - HTML: Hypertext Markup Language
Web › HTML › Element › object
ent represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin. 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; embedded content, palpable content; if the element has a usemap attribute, interactive content; listed, submittable form-associated element. permitted content zero or more <param> elements, then transparent. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts embedded content. ...
... position of the element in the tabbing navigation order for the current document. type the content type of the resource specified by data. at least one of data and type must be defined. typemustmatchhtml5 this boolean attribute indicates if the type attribute and the actual content type of the resource must match to be used. usemap a hash-name reference to a <map> element; that is a '#' followed by the value of a name of a map element. width the width of the display resource, in css pixels. -- (absolute values only. no percentages) examples embed a flash movie <!-- embed a flash movie --> <object data="movie.swf" type="application/x-shockwave-flash"></object> <!-- embed a flash movie with parameters --> <object data="movie.swf" type="application/x-shockwave-flash"> <param na...
<output>: The Output element - HTML: Hypertext Markup Language
Web › HTML › Element › output
permitted content phrasing content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. ...
...t, the <output> is associated with its ancestor <form> element, if any.) this attribute lets you associate <output> elements to <form>s anywhere in the document, not just inside a <form>. it can also override an ancestor <form> element. name the element's name. used in the form.elements api. the <output> value, name, and contents are not submitted during form submission. examples in the following example, the form provides a slider whose value can range between 0 and 100, and an <input> element into which you can enter a second number. the two numbers are added together, and the result is displayed in the <output> element each time the value of any of the controls changes. <form oninput="result.value=parseint(a.value)+parseint(b.value)"> <input type="range" id="b" name="b" value="50...
<p>: The Paragraph element - HTML: Hypertext Markup Language
Web › HTML › Element › p
ally represented in visual media as blocks of text separated from adjacent blocks by blank lines and/or first-line indentation, but html paragraphs can be any structural grouping of related content, such as images or form fields. paragraphs are block-level elements, and notably will automatically close if another block-level element is parsed before the closing </p> tag. see “tag omission” below. 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, palpable content. permitted content phrasing content. tag omission the start tag is required. the end...
... 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, palpable content. permitted content phrasing content. tag omission the start tag is required. the end tag may be omitted if the <p> element is immediately followed by an <address>, <article>, <aside>, <blockquote>, <div>, <dl>, <fieldset>, <footer>, <form>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <header>, <hr>, <menu>, <nav>, <ol>, <pre>, <section>, <table>, <ul> or another <p> element, or if there is no more content in the parent element and the parent element is not an <a> element. permitted parents any element that accepts flow content. ...
<progress>: The Progress Indicator element - HTML: Hypertext Markup Language
Web › HTML › Element › progress
the html <progress> element displays an indicator showing the completion progress of a task, typically displayed as a progress bar. 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, labelable content, palpable content. permitted content phrasing content, but there must be no <progress> element among its descendants. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. implicit aria role progressbar permitted aria roles no...
... 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 on windows 7, the resulting progress looks like this: ...
<s> - HTML: Hypertext Markup Language
Web › HTML › Element › s
er, <s> is not appropriate when indicating document edits; for that, use the <del> and <ins> elements, 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. content categories phrasing content or flow content. permitted content phrasing content. tag omission 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 any dom interface htmlelement attributes this element only includes the global attri...
...y's special: salmon</span> sold out accessibility concerns the presence of the s element is not announced by most screen reading technology in its default configuration. it can be made to be announced by using the css content property, along with the ::before and ::after pseudo-elements. s::before, s::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } s::before { content: " [start of stricken text] "; } s::after { content: " [end of stricken text] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity. because of this, it is important to not abuse this technique and only apply it in situations where not knowing co...
<samp>: The Sample Output element - HTML: Hypertext Markup Language
Web › HTML › Element › samp
m a computer program. its contents are typically rendered using the browser's default monospaced font (such as courier or lucida console). 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. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this el...
...ludes text entered by the user. for example, consider this text presenting a transcript of a linux (or macos) console session: html <pre> <samp><span class="prompt">mike@interwebz:~$</span> <kbd>md5 -s "hello world"</kbd> md5 ("hello world") = 3e25960a79dbc69b674cd4ec67a72c62 <span class="prompt">mike@interwebz:~$</span> <span class="cursor">█</span></samp></pre> note the use of <span> to allow customization of the appearance of specific portions of the sample text such as the shell prompts and the cursor. note also the use of <kbd> to represent the command the user entered at the prompt in the sample text. css the css that achieves the appearance we want is: .prompt { color: #b00; } samp > kbd { font-weight: bold; } .cursor { color: #00b; } this simply gives the prompt and ...
<source>: The Media or Image Source element - HTML: Hypertext Markup Language
Web › HTML › Element › source
teractive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. content categories none. permitted content none, it is an empty element. tag omission it must have a start tag, but must not have an end tag. permitted parents a media element—<audio> or <video>—and it must be placed before any flow content or <track> element. a <picture> element, and it must be placed before the <img> element. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlsourceelement attributes this element includes the global attributes. media media query of the resource's intended media; this should be used only i...
... value of this attribute is ignored when the <source> element is placed inside a <picture> element. srcset a list of one or more strings separated by commas indicating a set of possible images represented by the source for the browser to use. each string is composed of: one url specifying an image. a width descriptor, which consists of a string containing a positive integer directly followed by "w", such as 300w. the default value, if missing, is the infinity. a pixel density descriptor, that is a positive floating number directly followed by "x". the default value, if missing, is 1x. each string in the list must have at least a width descriptor or a pixel density descriptor to be valid. among the list, there must be only one string containing the same tuple of width descript...
<td>: The Table Data Cell element - HTML: Hypertext Markup Language
Web › HTML › Element › td
> element defines a cell of a table that contains data. it participates in the table model. 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 sectioning root. permitted content flow content. tag omission the start tag is mandatory. the end tag may be omitted, if it is immediately followed by a <th> or <td> element or if there are no more data in its parent element. permitted parents a <tr> element. implicit aria role cell if a descendant of a <table> element permitted aria roles any dom interface htmltabledatace...
...relates to. only use this attribute with the <th> element to define the row or column for which it is a header. valign this attribute specifies how a text is vertically aligned inside a cell. possible values for this attribute are: baseline: positions the text near the bottom of the cell and aligns it with the baseline of the characters instead of the bottom. if characters don't descend below the baseline, the baseline value achieves the same effect as bottom. bottom: positions the text near the bottom of the cell. middle: centers the text in the cell. and top: positions the text near the top of the cell. to achieve a similar effect, use the css vertical-align property. width this attribute is used to define a recommended cell width. use the css width property instead.
<thead>: The Table Head element - HTML: Hypertext Markup Language
Web › HTML › Element › thead
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 none. permitted content zero or more <tr> elements. tag omission the start tag is mandatory. the end tag may be omitted if the <thead> element is immediately followed by a <tbody> or <tfoot> element. permitted parents a <table> element. the <thead> must appear after any <caption> or <colgroup> element, even implicitly defined, but before any <tbody>, <tfoot> and <tr> element. implicit aria role rowgroup permitted aria roles any dom interface htmltablesectionelement attributes this element includes the g...
... of each cell of the column. it is one of the 6-digit hexadecimal code as defined in srgb, prefixed by a '#'. ...
<u>: The Unarticulated Annotation (Underline) element - HTML: Hypertext Markup Language
Web › HTML › Element › u
oration property set to underline. 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. see the usage notes section for further details on when it's appropriate to use <u> and when it isn't. content categories flow content, phrasing content, palpable content. permitted content phrasing content. tag omission 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 any dom interface htmlelement attributes this el...
...r to anyone who has used any of the more popular word processors available today. avoiding <u> most of the time, you actually don't want to use <u>. here are some examples that show what you should do instead in several cases. non-semantic underlines to underline text without implying any semantic meaning, use a <span> element with the text-decoration property set to "underline", as shown below. html <span class="underline">today's special</span> <br> chicken noodle soup with carrots css .underline { text-decoration: underline; } result presenting a book title book titles should be presented using the <cite> element instead of <u> or even <i>. html <p>the class read <cite>moby dick</cite> in the first term.</p> result with default style note that the default styling f...
<var>: The Variable element - HTML: Hypertext Markup Language
Web › HTML › Element › var
ramming context. 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. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this el...
...this can be overridden in css, like this: var { font: bold 15px "courier", "courier new", monospace; } examples basic example here's a simple example, using <var> to denote variable names in a mathematical equation. <p>a simple equation: <var>x</var> = <var>y</var> + 2 </p> the outpu...
contextmenu - HTML: Hypertext Markup Language
here are some implementation examples, including nested menus. ...
...st element, you can change the size of the text by using the "increase/decrease font" actions from your context menu </li> <menu type="context" id="changefont"> <menuitem label="increase font" onclick="incfont()"></menuitem> <menuitem label="decrease font" onclick="decfont()"></menuitem> </menu> <li contextmenu="changeimage" id="changeimage"> on the image below, you can fire the "change image" action in your context menu.<br /> <img src="https://udn.realityripple.com/samples/a2/b601bdfc0c.png" contextmenu="changeimage" id="promobutton" /> <menu type="context" id="changeimage"> <menuitem label="change image" onclick="changeimage()"></menuitem> </menu> </li> </ol> </body> javascript function shareviatwitt...
data-* - HTML: Hypertext Markup Language
the data-* global attributes form a class of attributes called custom data attributes, that allow proprietary information to be exchanged between the html and its dom representation by scripts. 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. all such custom data are available via the htmlelement interface of the element the attribute is set on. the htmlelement.dataset property gives access to them. ...
...ractive 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. all such custom data are available via the htmlelement interface of the element the attribute is set on. the htmlelement.dataset property gives access to them. the * may be replaced by any name following the production rule of xml names with the following restrictions: the name must not start with xml, whatever case is used for these letters; the name must not contain any semicolon (u+003a); the name must not contain capital letters. note that the htmlelement.dataset property is a domstringmap, and the name of the custom data attribute data-test-value will be accessible via htmlelement...
dir - HTML: Hypertext Markup Language
the dir global attribute is an enumerated attribute that indicates the directionality of the element's 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. it can have the following values: ltr, which means left to right and is to be used for languages that are written from the left to the right (like english); rtl, which means right to left and is to be used for languages that are written from the right to the left (like arabic); auto, which lets the user agent decide. it uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then appli...
...entation, 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 + shift + x but does not update the dir attribute value. specifications ...
is - HTML: Hypertext Markup Language
// create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // constructor contents ommitted for brevity ... ...
... // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // constructor contents ommitted for brevity ... ...
HTML reference - HTML: Hypertext Markup Language
sing tags. html attribute reference elements in html have attributes; these are additional values that configure the elements or adjust their behavior in various ways to meet the criteria the users want. global attributes global attributes are attributes common to all html elements; they can be used on all elements, though they may have no effect on some elements. ...
...me elements. link types in html, the following link types indicate the relationship between two documents, in which one links to the other using an <a>, <area>, or <link> element. content categories every html element is a member of one or more content categories — these categories group elements that share common characteristics. date and time formats used in html certain html elements allow you to specify dates and/or times as the value or as the value of an attribute. these include the date and time variations of the <input> element as well as the <ins> and <del> elements. ...
Data URLs - HTTP
they were formerly known as "data uris" until that name was retired by the whatwg. note: data urls are treated as unique opaque origins by modern browsers, rather than inheriting the origin of the settings object responsible for the navigation. syntax data urls are composed of four parts: a prefix (data:), a mime type indicating the type of data, an optional base64 token if non-textual, and the data itself: data:[<mediatype>][;base64],<data> the mediatype is a mime type string, such as 'image/jpeg' for a jpeg image file. ...
...data url will just include the query string in the data the url represents. security issues a number of security issues (e.g. phishing) have been associated with data urls, and navigating to them in the browser's top level. to mitigate such issues, top-level navigation to data:// urls has been blocked in firefox 59+ (release version, nightly/beta from 58), and we hope to see other browsers follow suit soon. see blocking top-level navigations to data urls for firefox 58 for more details. specifications specification title rfc 2397 the "data" url scheme ...
Content-Disposition - HTTP
rameter in the http context is always form-data. additional parameters are case-insensitive and have arguments that use quoted-string syntax after the '=' sign. multiple parameters are separated by a semi-colon (';'). content-disposition: form-data content-disposition: form-data; name="fieldname" content-disposition: form-data; name="fieldname"; filename="filename.jpg" directives name is followed by a string containing the name of the html field in the form that the content of this subpart refers to. when dealing with multiple files in the same field (for example, the multiple attribute of an <input type="file"> element), there can be several subparts with the same name. a name with a value of '_charset_' indicates that the part is not an html field, but the default charset to use for ...
...orm that the content of this subpart refers to. when dealing with multiple files in the same field (for example, the multiple attribute of an <input type="file"> element), there can be several subparts with the same name. a name with a value of '_charset_' indicates that the part is not an html field, but the default charset to use for parts without explicit charset information. filename is followed by a string containing the original name of the file transmitted. the filename is always optional and must not be used blindly by the application: path information should be stripped, and conversion to the server file system rules should be done. this parameter provides mostly indicative information. when used in combination with content-disposition: attachment, it is used as the default filena...
Content-Language - HTTP
for example, if "content-language: de-de" is set, it says that the document is intended for german language speakers (however, it doesn't indicate the document is written in german. for example, it might be written in english as part of a language course for german speakers. if you want to indicate which language the document is written in, use the lang attribute instead). if no content-language is specified, the default is that the content is intended for all language audiences. ...
...s content-language: de-de, en-ca directives language-tag multiple language tags are separated by comma. each language tag is a sequence of one or more case-insensitive subtags, each separated by a hyphen character ("-", %x2d). in most cases, a language tag consists of a primary language subtag that identifies a broad family of related languages (e.g., "en" = english), which is optionally followed by a series of subtags that refine or narrow that language's range (e.g., "en-ca" = the variety of english as communicated in canada). note: language tags are formaly defined in rfc 5646, which rely on the iso 639 standard (quite often the iso 639-1 code list) for language codes to be used. examples indicating the language a document is written in the global lang attribute is used on htm...
CSP: report-uri - HTTP
ax content-security-policy: report-uri <uri>; content-security-policy: report-uri <uri> <uri>; <uri> a uri where to post the report 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 violati...
...ubject . ' on ' . $current_domain; http_response_code(204); // http 204 no content $json_data = file_get_contents('php://input'); // we pretty print the json before adding it to the log file if ($json_data = json_decode($json_data)) { $json_data = json_encode($json_data, json_pretty_print | json_unescaped_slashes); if (!file_exists($log_file)) { // send an email $message = "the following content-security-policy violation occurred on " . $current_domain . ":\n\n" . $json_data . "\n\nfurther cps violations will be logged to the following log file, but no further email notifications will be sent until this log file is deleted:\n\n" . $log_file; mail($email_address, $email_subject, $message, 'content-type: text/plain;charset=utf-8'); } else i...
CSP: trusted-types - HTTP
the http content-security-policy (csp) trusted-types directive instructs user agents to restrict usage of known dom xss sinks to a predefined set of functions that only accept non-spoofable, typed values in place of strings. this allows authors to define rules guarding writing values to the dom and thus reducing the dom xss attack surface to small, isolated parts of the web application codebase, facilitating their monitoring and code review. ...
...mall, isolated parts of the web application codebase, facilitating their monitoring and code review. this directive declares a white-list of trusted type policy names created with trustedtypes.createpolicy from trusted types api. syntax content-security-policy: trusted-types; content-security-policy: trusted-types <policyname>; content-security-policy: trusted-types <policyname> <policyname> 'allow-duplicates'; <domstring> any string can be a trusted type policy name. 'allow-duplicates' allows for creating policies with a name that was already used examples todo polyfill a polyfill for trusted types is available on github. specifications specification status comment trusted types draft initial definition. ...
Cross-Origin-Opener-Policy - HTTP
the http cross-origin-opener-policy (coop) response header allows you to ensure a top-level document does not share a browsing context group with cross-origin documents. coop will process-isolate your document and potential attackers can't access to your global object if they were opening it in a popup, preventing a set of cross-origin attacks dubbed xs-leaks. if a cross-origin document with coop is opened in a new window, the opening document will not have a reference to it, and the window.opener property of the new window will be null. this allows you to have more control over references to a window than rel=noopener, which only affects outgoing navigations. header type response header forbidden header name no syntax cross-origin-opener-policy: unsafe-non...
... window, the opening document will not have a reference to it, and the window.opener property of the new window will be null. this allows you to have more control over references to a window than rel=noopener, which only affects outgoing navigations. header type response header forbidden header name no syntax cross-origin-opener-policy: unsafe-none | same-origin-allow-popups | same-origin directives unsafe-none this is the default value. allows the document to be added to its opener's browsing context group unless the opener itself has a coop of same-origin or same-origin-allow-popups. same-origin-allow-popups retains references to newly opened windows or tabs which either don't set coop or which opt out of isolation by setting a coop of unsafe-none. ...
Keep-Alive - HTTP
the keep-alive general header allows the sender to hint about how the connection may be used to set a timeout and a maximum amount of requests. the connection header needs to be set to "keep-alive" for this header to have any meaning. connection-specific header fields such as connection and keep-alive are prohibited in http/2. chrome and firefox ignore them in http/2 responses, but safari conforms to the http/2 spec requirements and won’t load any response which contains them. 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 ('='). ...
...e them in http/2 responses, but safari conforms to the http/2 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 no...
Public-Key-Pins-Report-Only - HTTP
the header is silently ignored in modern browsers as support for hpkp has been removed. use certificate transparency and the expect-ct header instead. ...
...nly: pin-sha256="<pin-value>"; max-age=<expire-time>; includesubdomains; report-uri="<uri>" directives pin-sha256="<pin-value>" the quoted string is the base64 encoded subject public key information (spki) fingerprint. it is possible to specify multiple pins for different public keys. some browsers might allow other hashing algorithms than sha-256 in the future. max-age=<expire-time> this directive is meaningless for the public-key-pins-report-only header, it will be ignored by user agents and the header will not be cached. includesubdomains optional if this optional parameter is specified, this rule applies to all of the site's subdomains as well. report-uri="<uri>" pin validation failures are r...
Referer - HTTP
Web › HTTP › Headers › Referer
important: although this header has many innocent uses it can have undesirable consequences for user security and privacy. see referer header: privacy and security concerns for more information and mitigations. note that referer is actually a misspelling of the word "referrer". see http referer on wikipedia for more details. ...
...referring resource is a local "file" or "data" uri. an unsecured http request is used and the referring page was received with a secure protocol (https). header type request header forbidden header name yes syntax referer: <url> directives <url> an absolute or partial address of the previous web page from which a link to the currently requested page was followed. url fragments (i.e. "#section") and userinfo (i.e. "username:password" in "https://username:password@example.com/foo/bar/") are not included. examples referer: https://developer.mozilla.org/docs/web/javascript specifications specification title rfc 7231, section 5.5.2: referer hypertext transfer protocol (http/1.1): semantics and content ...
Save-Data - HTTP
the save-data header field is a boolean which, in requests, indicates the client's preference for reduced data usage. this could be for reasons such as high transfer costs, slow connection speeds, etc. a value of on indicates explicit user opt-in into a reduced data usage mode on the client, and when communicated to origins allows them to deliver alternative content to reduce the data downloaded such as smaller image and video resources, different markup and styling, disabled polling and automatic updates, and so on. note: disabling http/2 server push (rfc 7540, section 8.2: server push) might be desirable too for reducing data downloads. syntax save-data: <sd-token> directives <sd-token> a numerical value indicating whether the client wants to opt in to reduced data usage mode. o...
...2: server push) might be desirable too for reducing data downloads. syntax save-data: <sd-token> directives <sd-token> a numerical value indicating whether the client wants to opt in to reduced data usage mode. on indicates yes, while off (the default) indicates no. examples the vary header ensures that the content is cached properly (for instance ensuring that the user is not served a lower-quality image from the cache when save-data header is no longer present [e.g. after having switched from cellular to wi-fi]). with save-data: on request: get /image.jpg http/1.0 host: example.com save-data: on response: http/1.0 200 ok content-length: 102832 vary: accept-encoding, save-data cache-control: public, max-age=31536000 content-type: image/jpeg [...] without save-data request...
Server-Timing - HTTP
ics 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. // single metric without value server-timing: missedcache //...
... could only show metrics to authenticated users and nothing to the public. performanceservertiming interface in addition to having server-timing header metrics appear in the developer tools of the browser, the performanceservertiming interface enables tools to automatically collect and process metrics from javascript. 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. the interface is only available in secure contexts (https) in some browsers. specifications specification status title server timingthe definition of 'server-timing header field' in that specification. working draft initial definition. ...
Strict-Transport-Security - HTTP
tically using https. whenever the strict-transport-security header is delivered to the browser, it will update the expiration time for that site, so sites can refresh this information and prevent the timeout from expiring. should it be necessary to disable strict transport security, setting the max-age to 0 (over a https connection) will immediately expire the strict-transport-security header, allowing access via http. preloading strict transport security google maintains an hsts preload service. by following the guidelines and successfully submitting your domain, browsers will never connect to your domain using an insecure connection. while the service is hosted by google, all browsers have stated an intent to use (or actually started using) the preload list. however, it is not part of th...
...l. information regarding the hsts preload list in chrome : https://www.chromium.org/hsts consultation of the firefox hsts preload list : nsstspreloadlist.inc examples all present and future subdomains will be https for a max-age of 1 year. this blocks access to pages or sub domains that can only be served over http. strict-transport-security: max-age=31536000; includesubdomains in the following example, max-age is set to 2 years, raised from what was a former limit max-age of 1 year. note that 1 year is acceptable for a domain to be included in browsers' hsts preload lists. 2 years is, however, the recommended goal as a website's final hsts configuration as explained on https://hstspreload.org. it also suffixed with preload which is necessary for inclusion in most major web browsers'...
Trailer - HTTP
Web › HTTP › Headers › Trailer
the trailer response header allows the sender to include additional fields at the end of chunked messages in order to supply metadata that might be dynamically generated while the message body is sent, such as a message integrity check, digital 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. ...
... integrity check, digital 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 ...
X-DNS-Prefetch-Control - HTTP
this prefetching is performed in the background, so that the dns is likely to have been resolved by the time the referenced items are needed. this reduces latency when the user clicks a link. ...
...rmation to these domains. description dns requests are very small in terms of bandwidth, but latency can be quite high, especially on mobile networks. by speculatively prefetching dns results, latency can be reduced significantly at certain times, such as when the user clicks the link. in some cases, latency can be reduced by a second. the implementation of this prefetching in some browsers allows domain name resolution to occur in parallel with (instead of in serial with) the fetching of actual page content. by doing this, the high-latency domain name resolution process doesn't cause any delay while fetching content. page load times – especially on mobile networks – can be measurably improved in this way. if the domain names for images can be resolved in advance of the images being ...
POST - HTTP
Web › HTTP › Methods › POST
ach value is sent as a block of data ("body part"), with a user agent-defined delimiter ("boundary") separating each part. the keys are given in the content-disposition header of each part. text/plain when the post request is sent via a method other than an html form — like via an xmlhttprequest — the body can take any type. as described in the http 1.1 specification, post is designed to allow a uniform method to cover the following functions: annotation of existing resources posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; adding a new user through a signup modal; providing a block of data, such as the result of submitting a form, to a data-handling process; extending a database through an append operation. request has bod...
...ticles; adding a new user through a signup modal; providing a block of data, such as the result of submitting a form, to a data-handling process; extending a database through an append operation. ...
TRACE - HTTP
Web › HTTP › Methods › TRACE
the http trace method performs a message loop-back test along the path to the target resource, providing a useful debugging mechanism. the final recipient of the request should reflect the message received, excluding some fields described below, back to the client as the message body of a 200 (ok) response with a content-type of message/http. the final recipient is either the origin server or the first server to receive a max-forwards value of 0 in the request. ...
...ds described below, back to the client as the message body of a 200 (ok) response with a content-type of message/http. the final recipient is either the origin server or the first server to receive a max-forwards value of 0 in the request. ...
Network Error Logging - HTTP
network error logging is a mechanism that can be configured via the nel http response header. this experimental header allows web sites and applications to opt-in to receive reports about failed (and, if desired, successful) network fetches from supporting browsers. reports are sent to a reporting group defined within a report-to header. usage web applications opt in to this behaviour with the nel header, which is a json-encoded object: nel: { "report_to": "nel", "max_age": 31556952 } an origin considered secure by the browser is required. the following object keys can be specified in the nel header: report_to the reporting api group to send network error reports to (see below). max_age specifies the lifetime of the policy, in seconds (in a similar way to e.g. hsts ...
... dns.failed request to the dns server failed due to reasons not covered by previous errors (e.g. servfail) dns.address_cha...
451 Unavailable For Legal Reasons - HTTP
Web › HTTP › Status › 451
the hypertext transfer protocol (http) 451 unavailable for legal reasons client error response code indicates that the user requested a resource that is not available due to legal reasons, such as a web page for which a legal action has been issued. status 451 unavailable for legal reasons example this example response is taken from the ietf rfc (see below) and contains a reference to monty python's life of brian. note: the link header might also contain a rel="blocked-by" relation identifying the entity and implementing blockage, not any other entity mandating it. any attempt to identify the entity ultimately responsible for the resource being unavailable belongs in the response body, not in the rel="blocked-by" link. this includes the name of the person or organization that made a le...
...tp/1.1 451 unavailable for legal reasons link: <https://spqr.example.org/legislatione>; rel="blocked-by" content-type: text/html <html> <head><title>unavailable for legal reasons</title></head> <body> <h1>unavailable for legal reasons</h1> <p>this request may not be serviced in the roman province of judea due to the lex julia majestatis, which disallows access to resources hosted on servers deemed to be operated by the people's front of judea.</p> </body> </html> specifications specification title rfc 7725: 451 unavailable for legal reasons an http status code to report legal obstacles ...
Enumerability and ownership of properties - JavaScript
numerable 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 enumerability and ownership - built-in methods of detection, retrieval, and iteration functionality own object own object and its prototype chain prototype chain only detection enumerable nonenumerable enumerable a...
...this._enumerableandnotenumerable); }, // private static property checker callbacks _enumerable: function(obj, prop) { return obj.propertyisenumerable(prop); }, _notenumerable: function(obj, prop) { return !obj.propertyisenumerable(prop); }, _enumerableandnotenumerable: function(obj, prop) { return true; }, // inspired by http://stackoverflow.com/a/8024294/271577 _getpropertynames: function getallpropertynames(obj, iterateselfbool, iterateprototypebool, includepropcb) { var props = []; do { if (iterateselfbool) { object.getownpropertynames(obj).foreach(function(prop) { if (props.indexof(prop) === -1 && includepropcb(obj, prop)) { props.push(pr...
Equality comparisons and sameness - JavaScript
two values for equality, after converting both values to a common type. after conversions (one or both sides may undergo conversions), the final equality comparison is performed exactly as === performs it. loose equality is symmetric: a == b always has identical semantics to b == a for any values of a and b (except for the order of applied conversions). ...
...ernatively, someone might say that double equals is the baseline, and triple equals is an enhanced version, because it requires the two operands to be the same type, so it adds an extra constraint. which one is the better model for understanding depends on how you choose to view things.) however, this way of thinking about the built-in sameness operators is not a model that can be stretched to allow a place for es2015's object.is on this "spectrum". object.is isn't simply "looser" than double equals or "stricter" than triple equals, nor does it fit somewhere in between (i.e., being both stricter than double equals, but looser than triple equals). we can see from the sameness comparisons table below that this is due to the way that object.is handles nan. notice that if object.is(nan, nan) eva...
Groups and ranges - JavaScript
do not forget to edit it as well, thanks! characters meaning x|y matches either "x" or "y". for example, /green|red/ matches "green" in "green apple" and "red" in "red apple". [xyz] [a-c] a character set. matches any one of the enclosed characters. you can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character. ...
...ust the order of the capturing groups themselves. this becomes important when capturing groups are nested. matches are accessed using the index of the the result's elements ([1], ..., [n]) or from the predefined regexp object's properties ($1, ..., $9). capturing groups have a performance penalty. if you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below). string.match() won't return groups if the /.../g flag is set. however, you can still use string.matchall() to get all matches. \n where "n" is a positive integer. a back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses). for example, /apple(,)\sorange\1/ matches "apple, orange," in "apple, orange, cherry,...
Quantifiers - JavaScript
characters meaning x* matches the preceding item "x" 0 or more times. for example, /bo*/ matches "boooo" in "a ghost booooed" and "b" in "a bird warbled", but nothing in "a goat grunted". x+ matches the preceding item "x" 1 or more times. equivalent to {1,}. ...
...letterword)); // ["i"] console.table(sentence.match(notsolongword)); // [ "why", "do", "i", "have", "to", "learn", "table" ] console.table(sentence.match(loooongword)); // ["multiplication"] optional character var britishtext = "he asked his neighbour a favour."; var americantext = "he asked his neighbor a favor."; var regexpending = /\w+ou?r/g; // \w+ one or several letters // o followed by an "o", // u? optionally followed by a "u" // r followed by an "r" console.table(britishtext.match(regexpending)); // ["neighbour", "favour"] console.table(americantext.match(regexpending)); // ["neighbor", "favor"] greedy versus non-greedy var text = "i must be getting somewhere near the centre of the earth."; var greedyregexp = /[\w ]+/; // [\w ] a letter of the latin alphabet...
JavaScript technologies overview - JavaScript
m (document object model). javascript, the core language (ecmascript) the core language of javascript is standardized by the ecma tc39 committee as a language named ecmascript. this core language is also used in non-browser environments, for example in node.js. what falls under the ecmascript scope? among other things, ecmascript defines: language syntax (parsing rules, keywords, control flow, object literal initialization, ...) error handling mechanisms (throw, try...catch, ability to create user-defined error types) types (boolean, number, string, function, object, ...) the global object. in a browser, this global object is the window object, but ecmascript only defines the apis not specific to browsers, e.g. parseint, parsefloat, decodeuri, encodeuri... a prototype-based inheri...
... aren't defined in a standard. looking for the document object, window object, and the other dom elements? read the dom documentation. other notable apis the settimeout and setinterval functions were first specified on the window interface in html standard. xmlhttprequest makes it possible to send asynchronous http requests. the css object model abstract css rules as objects. webworkers allows parallel computation. websockets allows low-level bidirectional communication. canvas 2d context is a drawing api for <canvas>. ...
About the JavaScript reference - JavaScript
pt guide. the javascript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. for the most part, this reference attempts to be environment-agnostic and does not target a web browser environment. ...
... statements and declarations javascript applications consist of statements with an appropriate syntax. a single statement may span multiple lines. ...
Private class fields - JavaScript
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. ...
...icstaticmethod1() { return classwithprivatestaticmethod.#privatestaticmethod(); } static publicstaticmethod2() { return this.#privatestaticmethod(); } } console.assert(classwithprivatestaticmethod.publicstaticmethod1() === 42); console.assert(classwithprivatestaticmethod.publicstaticmethod2() === 42); this can lead to unexpected behaviour when using this. ...
Public class fields - JavaScript
both static and instance public fields are writable, enumerable, and configurable properties. ...
...sing object.defineproperty(). they are writable, non-enumerable, and configurable. you may make use of generator, async, and async generator functions. class classwithfancymethods { *generatormethod() { } async asyncmethod() { } async *asyncgeneratormethod() { } } inside instance methods, this refers to the instance itself. in subclasses, super lets you access the superclass prototype, allowing you to call methods from the superclass. class baseclass { msg = 'hello world' basepublicmethod() { return this.msg } } class subclass extends baseclass { subpublicmethod() { return super.basepublicmethod() } } const instance = new subclass() console.log(instance.subpublicmethod()) // expected output: "hello worl​d" getters and setters are special methods that bind to ...
Classes - JavaScript
with the name of the class ("rectangle" here). class rectangle { constructor(height, width) { this.height = height; this.width = width; } } hoisting an important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. you first need to declare your class and then access it, otherwise code like the following will throw a referenceerror: const p = new rectangle(); // referenceerror class rectangle {} class expressions a class expression is another way to define a class. class expressions can be named or unnamed. the name given to a named class expression is local to the class's body. (it can be retrieved through the class's (not an instance's) name property, though). // unnamed let rectangle ...
...or(height, width) { this.height = height; this.width = width; } } by declaring fields up-front, class definitions become more self-documenting, and the fields are always present. as seen above, the fields can be declared with or without a default value. see public class fields for more information. private field declarations using private fields, the definition can be refined as below. class rectangle { #height = 0; #width; constructor(height, width) { this.#height = height; this.#width = width; } } it's an error to reference private fields from outside of the class; they can only be read or written within the class body. by defining things which are not visible outside of the class, you ensure that your classes' users can't depend on internals, which may ch...
SyntaxError: invalid regular expression flag "x" - JavaScript
d separately or together in any order, but there are only six of them in ecmascript. to include a flag with the regular expression, use this syntax: var re = /pattern/flags; or var re = new regexp('pattern', 'flags'); regular expression flags flag description g global search. i case-insensitive search. m multi-line search. s allow . to match newlines (added in ecmascript 2018) u unicode; treat pattern as a sequence of unicode code points y perform a "sticky" search that matches starting at the current position in the target string. see sticky examples there are only six valid regular expression flags. /foo/bar; // syntaxerror: invalid regular expression flag "b" did you intend to create ...
... /foo/g; /foo/gims; /foo/uy; ...
TypeError: cyclic object value - JavaScript
converting circular structure to json (chrome and opera) typeerror: circular reference in value argument not supported (edge) error type typeerror what went wrong? the json format per se doesn't support object references (although an ietf draft exists), hence json.stringify() doesn't try to solve them and fails accordingly. examples circular references in a circular structure like the following var circularreference = {otherdata: 123}; circularreference.myself = circularreference; json.stringify() will fail json.stringify(circularreference); // typeerror: cyclic object value to serialize circular references you can use a library that supports them (e.g. cycle.js) or implement a solution by yourself, which will require finding and replacing (or removing) the cyclic references by...
...ta: 123}; circularreference.myself = circularreference; json.stringify() will fail json.stringify(circularreference); // typeerror: cyclic object value to serialize circular references you can use a library that supports them (e.g. cycle.js) or implement a solution by yourself, which will require finding and replacing (or removing) the cyclic references by serializable values. ...
TypeError: can't access dead object - JavaScript
a dead object, is holding a strong (keep alive) reference to a dom element that persists even after it was destroyed in the dom. ...
...a dead object, is holding a strong (keep alive) reference to a dom element that persists even after it was destroyed in the dom. ...
SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated - JavaScript
the javascript strict mode-only exception "0-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the "0o" prefix instead" occurs when deprecated octal literals and octal escape sequences are used. message syntaxerror: octal numeric literals and escape characters not allowed in strict mode (edge) syntaxerror: "0"-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the "0o" prefix instead error type syntaxerror in strict mode only. what went wrong? octal literals and octal escape sequences are deprecated and will throw a syntaxerror in strict mode. with ecmascript 2015 and later, the standardized syntax uses a leading zero followed by a lowercase or uppercase latin letter "o" (0o or 0o). examples "0"-prefixed ...
...o followed by a lowercase or uppercase latin letter "o" (0o or 0o). ...
SyntaxError: for-in loop head declarations may not have initializers - JavaScript
message syntaxerror: for-in loop head declarations cannot have an initializer (edge) syntaxerror: for-in loop head declarations may not have initializers (firefox) syntaxerror: for-in loop variable declaration may not have an initializer. (chrome) error type syntaxerror in strict mode only. ...
...head declarations may not have initializers valid for-in loop you can remove the initializer (i = 0) in the head of the for-in loop. ...
SyntaxError: JSON.parse: bad parsing - JavaScript
ror: json.parse: unexpected character syntaxerror: json.parse: unexpected non-whitespace character after json data syntaxerror: json.parse error: invalid character at position {0} (edge) error type syntaxerror what went wrong? json.parse() parses a string as json. this string has to be valid json and will throw this error if incorrect syntax was encountered. ...
...('{"foo": 1}'); property names must be double-quoted strings you cannot use single-quotes around properties, like 'foo'. json.parse("{'foo': 1}"); // syntaxerror: json.parse: expected property name or '}' // at line 1 column 2 of the json data instead write "foo": json.parse('{"foo": 1}'); leading zeros and decimal points you cannot use leading zeros, like 01, and decimal points must be followed by at least one digit. json.parse('{"foo": 01}'); // syntaxerror: json.parse: expected ',' or '}' after property value // in object at line 1 column 2 of the json data json.parse('{"foo": 1.}'); // syntaxerror: json.parse: unterminated fractional number // at line 1 column 2 of the json data instead write just 1 without a zero and use at least one digit after a decimal point: json.parse('{...
TypeError: "x" is not a constructor - JavaScript
what went wrong? there was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor. see constructor or the new operator for more information on what a constructor is. there are many global objects, like string or array, which are constructable using new. however, some global objects are not and their properties and methods are static. the following javascript standard built-in objects are not a constructor: math, json, symbol, reflect, intl, atomics. generator functions cannot be used as constructors either. examples invalid cases var car = 1; new car(); // typeerror: car is not a constructor new math(); // typeerror: math is not a constructor new symbol(); // typeerror: symbol is not a constructor function* f() {}; var obj = new ...
... new math(); // typeerror: math is not a constructor new symbol(); // typeerror: symbol is not a constructor function* f() {}; var obj = new f; // typeerror: f is not a constructor a car constructor suppose you want to create an object type for cars. you want this type of object to be called car, and you want it to have properties for make, model, and year. to do this, you would write the following function: function car(make, model, year) { this.make = make; this.model = model; this.year = year; } now you can create an object called mycar as follows: var mycar = new car('eagle', 'talon tsi', 1993); in promises when returning an immediately-resolved or immediately-rejected promise, you do not need to create a new promise(...) and act on it. this is not legal (the promise con...
RangeError: precision is out of range - JavaScript
method firefox (spidermonkey) chrome, opera (v8) number.prototype.toexponential() 0 to 100 0 to 20 number.prototype.tofixed() -20 to 100 0 to 20 number.prototype.toprecision() 1 to 100 1 to 21 exam...
...rome) rangeerror: toprecision() argument must be between 1 and 21 (chrome) error type rangeerror what went wrong? there was an out of range precision argument in one of these methods: number.prototype.toexponential() number.prototype.tofixed() number.prototype.toprecision() the allowed range for these methods is usually between 0 and 20 (or 21). however, the ecmascript specification allows to extend this range. method firefox (spidermonkey) chrome, opera (v8) number.prototype.toexponential() 0 to 100 0 to 20 number.prototype.tofixed() -20 to 100 0 to 20 number.prototype.toprecision() 1 to 100 1 to 21 examples invalid cases 77.1234.toexponential(-1); // rangeerror 77.1234.toexponential(101); // rangeerror 2...
Warning: unreachable code after return statement - JavaScript
uding an expression directly after. when an expression exists after a valid return statement, a warning is given to indicate that the code after the return statement is unreachable, meaning it can never be run. ...
...why should i have semicolons after return statements? ...
The arguments object - JavaScript
each() or map(). see §description for details. the arguments object is a local variable available within all non-arrow functions. you can refer to a function's arguments inside that function by using its arguments object. it has entries for each argument the function was called with, with the first entry's index at 0. for example, if a function is passed 3 arguments, you can access them as follows: arguments[0] // first argument arguments[1] // second argument arguments[2] // third argument each argument can also be set or reassigned: arguments[1] = 'new value'; the arguments object is not an array. it is similar, but lacks all array properties except length. for example, it does not have the pop() method. however, it can be converted to a real array: var args = array.prototype.sl...
...o. pepper. parsley" myconcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley'); defining a function that creates html lists this example defines a function that creates a string containing html for a list. the only formal argument for the function is a string that is "u" if the list is to be unordered (bulleted), or "o" if the list is to be ordered (numbered). the function is defined as follows: function list(type) { var html = '<' + type + 'l><li>'; var args = array.prototype.slice.call(arguments, 1); html += args.join('</li><li>'); html += '</li></' + type + 'l>'; // end list return html; } you can pass any number of arguments to this function, and it adds each argument as a list item to a list of the type indicated. for example: let listhtml = list('u', 'one', 'two', 't...
Rest parameters - 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 function f(a, b, ...theargs) { // ... } description a function's last parameter can be prefixed with ... which will cause all remaining (user supplied) arguments to be placed within a "standard" javascript array. only the last parameter can be a "rest parameter". ...
...wever, the third argument, manymoreargs, will be an array that contains the 3rd, 4th, 5th, 6th ... nth — as many arguments that the user includes. function myfun(a, b, ...manymoreargs) { console.log("a", a) console.log("b", b) console.log("manymoreargs", manymoreargs) } myfun("one", "two", "three", "four", "five", "six") // a, one // b, two // manymoreargs, [three, four, five, six] below... even though there is just one value, the last argument still gets put into an array. // using the same function definition from example above myfun("one", "two", "three") // a, one // b, two // manymoreargs, [three] below, the third argument isn't provided, but manymoreargs is still an array (albeit an empty one). // using the same function definition from example above myfun("one", "two...
setter - JavaScript
pressions for a computed property name to bind to the given function. description in javascript, a setter can be used to execute a function whenever a specified property is attempted to be changed. setters are most often used in conjunction with getters to create a type of pseudo-property. it is not possible to simultaneously have a setter on a property that holds an actual value. note the following when working with the set syntax: it can have an identifier which is either a number or a string; it must have exactly one parameter (see incompatible es5 change: literal getter and setter functions must now have exactly zero or one arguments for more information); it must not appear in an object literal with another set or with a data entry for the same property. ( { set x(v) { }, set...
...rameter (see incompatible es5 change: literal getter and setter functions must now have exactly zero or one arguments for more information); it must not appear in an object literal with another set or with a data entry for the same property. ( { set x(v) { }, set x(v) { } } and { x: ..., set x(v) { } } are forbidden ) examples defining a setter on new objects in object initializers the following example define a pseudo-property current of object language. when current is assigned a value, it updates log with that value: const language = { set current(name) { this.log.push(name); }, log: [] } language.current = 'en'; console.log(language.log); // ['en'] language.current = 'fa'; console.log(language.log); // ['en', 'fa'] note that current is not defined, and any attempts ...
Array.prototype.findIndex() - JavaScript
crease k by 1. k++; } // 7. return -1. return -1; }, configurable: true, writable: true }); } if you need to support truly obsolete javascript engines that do not support object.defineproperty, it is best not to polyfill array.prototype methods at all, as you cannot make them non-enumerable. examples find the index of a prime number in an array the following example returns the index of the first element in the array that is a prime number, or -1 if there is no prime number. function isprime(num) { for (let i = 2; num > i; i++) { if (num % i == 0) { return false; } } return num > 1; } console.log([4, 6, 8, 9, 12].findindex(isprime)); // -1, not found console.log([4, 6, 7, 9, 12].findindex(isprime)); // 2 (array[2] is 7) fin...
...first element in the array that is a prime number, or -1 if there is no prime number. ...
Array.prototype.indexOf() - JavaScript
not found. description indexof() compares searchelement to elements of the array using strict equality (the same method used by the === or triple-equals operator). note: for the string method, 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. this algorithm matches the one specified in ecma-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...
...the get // internal method of o with the argument tostring(k). // ii. let same be the result of applying the // strict equality comparison algorithm to // searchelement and elementk. // iii. if same is true, return k. if (k in o && o[k] === searchelement) return k; } return -1; }; } examples using indexof() the following example uses indexof() to locate values in an array. var array = [2, 9, 9]; array.indexof(2); // 0 array.indexof(7); // -1 array.indexof(9, 2); // 2 array.indexof(2, -1); // -1 array.indexof(2, -3); // 0 finding all the occurrences of an element var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd']; var element = 'a'; var idx = array.indexof(element); while (idx != -1) { ...
Array.prototype.join() - JavaScript
ents are joined without any characters in between them. return value a string with all array elements joined. if arr.length is 0, the empty string is returned. description the string conversions of all array elements are joined into one string. if an element is undefined, null or an empty array [], it is converted to an empty string. ...
... function f(a, b, c) { var s = array.prototype.join.call(arguments); console.log(s); // '1,a,true' } f(1, 'a', true); //expected output: "1,a,true" specifications specification ecmascript (ecma-262)the definition of 'array.prototype.join' in that specification. ...
Array.prototype.length - JavaScript
itable: if this attribute set to false, the value of the property cannot be changed. configurable: if this attribute set to false, any attempts to delete the property or change its attributes (writable, configurable, or enumerable) will fail. enumerable: if this attribute set to true, the property will be iterated over during for or for..in loops. ...
...ted over during for or for..in loops. examples iterating over an array in the following example, the array numbers is iterated through by looking at the length property. the value in each element is then doubled. var numbers = [1, 2, 3, 4, 5]; var length = numbers.length; for (var i = 0; i < length; i++) { numbers[i] *= 2; } // numbers is now [2, 4, 6, 8, 10] shortening an array the following example shortens the array numbers to a length of 3 if the current length is greater than 3. var numbers = [1, 2, 3, 4, 5]; if (numbers.length > 3) { numbers.length = 3; } console.log(numbers); // [1, 2, 3] console.log(numbers.length); // 3 create empty array of fixed length var numbers = []; numbers.length = 3; console.log(numbers); // [undefined, undefined, undefined] specification...
Array.prototype.push() - JavaScript
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 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...
...generic, and we can use that to our advantage. array.prototype.push can work on an object just fine, as this example shows. note that we don't create an array to store a collection of objects. instead, we store the collection on the object itself and use call on array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way javascript allows us to establish the execution context in any way we want. let obj = { length: 0, addelem: function addelem(elem) { // obj.length is automatically incremented // every time an element is added. [].push.call(this, elem) } } // let's add some empty objects just to illustrate. obj.addelem({}) obj.addelem({}) console.log(obj.length) // → 2 note that although...
Array.prototype.reverse() - JavaScript
bject in place, mutating the array, and returning a reference to the array. reverse is intentionally generic; this method can be called or applied to objects resembling arrays. objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. ...
...the call to reverse() returns a reference to the reversed array-like object a. ...
DataView - JavaScript
description endianness multi-byte number formats are represented in memory differently depending on machine architecture — see endianness for an explanation. dataview accessors provide explicit control of how data is accessed, regardless of the executing computer's endianness. var littleendian = (function() { var buffer = new arraybuffer(2); new dataview(buffer).setint16(0, 256, true /* littleendian */); // int16array uses the platform's endianness. ...
...const combined = littleendian? left + 2**32*right : 2**32*left + right; if (!number.issafeinteger(combined)) console.warn(combined, 'exceeds max_safe_integer. precision may be lost'); return combined; } alternatively, if you need full 64-bit range, you can create a bigint. further, although native bigints are much faster than user-land library equivalents, bigints will always be much slower than 32-bit integers in javascript due to the nature of their variable size. const bigint = window.bigint, bigthirtytwo = bigint(32), bigzero = bigint(0); function getuint64bigint(dataview, byteoffset, littleendian) { // split 64-bit number into two 32-bit (4-byte) parts const left = bigint(dataview.getuint32(byteoffset|0, !!littleendian)>>>0); const right = bigint(dataview.getuint32((by...
Date() constructor - JavaScript
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, beginning with 0 for january to 11 for december. d...
...esenting 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 ways to create a date object the following examples show several ways to create javascript dates: note: parsing of date strings with the date constructor (and date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. let today = new date() let birthday = new date('december 17, 1995 03:24:00') let birthday = new date('1995-12-17t03:24:00') let birthday = new date(1995, 11, 17) ...
Date.prototype.toDateString() - JavaScript
"thu jan 01 1970". 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. ...
...d send us a pull request. syntax 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-dependen...
Date.prototype.toLocaleDateString() - JavaScript
in older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. the source for this interactive example is stored in a github repository. ...
...turn e.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized date formats. in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: var date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // formats below assume the local time zone of the locale; // america/los_angeles for the us // us english uses month-day-year order console.log(date.tolocaledatestring('en-us')); // → "12/19/2012" // british english uses day-month-year order console.log(date.tolocaledatestring('en-gb')); // → "20/12/2012" // korean uses year-month-day order console.log(date.tolocaledatestring('ko-kr')); // → "2012. 12. ...
Error - JavaScript
description runtime errors result in new error objects being created and thrown. error types besides the generic error constructor, there are seven other core error constructors in javascript. for client-side exceptions, see exception handling statements. evalerror creates an instance representing an error that occurs regarding the global function eval(). ...
... console.error(e.name + ': ' + e.message) } // ... etc } custom error types you might want to define your own error types deriving from error to be able to throw new myerror() and use instanceof myerror to check the kind of error in the exception handler. this results in cleaner and more consistent error handling code. see "what's a good way to extend error in javascript?" on stackoverflow for an in-depth discussion. es6 custom error class versions of babel prior to 7 can handle customerror class methods, but only when they are declared with object.defineproperty(). otherwise, old versions of babel and other transpilers will not correctly handle the following code without additional configuration. some browsers include the customerror constructor in the stack trace when using...
FinalizationRegistry.prototype.register() - JavaScript
onal a token that may be used with the unregister method later to unregister the target object. if provided (and not undefined), this must be an object. if not provided, the target cannot be unregistered. return value undefined. notes see the avoid where possible and notes on cleanup callbacks sections of the finalizationregistry page for important caveats. ...
... undefined. notes see the avoid where possible and notes on cleanup callbacks sections of the finalizationregistry page for important caveats. examples using register the following registers the target object referenced by target, passing in the held value "some value" and passing the target object itself as the unregistration token: registry.register(target, "some value", target); the following registers the target object referenced by target, passing in another object as the held value, and not passing in any unregistration token (which means target can't be unregistered): registry.register(target, {"useful": "info about target"}); specifications specification weakrefsthe definition of 'finalizationregistry.prototype.register' in that specification. ...
Function.caller - JavaScript
ers. description if the function f was invoked by the top level code, the value of f.caller is null, otherwise it's the function that called f. it's also null for strict, async function and generator function callers. this property replaces the obsolete arguments.caller property of the arguments object. ...
...object of the caller thus allowing to reconstruct the stack, was removed for security reasons. notes note that in case of recursion, you can't reconstruct the call stack using this property. consider: function f(n) { g(n - 1); } function g(n) { if (n > 0) { f(n); } else { stop(); } } f(2); at the moment stop() is called the call stack will be: f(2) -> g(1) -> f(1) -> g(0) -> stop() the following is true: stop.caller === g && f.caller === g && g.caller === f so if you tried to get the stack trace in the stop() function like this: var f = stop; var stack = 'stack trace:'; while (f) { stack += '\n' + f.name; f = f.caller; } the loop would never stop. examples checking the value of a function's caller property the following code checks the value a function's caller property. ...
Intl.DateTimeFormat.prototype.format() - JavaScript
ions); var formatted = a.map(datetimeformat.format); console.log(formatted.join('; ')); // → "setembro de 2012; dezembro de 2012; abril de 2012" avoid comparing formatted date values to static values most of the time, the formatting returned by format() is consistent. however, this might change in the future and isn't guaranteed for all the languages — output variations are by design and allowed by the specification. most notably, the ie and edge browsers insert bidirectional 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...
... specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.datetimeformat.format' in that specification. ...
Intl.ListFormat() constructor - JavaScript
examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax new intl.listformat([locales[, options]]) parameters locales optional. a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. options optional. an object with some or all of the following properties: 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. type the format of output message. possible values are "conjunction" that stands for "and"-based lists (default, e.g., a, b, and c), or "disjunction" that stands for "or"-based lists (e.g., a, b...
... "and"-based lists (default, e.g., a, b, and c), or "disjunction" that stands for "or"-based lists (e.g., a, b, or c). "unit" stands for lists of values with units (e.g., 5 pounds, 12 ounces). style the length of the formated message. possible values are: "long" (default, e.g., a, b, and c); "short" (e.g., a, b, c), or "narrow" (e.g., a b c). when style is short or narrow, unit is the only allowed value for the type option. examples using format the following example shows how to create a list formatter using the english language. const list = ['motorcycle', 'bus', 'car']; console.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).format(list)); // > motorcycle, bus and car console.log(new intl.listformat('en-gb', { style: 'short', type: 'disjunction' }...
Intl.ListFormat - JavaScript
fall back to the runtime's default locale. instance methods intl.listformat.prototype.format() returns a language-specific formatted string representing the elements of the list. intl.listformat.prototype.formattoparts() returns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion. examples using format the following example shows how to create a list formatter using the english language. const list = ['motorcycle', 'bus', 'car']; console.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).format(list)); // > motorcycle, bus and car console.log(new intl.listformat('en-gb', { style: 'short', type: 'disjunction' }).format(list)); // > motorcycle, bus or car console.log(new intl.li...
... console.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).format(list)); // > motorcycle, bus and car console.log(new intl.listformat('en-gb', { style: 'short', type: 'disjunction' }).format(list)); // > motorcycle, bus or car console.log(new intl.listformat('en-gb', { style: 'narrow', type: 'unit' }).format(list)); // > motorcycle bus car using formattoparts the following example shows how to create a list formatter returning formatted parts const list = ['motorcycle', 'bus', 'car']; console.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).formattoparts(list)); // [ { "type": "element", "value": "motorcycle" }, // { "type": "literal", "value": ", " }, // { "type": "element", "value": "bus" }, // { "type": "literal", "value": ", a...
Intl.Locale.prototype.caseFirst - JavaScript
the intl.locale.prototype.casefirst property is an accessor property that returns whether case is taken into account for the locale's collation rules. description a locale's collation rules are used to determine how strings are ordered in that locale. 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. casefirst values value description upper upper case to be sorted before lower case. lower lower case to be sorted before upper case. false no special case ordering. examples setting the casefirst value via the locale string in the unico...
...irst); // prints "upper" setting the casefirst value via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can be used to pass extension types. set the casefirst property of the configuration object to your desired casefirst value, and then pass it into the constructor. let casefirstobj= new intl.locale("en-latn-us", {casefirst: "lower"}); console.log(us12hour.casefirst); // prints "lower" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.NumberFormat.prototype.formatToParts() - JavaScript
the intl.numberformat.prototype.formattoparts() method allows locale-aware formatting of strings produced by numberformat formatters. syntax intl.numberformat.prototype.formattoparts(number) parameters number optional a number or bigint to format. return value an array of objects containing the formatted number in parts. description the formattoparts() method is useful for custom formatting of number strings. it returns an array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. ...
...custom formatting of number strings. it returns an array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. the structure the formattoparts() method returns, looks like this: [ { type: "integer", value: "3" }, { type: "group", value: "." }, { type: "integer", value: "500" } ] possible types are the following: currency the currency string, such as the symbols "$" and "€" or the name "dollar", "euro" depending on how currencydisplay is specified. 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 ...
Intl.NumberFormat.prototype.resolvedOptions() - JavaScript
f 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 numberformat.resolvedoptions() return value a new object with properties reflecting the locale and number formatting options computed during the initialization of the given numberformat object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 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. numberingsystem the value provided for this properties in the options argument, if present, or the value requested...
...the value provided for this property in the options 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". only one of the following two groups of properties is included: minimumintegerdigits minimumfractiondigits maximumfractiondigits the values provided for these properties in the options argument or filled in as defaults. these properties are present only if neither minimumsignificantdigits nor maximumsignificantdigits was provided in the options argument. minimumsignificantdigits maximumsignificantdigits the va...
Intl.PluralRules() constructor - JavaScript
the intl.pluralrules() constructor creates intl.pluralrules objects. syntax new intl.pluralrules([locales[, options]]) parameters locales optional. a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. options optional. an object with some or all of the following properties: 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. 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,...
...lues are "lookup" and "best fit"; the default 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). the following properties fall into two groups: minimumintegerdigits, minimumfractiondigits, and maximumfractiondigits in one group, minimumsignificantdigits and maximumsignificantdigits in the other. if at least one property from the second group is defined, then the first group is ignored. minimumintegerdigits the minimum number of integer digits to use. possible values are from 1 to 21; the...
Intl.PluralRules.prototype.resolvedOptions() - JavaScript
hod returns a new object with properties reflecting the locale and plural formatting options computed during initialization of this pluralrules object. syntax pluralrule.resolvedoptions() return value a new object with properties reflecting the locale and plural formatting options computed during the initialization of the given pluralrules object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 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...
... extension values were requested in the input bcp 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). only one of the following two groups of properties is included: minimumintegerdigits minimumfractiondigits maximumfractiondigits the values provided for these properties in the options argument or filled in as defaults. these properties are present only if neither minimumsignificantdigits nor maximumsignificantdigits was provided in the options argument. minimumsignificantdigits maximumsignificantdigits the va...
Intl.RelativeTimeFormat.prototype.format() - JavaScript
se 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 in your locale // with default values explicitly passed in. const rtf = new intl.relativetimeformat("en", { localematcher: "best fit", // other values: "lookup" numeric: "always", // other values: "auto" style: "long", // other values: "short" or "narrow" }); // f...
...s: "auto" style: "long", // other values: "short" or "narrow" }); // format relative time using negative value (-1). rtf.format(-1, "day"); // > "1 day ago" // format relative time using positive value (1). rtf.format(1, "day"); // > "in 1 day" using the auto option if numeric:auto option is passed, it will produce the string yesterday or tomorrow instead of 1 day ago or in 1 day. this allows to not always have to use numeric values in the output. // create a relative time formatter in your locale // with numeric: "auto" option value passed in. const rtf = new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using negative value (-1). rtf.format(-1, "day"); // > "yesterday" // format relative time using positive day unit (1). rtf.format(1, "day"); // > "...
Intl.RelativeTimeFormat.prototype.resolvedOptions() - JavaScript
to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax relativetimeformat.resolvedoptions() return value a new object with properties reflecting the locale and number formatting options computed during the initialization of the given relativetimeformat object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 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. style the length of the internationalized message. possible values are: "long" (default, e.g., in 1 month) "...
... style the length of the internationalized message. possible values are: "long" (default, e.g., in 1 month) "short" (e.g., in 1 mo.), or "narrow" (e.g., in 1 mo.). the narrow style could be similar to the short style for some locales. numeric the format of output message. possible values are: "always" (default, e.g., 1 day ago), or "auto" (e.g., yesterday). the "auto" value allows to not always have to use numeric values in the output. numberingsystem the value requested using the unicode extension key "nu" or filled in as a default. examples using the resolvedoptions method var de = new intl.relativetimeformat('de-de'); var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de-de" usedoptions.style; // "long" usedoptions.numeric; ...
Intl.RelativeTimeFormat - JavaScript
intl.relativetimeformat.prototype.formattoparts() returns an array of objects representing the relative time format in parts that can be used for custom locale-aware formatting. intl.relativetimeformat.prototype.resolvedoptions() returns a new object with properties reflecting the locale and formatting options computed during initialization of the object. examples basic format usage the following example shows how to use a relative time formatter for the english language. // create a relative time formatter in your locale // with default values explicitly passed in. const rtf = new intl.relativetimeformat("en", { localematcher: "best fit", // other values: "lookup" numeric: "always", // other values: "auto" style: "long", // other values: "short" or "narrow" }); // format...
...lativetimeformat("en", { localematcher: "best fit", // other values: "lookup" numeric: "always", // other values: "auto" style: "long", // other values: "short" or "narrow" }); // format relative time using negative value (-1). rtf.format(-1, "day"); // > "1 day ago" // format relative time using positive value (1). rtf.format(1, "day"); // > "in 1 day" using formattoparts the following example shows how to create a relative time formatter returning formatted parts const rtf = new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using the day unit. rtf.formattoparts(-1, "day"); // > [{ type: "literal", value: "yesterday"}] rtf.formattoparts(100, "day"); // > [{ type: "literal", value: "in " }, // > { type: "integer", value: "100", unit: "day" },...
JSON.parse() - JavaScript
ct all unexpected forms. // we split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in ie's and safari's regexp engines. first we // replace the json backslash pairs with "@" (a non-json character). second, we // replace all simple value tokens with "]" characters. third, we delete all // open brackets that follow a colon or comma or that begin the text. finally, // we look to see that the remaining characters are only whitespace or "]" or // "," or ":" or "{" or "}". if that is so, then the text is safe for eval. if ( rx_one.test( text .replace(rx_two, "@") .replace(rx_three, "]") .replace(rx_four, "") ...
...mber' ? value * 2 // return value * 2 for numbers : value // return everything else unchanged ); // { p: 10 } json.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => { console.log(key); // log the current property name, the last is "". return value; // return the unchanged property value. }); // 1 // 2 // 4 // 6 // 5 // 3 // "" json.parse() does not allow trailing commas // both will throw a syntaxerror json.parse('[1, 2, 3, 4, ]'); json.parse('{"foo" : 1, }'); json.parse() does not allow single quotes // will throw a syntaxerror json.parse("{'foo': 1}"); specifications specification ecmascript (ecma-262)the definition of 'json.parse' in that specification. ...
Map.prototype.forEach() - JavaScript
in insertion order. 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 mymap.foreach(callback([value][,key][,map])[, thisarg]) parameters callback function to execute for each entry of mymap. it takes the following arguments: value optional value of each iteration. key optional key of each iteration. map optional the map being iterated (mymap in the above syntax box). thisarg optional value to use as this when executing callback. return value undefined. description the foreach method executes the provided callback once for each key of the map which actually exist. it is not invo...
...ch 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 does not return a value. ...
Map - JavaScript
keyfunc" mymap.get('a string') // "value associated with 'a string'" // because keystring === 'a string' mymap.get({}) // undefined, because keyobj !== {} mymap.get(function() {}) // undefined, because keyfunc !== function () {} using nan as map keys nan can also be used as a key. ...
... 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]) ...
Math.fround() - JavaScript
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. ...
...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 static method of math, you always use it as math.fround(), rather than as a method of a math object you created (math is not a constructor). polyfill this can be emulated with the following function, if float32array are supported: math.fround = math.fround || (function (array) { return function(x) { return array[0] = x, array[0]; }; })(new float32array(1)); supporting older browsers is slower, but also possible: if (!math.fround) math.fround = function(arg) { arg = number(arg); // return early for ±0 and nan. if (!arg) return arg; var sign = arg < 0 ? -1 : 1;...
Math.min() - JavaScript
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. ...
...ameter 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. 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 construc...
Object.create() - JavaScript
now look very much like ordinary objects. polyfill this polyfill covers the main use case, which is creating a new object for which the prototype has been chosen but doesn't take the second argument into account. note that while the setting of null as [[prototype]] is supported in the real es5 object.create, this polyfill cannot support it due to a limitation inherent in versions of ecmascript lower than 5. if (typeof object.create !== "function") { object.create = function (proto, propertiesobject) { if (typeof proto !== 'object' && typeof proto !== 'function') { throw new typeerror('object prototype may only be an object: ' + proto); } else if (proto === null) { throw new error("this browser's implementation of object.create is a shim and doe...
...this is for a single inheritance, which is all that javascript supports. // shape - superclass function shape() { this.x = 0; this.y = 0; } // superclass method shape.prototype.move = function(x, y) { this.x += x; this.y += y; console.info('shape moved.'); }; // rectangle - subclass function rectangle() { ...
Object.entries() - JavaScript
s() returns an array whose elements are arrays corresponding to the enumerable string-keyed property [key, value] pairs found directly upon object. the ordering of the properties is the same as that given by looping over the property values of the object manually. ...
.... ...
Object.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. syntax object.tosource(); obj.tosource(); return value a string representing 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 pers...
...('cyclical: ' + (obj1.b.a == obj1)); var objsource = obj1.tosource(); // returns "({b:{a:{}}})" obj1 = eval(objsource); console.log('cyclical: ' + (obj1.b.a == obj1)); if a cyclical structure is employed and tosource() is needed, the object must provide an override to tosource(), either using a reference to a constructor or providing an anonymous function. ...
Object.prototype.valueOf() - JavaScript
e. when you create a custom object, you can override object.prototype.valueof() to call a custom method instead of the default object method. overriding valueof for custom objects you can create a function to be called in place of the default valueof method. your function must take no arguments. suppose you have an object type mynumbertype and you want to create a valueof method for it. the following code assigns a user-defined function to the object's valueof method: mynumbertype.prototype.valueof = function() { return customprimitivevalue; }; with the preceding code in place, any time an object of type mynumbertype is used in a context where it is to be represented as a primitive value, javascript automatically calls the function defined in the preceding code. an object's valueof meth...
...mynumbertype.prototype.valueof = function() { return customprimitivevalue; }; with the preceding code in place, any time an object of type mynumbertype is used in a context where it is to be represented as a primitive value, javascript automatically calls the function defined in the preceding code. an object's valueof method is usually invoked by javascript, but you can invoke it yourself as follows: mynumbertype.valueof() note: objects in string contexts convert via the tostring() method, which is different from string objects converting to string primitives using valueof. all objects have a string conversion, if only "[object type]". but many objects do not convert to number, boolean, or function. examples using valueof on custom types function mynumbertype(n) { this.number = n...
Promise.all() - JavaScript
ssed contains no promises. note, google chrome 58 returns an already resolved promise in this case. a pending promise in all other cases. this returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when all the promises in the given iterable have resolved, or if any of the promises reject. see the example about "asynchronicity or synchronicity of promise.all" below. returned values will be in order of the promises passed, regardless of completion order. description this method can be useful for aggregating the results of multiple promises. it is typically used when there are multiple asynchronous tasks that are dependent on one another to complete successfully, as it does not wait and will reject immediately upon any of the input promises rejecting. i...
...se.reject(555)]); // using settimeout we can execute code after the stack is empty settimeout(function() { console.log(p); console.log(p2); console.log(p3); }); // logs // promise { <state>: "fulfilled", <value>: array[3] } // promise { <state>: "fulfilled", <value>: array[4] } // promise { <state>: "rejected", <reason>: 555 } asynchronicity or synchronicity of promise.all this following example demonstrates the asynchronicity (or synchronicity, if the iterable passed is empty) of promise.all: // we are passing as argument an array of promises that are already resolved, // to trigger promise.all as soon as possible var resolvedpromisesarray = [promise.resolve(33), promise.resolve(44)]; var p = promise.all(resolvedpromisesarray); // immediately logging the value of p console.
Promise.any() - JavaScript
bject, which extends error, and contains an errors property with an array of rejection values. examples first to fulfil promise.any() resolves with the first promise to fulfil, even if a promise rejects first. this is in contrast to promise.race(), which resolves or rejects with the first promise to settle. ...
...t. this is in contrast to promise.race(), which resolves or rejects with the first promise to settle. const perr = new promise((resolve, reject) => { reject("always fails"); }); const pslow = new promise((resolve, reject) => { settimeout(resolve, 500, "done eventually"); }); const pfast = new promise((resolve, reject) => { settimeout(resolve, 100, "done quick"); }); promise.any([perr, pslow, pfast]).then((value) => { console.log(value); // pfast fulfils first }) // expected output: "done quick" rejections with aggregateerror promise.any() rejects with an aggregateerror if no promise fulfils. const perr = new promise((resolve, reject) => { reject('always fails'); }); promise.any([perr]).catch((err) => { console.log(err); }) // expected output: "aggregateerror: no promise...
Promise.prototype.catch() - JavaScript
reason. the promise returned by catch() is rejected if onrejected throws an error or returns a promise which is itself rejected; otherwise, it is resolved. return value internally calls promise.prototype.then on the object upon which it was called, passing the parameters undefined and the received onrejected handler. returns the value of that call, which is a promise. note the examples below are throwing instances of error. this is considered good practice in contrast to throwing strings; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information like stack traces. demonstration of the internal call: // overriding original promise.prototype.then/catch just to add some logs (function(p...
...he catch method var p1 = new promise(function(resolve, reject) { resolve('success'); }); p1.then(function(value) { console.log(value); // "success!" throw new error('oh, no!'); }).catch(function(e) { console.error(e.message); // "oh, no!" }).then(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('not fired due to the catch'); }); // the following behaves the same as above p1.then(function(value) { console.log(value); // "success!" return promise.reject('oh, no!'); }).catch(function(e) { console.error(e); // "oh, no!" }).then(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('not fired due to the catch'); }); gotchas when throwing errors // throwing an error will call the catch met...
handler.apply() - JavaScript
andler.apply() method is a trap for a function call. 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 const p = new proxy(target, { apply: function(target, thisarg, argumentslist) { } }); parameters the following parameters are passed to the apply() method. this is bound to the handler. target the target object. thisarg the this argument for the call. argumentslist the list of arguments for the call. return value the apply() method can return any value. description the handler.apply() method is a trap for a function call. interceptions this trap can intercept these operations: proxy(.
.... thisarg the this argument for the call. argumentslist the list of arguments for the call. return value the apply() method can return any value. description the handler.apply() method is a trap for a function call. interceptions this trap can intercept these operations: proxy(...args) function.prototype.apply() and function.prototype.call() reflect.apply() invariants if the following invariants are violated, the proxy will throw a typeerror. the target must be a callable itself. that is, it must be a function object. examples trapping a function call the following code traps a function call. const p = new proxy(function() {}, { apply: function(target, thisarg, argumentslist) { console.log('called: ' + argumentslist.join(', ')); return argumentslist[0] + argu...
handler.deleteProperty() - JavaScript
eleteproperty() method is a trap for the delete operator. 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 const p = new proxy(target, { deleteproperty: function(target, property) { } }); parameters the following parameters are passed to the deleteproperty() method. this is bound to the handler. target the target object. property the name or symbol of the property to delete. return value the deleteproperty() method must return a boolean indicating whether or not the property has been successfully deleted. description the handler.deleteproperty() method is a trap for the delete operator. int...
...o delete. return value the deleteproperty() method must return a boolean indicating whether or not the property has been successfully deleted. description the handler.deleteproperty() method is a trap for the delete operator. interceptions this trap can intercept these operations: property deletion: delete proxy[foo] and delete proxy.foo reflect.deleteproperty() invariants if the following invariants are violated, the proxy will throw a typeerror: a property cannot be deleted, if it exists as a non-configurable own property of the target object. examples trapping the delete operator the following code traps the delete operator. const p = new proxy({}, { deleteproperty: function(target, prop) { if (prop in target){ delete target[prop] console.log('proper...
handler.getPrototypeOf() - JavaScript
prototypeof() method is a trap for the [[getprototypeof]] internal method. 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 const p = new proxy(obj, { getprototypeof(target) { ... ...
... if target is not extensible, object.getprototypeof(proxy) method must return the same value as object.getprototypeof(target). ...
handler.setPrototypeOf() - JavaScript
totypeof() method is a trap for object.setprototypeof(). 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 const p = new proxy(target, { setprototypeof: function(target, prototype) { } }); parameters the following parameters are passed to the setprototypeof() method. this is bound to the handler. target the target object. prototype the object's new prototype or null. return value the setprototypeof() method returns true if the [[prototype]] was successfully changed, otherwise false. description the handler.setprototypeof() method is a trap for object.setprototypeof(). interceptions this tra...
...bject. prototype the object's new prototype or null. return value the setprototypeof() method returns true if the [[prototype]] was successfully changed, otherwise false. description the handler.setprototypeof() method is a trap for object.setprototypeof(). interceptions this trap can intercept these operations: object.setprototypeof() reflect.setprototypeof() invariants if the following invariants are violated, the proxy will throw a typeerror: if target is not extensible, the prototype parameter must be the same value as object.getprototypeof(target). examples if you want to disallow setting a new prototype for your object, your handler's setprototypeof() method can either return false, or it can throw an exception. approach 1: returning false this approach means tha...
Reflect.construct() - JavaScript
get optional the constructor whose prototype should be used. see also the new.target operator. if newtarget is not present, its value defaults to target. return value a new instance of target (or newtarget, if present), initialized by target as a constructor with the given argumentslist. exceptions a typeerror, if target or newtarget are not constructors. description reflect.construct() allows you to invoke a constructor with a variable number of arguments. (this would also be possible by using the spread syntax combined with the new operator.) let obj = new foo(...args) let obj = reflect.construct(foo, args) reflect.construct() vs object.create() prior to the introduction of reflect, objects could be constructed using an arbitrary combination of constructor and prototype by using...
...when using object.create() and function.prototype.apply(), the new.target operator will point to undefined wi...
RegExp.prototype.compile() - JavaScript
the deprecated compile() method is used to (re-)compile a regular expression during execution of a script. it is basically the same as the regexp constructor. syntax regexobj.compile(pattern, flags) parameters pattern the text of the regular expression. flags if specified, flags can have any combination of the following values: g global match i ignore case m multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string) y sticky; matches only from the index indicated by the lastindex property of this regular expression in the target string (and does not attempt to match from any later indexes). desc...
...ot only the very beginning or end of the whole input string) y sticky; matches only from the index indicated by the lastindex property of this regular expression in the target string (and does not attempt to match from any later indexes). description the compile method is deprecated. you can just use the regexp constructor to achieve the same effect. examples using compile() the following example shows how to recompile a regular expression with a new pattern and a new flag. var regexobj = new regexp('foo', 'gi'); regexobj.compile('new foo', 'g'); specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.compile' in that specification. ...
RegExp.prototype.dotAll - JavaScript
ression instance. 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...
... you cannot change this property directly. ...
RegExpInstance.lastIndex - JavaScript
index at which to start the next match. property attributes of regexpinstance.lastindex writable yes enumerable no configurable no description this property is set only if the regular expression instance used the g flag to indicate a global search, or the y flag to indicate a sticky search. the following rules apply: if lastindex is greater than the length of the string, test() and exec() fail, then lastindex is set to 0. if lastindex is equal to or less than the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting from lastindex. if lastindex is equal to the length of the string and if the regular expression does ...
...less than the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting from lastindex. if lastindex is equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, and lastindex is reset to 0. otherwise, lastindex is set to the next position following the most recent match. examples using lastindex consider the following sequence of statements: var re = /(hi)?/g; matches the empty string. console.log(re.exec('hi')); console.log(re.lastindex); returns ["hi", "hi"] with lastindex equal to 2. console.log(re.exec('hi')); console.log(re.lastindex); returns ["", undefined], an empty array whose zeroth element is the match string. in ...
RegExp.$1-$9 - JavaScript
and modified whenever successful matches are made. the number of possible parenthesized substrings is unlimited, but the regexp object can only hold the first nine. you can access all parenthesized substrings through the returned array's indexes. these properties can be used in the replacement text for the string.replace method. when used this way, do not prepend them with regexp. the example below illustrates this. when parentheses are not included in the regular expression, the script interprets $n's literally (where n is a positive integer). examples using $n with string.replace the following script uses the replace() method of the string instance to match a name in the format first last and output it in the format last, first. in the replacement text, the script uses $1 and $2 to ind...
...h a name in the format first last and output it in the format last, first. in the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern. var re = /(\w+)\s(\w+)/; var str = 'john smith'; str.replace(re, '$2, $1'); // "smith, john" regexp.$1; // "john" regexp.$2; // "smith" using $n with regexp.test the following script uses the test() method of the regexp instance to grab a number in a generic string. var str = 'test 24'; var number = /(\d+)/.test(str) ? regexp.$1 : '0'; number; // "24" please note that any operation involving the usage of other regular expressions between a re.test(str) call and the regexp.$n property, might have side effects, so that accessing these special properties should be d...
Set - JavaScript
(5) // set [ 1, 5 ] myset.add('some text') // set [ 1, 5, 'some text' ] let o = {a: 1, b: 2} myset.add(o) myset.add({a: 1, b: 2}) // o is referencing a different object, so this is okay myset.has(1) // true myset.has(3) // false, since 3 has not been added to the set myset.has(5) // true myset.has(math.sqrt(25)) // true myset.has('some text'.tolowercase()) // true myset.has(o) // true myset.size // 5 myset.delete(5) // removes 5 from the set myset.has(5) // false, 5 has been removed myset.size // 4, since we just removed one value console.log(myset) // logs set(4) [ 1, "some text", {…}, {…} ] in firefox // logs set(4) { 1, "some text", {…}, {…} } in chrome iterating sets // iterate over items i...
...: 1, "b": 2} for (let item of myset.values()) console.log(item) // logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} // (key and value are the same here) for (let [key, value] of myset.entries()) console.log(key) // convert set object to an array object, with array.from let myarr = array.from(myset) // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}] // the following will also work if run in an html document myset.add(document.body) myset.has(document.queryselector('body')) // true // converting between set and array myset2 = new set([1, 2, 3, 4]) myset2.size // 4 [...myset2] // [1, 2, 3, 4] // intersect can be simulated via let intersection = new set([...set1].filter(x => set2.has(x))) // difference can be simulate...
Planned changes to shared memory - JavaScript
rs mentioned above are set, for compatibility with web content. there is hope that this restriction can be removed in the future. webassembly.memory can still be used to get an instance. unless the two headers mentioned above are set, the various postmessage() apis will throw for sharedarraybuffer objects. if they are set, postmessage() on window objects and dedicated workers will function and allow for memory sharing. to avoid having to check whether postmessage() throws, self.crossoriginisolated is being standardized (a getter that returns a boolean; true if the headers are set), available in window and worker contexts. webassembly shared memory the webassembly threads proposal allows webassembly.memory objects to be created with a new shared constructor flag. when this flag is set to ...
...the requirements listed above for sharing a sharedarraybuffer between workers also apply to sharing a webassembly.memory. the webassembly threads proposal also defines a new set of atomic instructions. just as sharedarraybuffer and its methods are unconditionally enabled (and only sharing between threads is gated on the new headers), the webassembly atomic instructions are also unconditionally allowed. further reading coop and coep explained. cross-origin-opener-policy: whatwg/html issue #3740, draft specification. cross-origin-embedder-policy: whatwg/html issue #4175, draft specification. cross-origin-resource-policy: standardized in fetch, new cross-origin value is part of the cross-origin-embedder-policy effort. postmessage() changes and self.crossoriginisolated: whatwg/html issue...
String.prototype.anchor() - JavaScript
the anchor() method creates a string beginning with an <a name="..."> start tag, then some text, and then an </a> end tag. don't use this method. use dom apis instead. also, the html specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup. syntax str.anchor(name) parameters name a string representing a name value to put into the generated <a name="..."> start tag. return value a string beginning with an <a name="name"> start tag, then the text str, and then an </a> end tag description don't use this method. use dom apis instead. also, the html specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup. examples using anchor() var mystring = 'table...
...> start tag, then the text str, and then an </a> end tag description don't use this method. use dom apis instead. also, the html specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup. examples using anchor() var mystring = 'table of contents'; document.body.innerhtml = mystring.anchor('contents_anchor'); will output the following html: <a name="contents_anchor">table of contents</a> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.anchor' in that specification. ...
String.prototype.codePointAt() - JavaScript
pos position of an element in str to return the code point value from. return value a number representing the code point value of the character at the given pos. if there is no element at pos, returns undefined. description if there is no element at the specified position, undefined is returned. if no utf-16 surrogate pair begins at pos, the code unit at pos is returned. polyfill the following extends strings to include the codepointat() function as specified in ecmascript 2015 for browsers without native support. /*! https://mths.be/codepointat v0.2.0 by @mathias */ if (!string.prototype.codepointat) { (function() { 'use strict'; // needed to support `apply`/`call` with `undefined`/`null` var defineproperty = (function() { // ie 8 only supports `object.defineproper...
...fined; } // get the first code unit var first = string.charcodeat(index); var second; if ( // check if it’s the start of a surrogate pair first >= 0xd800 && first <= 0xdbff && // high surrogate size > index + 1 // there is a next code unit ) { second = string.charcodeat(index + 1); if (second >= 0xdc00 && second <= 0xdfff) { // low surrogate // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae return (first - 0xd800) * 0x400 + second - 0xdc00 + 0x10000; } } return first; }; if (defineproperty) { defineproperty(string.prototype, 'codepointat', { 'value': codepointat, 'configurable': true, 'writable': true }); } else { ...
String.fromCodePoint() - JavaScript
de point"). description this method returns a string (and not a string object). because fromcodepoint() is a static method of string, you must call it as string.fromcodepoint(), rather than as a method of a string object you created. polyfill the string.fromcodepoint() method has been added to ecmascript 2015 and may not be supported in all web browsers or environments yet. ...
...int <= 0xffff) { // bmp code point codelen = codeunits.push(codepoint); } else { // astral code point; split in surrogate halves // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae codepoint -= 0x10000; codelen = codeunits.push( (codepoint >> 10) + 0xd800, // highsurrogate (codepoint % 0x400) + 0xdc00 // lowsurrogate ); } if (codelen >= 0x3fff) { result += stringfromcharcode.apply(null, codeunits); codeunits.length = 0; } } return result + stringfromcharcode.apply(null, codeunits); }; try { // ie 8 only supports `object.defineproperty` on dom elements object.defineproperty(string, "fromcodepoint", { "value": fromc...
String.prototype.slice() - JavaScript
g. changes to the text in one string do not affect the other string. slice() extracts up to but not including endindex. str.slice(1, 4) extracts the second character through the fourth character (characters indexed 1, 2, and 3). as an example, str.slice(2, -1) extracts the third character through the second to last character in the string. examples using slice() to create a new string the following example uses slice() to create a new string. let str1 = 'the morning is upon us.', // the length of str1 is 23. str2 = str1.slice(1, 8), str3 = str1.slice(4, -2), str4 = str1.slice(12), str5 = str1.slice(30); console.log(str2) // output: he morn console.log(str3) // output: morning is upon u console.log(str4) // output: is upon us. console.log(str5) // output: "" using s...
...new string. let str1 = 'the morning is upon us.', // the length of str1 is 23. str2 = str1.slice(1, 8), str3 = str1.slice(4, -2), str4 = str1.slice(12), str5 = str1.slice(30); console.log(str2) // output: he morn console.log(str3) // output: morning is upon u console.log(str4) // output: is upon us. console.log(str5) // output: "" using slice() with negative indexes the following example uses slice() with negative indexes. let str = 'the morning is upon us.' str.slice(-3) // returns 'us.' str.slice(-3, -1) // returns 'us' str.slice(0, -1) // returns 'the morning is upon us' this example counts backwards from the end of the string by 11 to find the start index and forwards from the start of the string by 16 to find the end index. console.log(str.slice(-11, 1...
String.prototype.trim() - JavaScript
e 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. description the trim() method returns the string stripped of whitespace from both ends. trim() does not affect the value of the str itself. ...
... returns the string stripped of whitespace from both ends. trim() does not affect the value of the str itself. polyfill running the following code before any other code will create trim() if it's not natively available. if (!string.prototype.trim) { string.prototype.trim = function () { return this.replace(/^[\s\ufeff\xa0]+|[\s\ufeff\xa0]+$/g, ''); }; } examples using trim() the following example displays the lowercase string 'foo': var orig = ' foo '; console.log(orig.trim()); // 'foo' // another example of .trim() removing whitespace from just one side. var orig = 'foo '; console.log(orig.trim()); // 'foo' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.trim' in that specification. ...
String.prototype.trimStart() - JavaScript
...
... ...
TypedArray.from() - JavaScript
ray. thisarg optional value to use as this when executing mapfn. return value a new typedarray instance. description typedarray.from() lets you create typed arrays from: array-like objects (objects with a length property and indexed elements); or iterable objects (objects where you can get its elements, such as map and set). typedarray.from() has the optional parameter mapfn, which allows you to execute a map() function on each element of the typed array (or subclass object) that is being created. this means that the following are equivalent: typedarray.from(obj, mapfn, thisarg) typedarray.from(array.prototype.map.call(obj, mapfn, thisarg)). the length property of the from() method is 1. differences from array.from() some subtle distinctions between array.from() and typed...
...erator, then creates an instance of thisarg using the count, then sets the values on the instance. array.from() sets each value as it receives them from the iterator, then sets its length at the end. when array.from() gets an array-like which isn't an iterator, it respects holes. typedarray.from() will ensure the result is dense. polyfill you can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of from() in implementations that do not natively support it. if (!int8array.__proto__.from) { (function () { int8array.__proto__.from = function (obj, func, thisobj) { var typedarrayclass = int8array.__proto__; if(typeof this !== 'function') { throw new typeer...
TypedArray.prototype.map() - JavaScript
fore 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 typed array are changed, or deleted, their value as passed to mapfn will be the value at the time map() visits them; elements that are deleted are not visited. ...
...the argument will automatically be assigned to each element of the typed array as map loops through the original typed array. ...
TypedArray.prototype.slice() - JavaScript
this method has the same algorithm as array.prototype.slice(). 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.slice([begin[, end]]) parameters begin optional zero-based index at which to begin extraction. a negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence. if begin is undefined, slice begins from index 0. ...
...d 3). a negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. if end is omitted, slice extracts through the end of the sequence (typedarray.length). return value a new typed array containing the extracted elements. description the slice method does not alter. it returns a shallow copy of elements from the original typed array. if a new element is added to either typed array, the other typed array is not affected. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as needed" basis. if (!uint8array.prototype.slice) { object.defineproperty(uint8array.prototype, 'slice', { value: function (begin, end) { re...
TypedArray - JavaScript
a typedarray object describes an array-like view of an underlying binary data buffer. there is no global property named typedarray, nor is there a directly visible typedarray constructor. instead, there are a number of different global properties, whose values are typed array constructors for specific element types, listed below. on the following pages you will find common properties and methods that can be used with any typed array containing elements of any 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. description ecmascript 2015 defines a typedarray constructor that serves as the [[prototype]] of al...
... ...
WebAssembly.Global() constructor - JavaScript
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. ...
...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 using the webassembly.global() constructor. it is being defined as a mutable i32 type, with a value of 0. the value of the global is then changed, first to 42 using the global.value property, and then to 43 using the incglobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the n...
WebAssembly.Global - JavaScript
constructor webassembly.global() creates a new global object. global instances all global instances inherit from the global() constructor's prototype object — this can be modified to affect all global instances. instance properties global.prototype.constructor returns the function that created this object's instance. by default this is the webassembly.global() constructor. ...
...itial value of the @@tostringtag property is the string value "webassembly.global". global.prototype.value the value contained inside the global variable — this can be used to directly set and get the global's value. instance methods global.prototype.valueof() old-style method that returns the value contained inside the global variable. examples creating a new global instance the following example shows a new global instance being created using the webassembly.global() constructor. it is being defined as a mutable i32 type, with a value of 0. the value of the global is then changed, first to 42 using the global.value property, and then to 43 using the incglobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the n...
WebAssembly.Instance - JavaScript
read-only. ...
...read-only. ...
WebAssembly.Memory - JavaScript
ototype.buffer an accessor property that returns the buffer contained in the memory. instance methods memory.prototype.grow() increases the size of the memory instance by a specified number of webassembly pages (each one is 64kb in size). examples creating a new memory object there are two ways to get a webassembly.memory object. the first way is to construct it from javascript. ...
...it then stores some values in that memory, then exports a function and uses it to sum some values. ...
WebAssembly.Module.customSections() - JavaScript
m spec, but modules can also contain custom sections that are ignored and skipped over during validation. (read high level structure for information on section structures, and how normal sections ("known sections") and custom sections are distinguished.) this provides developers with a way to include custom data inside wasm modules for other purposes, for example the name custom section, which allows developers to provide names for all the functions and locals in the module (like "symbols" in a native build). note that the webassembly text format currently doesn't have a syntax specified for adding new custom sections; you can however add a name section to your wasm during conversion from text format over to .wasm. the wast2wasm command available as part of the wabt tool has a --debug-names...
...ections; you can however add a name section to your wasm during conversion from text format over to .wasm. the wast2wasm command available as part of the wabt tool has a --debug-names option — specify this during conversion to get a .wasm with a names custom section, for example: wast2wasm simple-name-section.was -o simple-name-section.wasm --debug-names examples using customsections the following example (see the custom-section.html source and live example) compiles the loaded simple-name-section.wasm byte code. we then do a check using webassembly.module.customsections, looking to see whether the module instance contains a "name" custom section by checking that its length is more than 0. since there is a "name" section in the example, an arraybuffer object is returned. webassembly.c...
WebAssembly.Table() constructor - JavaScript
the webassembly.table() constructor creates a new table object of the given size and element type. syntax new webassembly.table(tabledescriptor); parameters tabledescriptor an object that can contain the following members: element a string representing the type of value to be stored in the table. at the moment this can only have a value of "anyfunc" (functions). initial the initial number of elements of the webassembly table. maximum optional the maximum number of elements the webassembly table is allowed to grow to. ...
...ctions). initial the initial number of elements of the webassembly table. maximum optional the maximum number of elements the webassembly table is allowed to grow to. exceptions if tabledescriptor is not of type object, a typeerror is thrown. if maximum is specified and is smaller than initial, a rangeerror is thrown. examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements. we then print out the table length and contents of the two indexes (retrieved via table.prototype.get() to show that the length is two and both elements are null. var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" co...
WebAssembly.Table.prototype.grow() - JavaScript
prototype method of the webassembly.table object increases the size of the table instance by a specified number of elements. syntax table.grow(number); parameters number the number of elements you want to grow the table by. return value the previous length of the table. exceptions if the grow() operation fails for whatever reason, a rangeerror is thrown. ...
...n value the previous length of the table. exceptions if the grow() operation fails for whatever reason, a rangeerror is thrown. examples using grow the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10. var table = new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification webassembly javascript interfacethe definition of 'grow()' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please...
WebAssembly.instantiate() - JavaScript
this function has two overloads: the primary overload takes the webassembly binary code, in the form of a typed array or arraybuffer, and performs both compilation and instantiation in one step. the returned promise resolves to both a compiled webassembly.module and its first 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. ...
...ect = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).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 def...
WebAssembly - JavaScript
embly via the webassembly.compileerror()/webassembly.linkerror()/webassembly.runtimeerror() constructors. constructor properties webassembly.compileerror() indicates an error during webassembly decoding or validation. webassembly.global() represents a global variable instance, accessible from both javascript and importable/exportable across one or more webassembly.module instances. this allows dynamic linking of multiple modules. webassembly.instance() is a stateful, executable instance of a webassembly.module webassembly.linkerror() indicates an error during module instantiation (besides traps from the start function). webassembly.memory() an object whose buffer property is a resizable arraybuffer that holds the raw bytes of memory accessed by a webassembly instance. webassemb...
... 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). 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. because the instantiatestreaming() function accepts a promise for a response object, you can directly pass it a windoworworkerglobalscope.fetch() call, and it will pass the re...
Comma operator (,) - JavaScript
se the comma operator when you want to include multiple expressions in a location that requires a single expression. the most common usage of this operator is to supply multiple parameters in a for loop. the comma operator is fully different from the comma within arrays, objects, and function arguments and parameters. examples if a is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i and decrement j at once. the following code prints the values of the diagonal elements in the array: for (var i = 0, j = 9; i <= 9; i++, j--) console.log('a[' + i + '][' + j + '] = ' + a[i][j]); note that the comma operators in assignments may appear not to have the normal effect of comma operators because they don't exist within an expression. ...
...this is due to operator precedence and associativity. ...
Conditional (ternary) operator - JavaScript
this operator is frequently used as a shortcut for the if statement. 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. ...
...values one common usage is to handle a value that may be null: let greeting = person => { let name = person ? person.name : `stranger` return `howdy, ${name}` } console.log(greeting({name: `alice`})); // "howdy, alice" console.log(greeting(null)); // "howdy, stranger" conditional chains the ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain: function example(…) { return condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4; } // equivalent to: function example(…) { if (condition1) { return value1; } else if (condition2) { return value2; } else if (condition3) { return value3; } else { return valu...
Equality (==) - 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 x == y description the equality operators (== and !=) use the abstract equality comparison algorithm to compare two operands. this can be roughly summarised as follows: if the operands are both objects, return true only if both operands reference the same object. if one operand is null and the other is undefined, return true. if the operands are of different types, try to convert them to the same type before comparing: when comparing a number to a string, try to convert the string to a numeric value. if one of the operands is boolean, convert the...
...string, try to convert the string to a numeric value. if one of the operands is boolean, convert the boolean operand to 1 if it is true and +0 if it is false. if one of the operands is an object and the other is a number or a string, try to convert the object to a primitive using the object's valueof() and tostring() methods. if the operands have the same type, they are compared as follows: string: return true only if both operands have the same characters in the same order. number: return true only if both operands have the same value. +0 and -0 are treated as the same value. if either operand is nan, return false. boolean: return true only if operands are both true or both false. the most notable difference between this operator and the strict equality (===) o...
Logical AND assignment (&&=) - JavaScript
rce 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 expr1 &&= expr2 description short-circuit evaluation the logical and operator is evaluated left to right, it is tested for possible short-circuit evaluation using the following rule: (some falsy expression) && expr is short-circuit evaluated to the falsy expression; short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). logical and assignment short-circuits as well meaning that x &&= y is equivalent to: x && (x = y); and not equivalent...
...(some falsy expression) && expr is short-circuit evaluated to the falsy expression; short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). logical and assignment short-circuits as well meaning that x &&= y is equivalent to: x && (x = y); and not equivalent to the following which would always perform an assignment: x = x && y; examples using logical and assignment let x = 0; let y = 1; x &&= 0; // 0 x &&= 1; // 0 y &&= 1; // 1 y &&= 0; // 0 specifications specification logical assignment operatorsthe definition of 'assignment operators' in that specification. ...
Logical NOT (!) - JavaScript
ndefined. even though the ! operator can be used with operands that are not boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. to explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double not operator or the boolean constructor. examples using not the following code shows examples of the ! (logical not) operator. n1 = !true // !t returns false n2 = !false // !f returns true n3 = !'' // !f returns true n4 = !'cat' // !t returns false double not (!!) it is possible to use a couple of not operators in series to explicitly force the conversion of any value to the corresponding boolean primitive. ...
... // !!truthy returns true n2 = !!{} // !!truthy returns true: any object is truthy... n3 = !!(new boolean(false)) // ...even boolean objects with a false .valueof()! n4 = !!false // !!falsy returns false n5 = !!"" // !!falsy returns false n6 = !!boolean(false) // !!falsy returns false converting between nots the following operation involving booleans: !!bcondition is always equal to: bcondition specifications specification ecmascript (ecma-262)the definition of 'logical not expression' in that specification. ...
Logical nullish assignment (??=) - JavaScript
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 expr1 ??= expr2 description short-circuit evaluation the nullish coalescing operator is evaluated left to right, it is tested for possible short-circuit evaluation using the following rule: (some expression that is neither null nor undefined) ?? expr is short-circuit evaluated to the left-hand side expression if the left-hand side proves to be neither null nor undefined. short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). logical nullish ass...
... side expression if the left-hand side proves to be neither null nor undefined. 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). ...
Property accessors - JavaScript
= 77.0, no ambiguity bracket notation in the object[property_name] syntax, the property_name is just a string or symbol. so, it can be any string, including '1foo', '!bar!', or even ' ' (a space). const variable = object[property_name] object[property_name] = value; this does the exact same thing as the previous example. document['createelement']('pre') a space before bracket notation is allowed. document ['createelement']('pre') property names property names are string or symbol. any other value, including a number, is coerced to a string. this outputs 'value', since 1 is coerced into '1'. let object = {} object['1'] = 'value' console.log(object[1]) this also outputs 'value', since both foo and bar are converted to the same string. let foo = {unique_prop: 1}, bar = {unique_prop...
...to the object that it is a method of. specifically, this is not fixed in a method. put another way, this does not necessarily refer to the object containing a method. instead, this is "passed" by the function call. see method binding. examples bracket notation vs. eval javascript novices often make the mistake of using eval() where the bracket notation can be used instead. for example, the following syntax is often seen in many scripts. x = eval('document.forms.form_name.elements.' + strformcontrol + '.value') eval() is slow and should be avoided whenever possible. also, strformcontrol would have to hold an identifier, which is not required for names and ids of form controls. it is better to use bracket notation instead: x = document.forms['form_name'].elements[strformcontrol].value ...
class expression - JavaScript
; description a class expression has a similar syntax to a class declaration (statement). as with class statements, the body of a class expression is executed in strict mode. there are several differences between class expressions and class statements, however: class expressions may omit the class name ("binding identifier"), which is not possible with class statements. ...
...atements. class expressions allow you to redefine (re-declare) classes without throwing a syntaxerror. this is not the case with class statements. the constructor method is optional. classes generated with class expressions will always respond to typeof with the value "function". 'use strict'; let foo = class {}; // constructor property is optional foo = class {}; // re-declaration is allowed typeof foo; // returns "function" typeof class {}; // returns "function" foo instanceof object; // true foo instanceof function; // true class foo {} // throws syntaxerror (class declarations do not allow re-declaration) examples a simple class expression this is just a simple anonymous class expression which you can refer to using the variable foo. const ...
Function expression - JavaScript
e used to define a function inside an expression. you can also define functions using the function constructor and a function declaration. 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 expression is not allowed at the start of a statement. function [name]([param1[, param2[, ..., paramn]]]) { statements } as of es2015, you can also use arrow functions. parameters name optional the function name. can be omitted, in which case the function is anonymous. the name is only local to the function body. paramn optional the name of an argument to be passed to the function. statements optional the ...
...ons (arrows don't have a name so you can only give the variable an implicit name). var foo = function() {} foo.name // "foo" var foo2 = foo foo2.name // "foo" var bar = function baz() {} bar.name // "baz" console.log(foo === foo2); // true console.log(typeof baz); // undefined console.log(bar === baz); // false (errors because baz == undefined) examples creating an unnamed function the following example defines an unnamed function and assigns it to x. the function returns the square of its argument: var x = function(y) { return y * y; }; using a function as a callback more commonly it is used as a callback: button.addeventlistener('click', function(event) { console.log('button is clicked!') }) using an immediately executed function expression an anonymous function is cr...
instanceof - JavaScript
face) 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 demonstrating that string and date are of type object and exceptional cases the following code uses instanceof to demonstrate that string and date objects are also of type object (they are derived from object). however, objects created with the object literal notation are an exception here: although the prototype is undefined, instanceof object returns true. let simplestr = 'this is a simple string' let mystring = new string() let newstr = new string('string created with cons...
...the instanceof operator demonstrates that the mycar object is of type car and of type object. function car(make, model, year) { this.make = make; this.model = model; this.year = year; } let mycar = new car('honda', 'accord', 1998) let a = mycar instanceof car // returns true let b = mycar instanceof object ...
Expressions and operators - JavaScript
destination of an assignment. property accessors member operators provide access to a property or method of an object (object.property and object["property"]). new the new operator creates an instance of a constructor. new.target in constructors, new.target refers to the constructor that was invoked by new. super the super keyword calls the parent constructor. ...obj spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected. increment and decrement postfix/prefix increment and postfix/prefix decrement operators. a++ postfix increment operator. a-- postfix decrement operator. ++a prefix increment operator. --a prefix decrement operator. unary operators a unary op...
... += addition assignment. -= subtraction assignment <<= left shift assignment. >>= right shift assignment. >>>= unsigned right shift assignment. &= bitwise and assignment. ^= bitwise xor assignment. |= bitwise or assignment. &&= logical and assignment. ||= logical or assignment. ??= logical nullish assignment. [a, b] = [1, 2] {a, b} = {a:1, b:2} destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals. comma operator , the comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression. specifications specification ecmascript (ecma-262)the definition of 'ecmascript language: expre...
class - JavaScript
ss with a given name using prototype-based inheritance. 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. you can also define a class using a class expression. ...
... note that super(), used in the constructor, can only be used in constructors, and must be called before the this keyword can be used. ...
const - JavaScript
tifier cannot be reassigned. for instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered. all the considerations about the "temporal dead zone" apply to both let and const. a constant cannot share its name with a function or a variable in the same scope. examples basic const usage constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters. // define my_fav as a constant and give it the value 7 const my_fav = 7; // this will throw an error - uncaught typeerror: assignment to constant variable. my_fav = 20; // my_fav is 7 console.log('my favorite number is: ' + my_fav); // trying to redeclare a constant throws an error // uncaught syntaxerror: identifier 'my_fav' has...
... an error // uncaught syntaxerror: missing initializer in const declaration const foo; const in objects and arrays const also works on objects and arrays. const my_object = {'key': 'value'}; // attempting to overwrite the object throws an error // uncaught typeerror: assignment to constant variable. my_object = {'other_key': 'value'}; // however, object keys are not protected, // so the following statement is executed without problem my_object.key = 'othervalue'; // use object.freeze() to make object immutable // the same applies to arrays const my_array = []; // it's possible to push items into the array my_array.push('a'); // ["a"] // however, assigning a new array to the variable throws an error // uncaught typeerror: assignment to constant variable. my_array = ['b']; specificatio...
continue - JavaScript
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 statement. examples using continue with while the following example shows a while loop that has a continue statement that executes when the value of i is 3. thus, n takes on the values 1, 3, 7, and 12. var i = 0; var n ...
...if continue is encountered, the program continues at the top of the checkj statement. each time continue is encountered, checkj reiterates until its condition returns false. ...
for...in - JavaScript
asy way to check the properties of an object (by outputting to the console or otherwise). although arrays are often more practical for storing data, in situations where a key-value pair is preferred for working with data (with properties acting as the "key"), there may be instances where you want to check if any of those keys hold a particular value. ...
...s hold a particular value. examples using for...in the for...in loop below iterates over all of the object's enumerable, non-symbol properties and logs a string of the property names and their values. var obj = {a: 1, b: 2, c: 3}; for (const prop in obj) { console.log(`obj.${prop} = ${obj[prop]}`); } // output: // "obj.a = 1" // "obj.b = 2" // "obj.c = 3" iterating own properties the following function illustrates the use of hasownproperty(): the inherited properties are not displayed. var triangle = {a: 1, b: 2, c: 3}; function coloredtriangle() { this.color = 'red'; } coloredtriangle.prototype = triangle; var obj = new coloredtriangle(); for (const prop in obj) { if (obj.hasownproperty(prop)) { console.log(`obj.${prop} = ${obj[prop]}`); } } // output: // "obj.color...
return - JavaScript
tps://github.com/mdn/interactive-examples and send us a pull request. syntax return [[expression]]; expression the expression whose value is to be returned. if omitted, undefined is returned instead. description when a return statement is used in a function body, the execution of the function is stopped. if specified, a given value is returned to the function caller. ...
... a return statement is used in a function body, the execution of the function is stopped. if specified, a given value is returned to the function caller. for example, the following function returns the square of its argument, x, where x is 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...
try...catch - JavaScript
tch-block, the enclosing try statement's catch-block is used instead. you can also use the try statement to handle javascript exceptions. see the javascript guide for more information on javascript exceptions. unconditional catch-block when a catch-block is used, the catch-block is executed when any exception is thrown from within the try-block. for example, when the exception occurs in the following code, control transfers to the catch-block. try { throw 'myexception'; // generates an exception } catch (e) { // statements to handle any exceptions logmyerrors(e); // pass exception object to error handler } the catch-block specifies an identifier (e in the example above) that holds the value of the exception; this value is only available in the scope of the catch-block. conditiona...
...n use this identifier to get information about the exception that was thrown. this identifier is only available in the catch-block's scope. function isvalidjson(text) { try { json.parse(text); return true; } catch { return false; } } the finally-block the finally-block contains statements to execute after the try-block and catch-block(s) execute, but before the statements following the try...catch...finally-block. note that the finally-block executes regardless of whether an exception is thrown. also, if an exception is thrown, the statements in the finally-block execute even if no catch-block handles the exception. the following example shows one use case for the finally-block. the code opens a file and then executes statements that use the file; the finally-block make...
while - JavaScript
evaluates to false, execution continues with the statement after the while loop. statement an optional statement that is executed as long as the condition evaluates to true. to execute multiple statements within the loop, use a block statement ({ ... }) to group those statements. note: use the break statement to stop a loop before condition evaluates to true. ...
...thin the loop, use a block statement ({ ... }) to group those statements. note: use the break statement to stop a loop before condition evaluates to true. examples using while the following while loop iterates as long 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
javascript applications consist of statements with an appropriate syntax. a single statement may span multiple 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 iter...
...nction. class declares a class. iterations do...while creates a loop that executes a specified statement until the test condition evaluates to false. the condition is evaluated after executing the statement, resulting in the specified statement executing at least once. for creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop. for each...in iterates a specified variable over all values of object's properties. for each distinct property, a specified statement is executed. for...in iterates over the enumerable properties of an object, in arbitrary order. for each distinct property, statements can be executed. for...of iterates over iterable objects (including arrays, array-l...
Strict mode - JavaScript
rict mode it's no longer possible to "walk" the javascript stack via commonly-implemented extensions to ecmascript. in normal code with these extensions, when a function fun is in the middle of being called, fun.caller is the function that most recently called fun, and fun.arguments is the arguments for that invocation of fun. both extensions are problematic for "secure" javascript because they allow "secured" code to access "privileged" functions and their (potentially unsecured) arguments. if fun is in strict mode, both fun.caller and fun.arguments are non-deletable properties which throw when set or retrieved: function restricted() { 'use strict'; restricted.caller; // throws a typeerror restricted.arguments; // throws a typeerror } function privilegedinvoker() { return restric...
...ents are an extension of basic es5. but it is the recommendation of the ecmascript committee, and browsers will implement it. strict mode in browsers the major browsers now implement strict mode. however, don't blindly depend on it since there still are numerous browser versions used in the wild that only have partial support for strict mode or do not support it at all (e.g. internet explorer below version 10!). strict mode changes semantics. relying on those changes will cause mistakes and errors in browsers which don't implement strict mode. exercise caution in using strict mode, and back up reliance on strict mode with feature tests that check whether relevant parts of strict mode are implemented. finally, make sure to test your code in browsers that do and don't support strict mode. if ...
JavaScript shells - JavaScript
node.js - node.js is a platform for easily building fast, scalable network applications. jsdb - a standalone javascript shell, with compiled binaries for windows, mac, and linux. javalikescript - a standalone, extensible 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. ...
...s. 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 mozilla development. babel repl - a browser-based repl for experimenting with future javascript. es6console.com - an open-source javascript consol...
JavaScript typed arrays - JavaScript
this is useful when dealing with different types of data, for example. typed array views are in the native byte-order (see endianness) of your platform. with a dataview you are able to control the byte-order. it is big-endian by default and can be set to little-endian in the getter/setter methods. w...
...e amount due with amountdueview[0]. note: the data structure alignment in a c structure is platform-dependent. take precautions and considerations for these padding differences. conversion to normal arrays after processing a typed array, it is sometimes useful to convert it back to a normal array in order to benefit from the array prototype. this can be done using array.from(), or using the following code where array.from() is unsupported. let typedarray = new uint8array([1, 2, 3, 4]), normalarray = array.prototype.slice.call(typedarray); normalarray.length === 4; normalarray.constructor === array; specifications specification ecmascript (ecma-262)the definition of 'typedarray objects' in that specification. ...
<mi> - MathML
Web › MathML › Element › mi
ecated values are: small, normal and big. these will be removed in the future. mathvariant this logical class of the identifier, which varies in typography. that is, although the names suggest the typographic style for the class, semantically, items with the same class are treated "the same" within an expression, which might or might not involve displaying them with the named typography. ...
...mall, normal and big. these will be removed in the future. mathvariant this logical class of the identifier, which varies in typography. that is, although the names suggest the typographic style for the class, semantically, items with the same class are treated "the same" within an expression, which might or might not involve displaying them with the named typography. ...
<ms> - MathML
Web › MathML › Element › ms
, normal and big. these will be removed in the future. mathvariant this attribute specifies the logical class of the identifier, which varies in typography. that is, although the names suggest the typographic style for the class, semantically, items with the same class are treated "the same" within an expression, which might or might not involve displaying them with the named typography. ...
...ese will be removed in the future. mathvariant this attribute specifies the logical class of the identifier, which varies in typography. that is, although the names suggest the typographic style for the class, semantically, items with the same class are treated "the same" within an expression, which might or might not involve displaying them with the named typography. ...
<msub> - MathML
Web › MathML › Element › msub
this attribute is deprecated and will be removed in the future. ...
... 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 of 'msub' in that specification. ...
<msubsup> - MathML
this attribute is deprecated and will be removed in the future. ...
...subsup> 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: rendering in your browser: ∫ 0 1 <math displ...
<mtext> - MathML
Web › MathML › Element › mtext
, normal and big. these will be removed in the future. mathvariant this attribute specifies the logical class of the identifier, which varies in typography. that is, although the names suggest the typographic style for the class, semantically, items with the same class are treated "the same" within an expression, which might or might not involve displaying them with the named typography. ...
...ese will be removed in the future. mathvariant this attribute specifies the logical class of the identifier, which varies in typography. that is, although the names suggest the typographic style for the class, semantically, items with the same class are treated "the same" within an expression, which might or might not involve displaying them with the named typography. ...
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
attractive thing for your users to see, and could also result in performance issues due to the repainting required after each image loads, hence adding the attributes being a good idea. let’s move forward a few years to the era of responsive design. to keep images from breaking out of their containers when the container becomes narrower than the image, developers started using css like the following: img { max-width: 100%; height: auto; } this is really useful for responsive layouts, but unfortunately it causes the jank problem to return — the above css overrides the width and height attribute information, meaning that if the image has not loaded for some reason, its height will be set to 0. when the image finally loads, the same jank will occur as the page layout is shifted to ma...
...e were onboard with the idea. due to this work, browsers are working on adding a new mechanism for sizing images before the actual image is loaded. firefox has added an internal aspect-ratio property (in version 69 onwards) that applies to replaced elements, and other related elements that accept width and height attributes. this appears in the browser's internal ua stylesheet, similar to the following: img, input[type="image"], video, embed, iframe, marquee, object, table { aspect-ratio: attr(width) / attr(height); } this actually affects any element that acts as a container for complex or mixed visual media — <embed>, <iframe>, <marquee>, <object>, <table>, and <video>, in addition to actual images (<img> and <input type="image">). when such an element has width and height attribute...
Installing and uninstalling web apps - Progressive web apps (PWAs)
depending on the device and features of the operating system and browser, this can result in what is essentially a fully featured application (for example, using webapk on android) or as a shortcut added to their device’s screen. this guide explains how installation is performed, what it means, and what you need to do as a developer to let your users take advantage of it. ...
... later. safari on ios is a little different. some parts of the pwa ecosystem are supported, while others are not. ios 13 introduced a much more comparable install experience, which is also described here. the install user experience we've written a very simple example web site (see our demo live, and also see the source code) that doesn't do much, but was developed with the necessary code to allow it to be installed, as well as a service worker to enable it to be used offline. the example displays a series of fox pictures.if you have a web application compatible device available, use it to navigate to our demo at https://mdn.github.io/pwa-examples/a2hs/. you'll see fox pictures, but more importantly, some form of user interface will be available to let you install the site as a web app. t...
SVG Event Attributes - SVG: Scalable Vector Graphics
Web › SVG › Attribute › Events
the global event attributes are available on all svg elements. other event attributes are available on a case by case basis for each elements. all event attribute are not animatable. ...
... the global event attributes are available on all svg elements. other event attributes are available on a case by case basis for each elements. all event attribute are not animatable. ...
alignment-baseline - SVG: Scalable Vector Graphics
the alignment-baseline attribute specifies how an object is aligned with respect to its parent. this property specifies which baseline of this element is to be aligned with the corresponding baseline of the parent. for example, this allows alphabetic baselines in roman text to stay aligned across font size changes. it defaults to the baseline with the same name as the computed value of the alignment-baseline property. note: as a presentation attribute alignment-baseline can be used as a css property. ...
...the parent. for example, this allows alphabetic baselines in roman text to stay aligned across font size changes. it defaults to the baseline with the same name as the computed value of the alignment-baseline property. note: as a presentation attribute alignment-baseline can be used as a css property. ...
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. 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 defau...
... <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. <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-...
class - SVG: Scalable Vector Graphics
Web › SVG › Attribute › class
svg 1.1 (2nd edition): the class attribute list-of-ts <list-of-ts> (where t is some type.) a list consists of a separated sequence of values. unless explicitly described differently, lists within svg's xml attributes can be either comma-separated (with optional white space before or after the comma), or white space-separated. white space in lists is defined as one or more of the following consecutive characters: "space" (u+0020), "tab" (u+0009), "line feed" (u+000a), "carriage return" (u+000d), and "form-feed" (u+000c). the following is a template for an ebnf grammar describing the <list-of-ts> syntax: list-of-ts ::= t | t, list-of-ts within the svg dom, values of a <list-of-ts> type are represented by an interface specific for the particular type t. for ex...
... } circle.circleclass { stroke: #006600; fill: #cc0000; } ]]> </style> <rect class="rectclass" x="10" y="10" width="100" height="100"/> <circle class="circleclass" cx="40" cy="50" r="26"/> </svg> </body> </html> elements the following elements can use the class attribute: <a> <altglyph> <circle> <clippath> <defs> <desc> <ellipse> <feblend> <fecolormatrix> <fecomponenttransfer> <fecomposite> <feconvolvematrix> <fediffuselighting> <fedisplacementmap> <feflood> <fegaussianblur> <feimage> <femerge> <femorphology> <feoffset> <fespecularlighting> <fetile> <feturbulence> <filter> <font> <foreignobject>...
clip - SVG: Scalable Vector Graphics
Web › SVG › Attribute › clip
t. this attribute has the same parameter values as defined for the css clip property. unitless values, which indicate current user coordinates, are permitted on the coordinate values on the rect(). the value of auto defines a clipping path along the bounds of the viewport created by the given element. ...
...8, 2)"> <circle cx="5" cy="5" r="4" stroke="green" /> </svg> </svg> usage notes warning: this property is deprecated. use clip-path instead. value auto | rect() default value auto animatable yes the value auto defines a clipping path along the bounds of the viewport created by the given element.the value rect() defines a clipping rectangle following the following syntax: rect(<top>, <right>, <bottom>, <left>). the <top> and <bottom> values specify offsets from the top border edge of the element viewport, while <right> and <left> specify offsets from the left border edge of the element viewport. specifications specification status comment css masking module level 1the definition of 'clip' in that specification...
dominant-baseline - SVG: Scalable Vector Graphics
is constructed using the mathematical baseline-table in the font, and the baseline-table font-size is changed to the value of the font-size attribute on this element. central the baseline-identifier for the dominant-baseline is set to be central. the derived baseline-table is constructed from the defined baselines in a baseline-table in the font. that font baseline-table is chosen using the following priority order of baseline-table names: ideographic, alphabetic, hanging, mathematical. the baseline-table font-size is changed to the value of the font-size attribute on this element. middle the baseline-identifier for the dominant-baseline is set to be middle. the derived baseline-table is constructed from the defined baselines in a baseline-table in the font. that font baseline-table is c...
...of baseline-table names: ideographic, alphabetic, hanging, mathematical. the baseline-table font-size is changed to the value of the font-size attribute on this element. middle the baseline-identifier for the dominant-baseline is set to be middle. the derived baseline-table is constructed from the defined baselines in a baseline-table in the font. that font baseline-table is chosen using the following priority order of baseline-table names: alphabetic, ideographic, hanging, mathematical. the baseline-table font-size is changed to the value of the font-size attribute on this element. text-after-edge the baseline-identifier for the dominant-baseline is set to be text-after-edge. the derived baseline-table is constructed from the defined baselines in a baseline-table in the font. the choice ...
enable-background - SVG: Scalable Vector Graphics
the enable-background attribute specifies how the accumulation of the background image is managed. note: as a presentation attribute, enable-background can be used as a css property. ...
...background image canvas is established and that in effect all children of the current container element shall be rendered into the new background image canvas in addition to being rendered onto the target device. the optional <x>, <y>, <width>, and <height> parameters are <number> values that indicate the subregion of the container elementʼs user space where access to the background image is allowed to happen. those values act as a clipping rectangle on the background image canvas. negative values for <width> or <height> are forbidden. if one, two, or three values are specified or if neither <width> nor <height> are specified, the backgroundimage and backgroundalpha of a filter primitive are processed as if background image processing were not enabled. specifications specif...
fill-opacity - SVG: Scalable Vector Graphics
the fill-opacity attribute is a presentation attribute defining the opacity of the paint server (color, gradient, pattern, etc) applied to a shape. note: as a presentation attribute fill-opacity can be used as a css property. ...
... 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 a...
lang - SVG: Scalable Vector Graphics
Web › SVG › Attribute › lang
erent meaning and only applying to <glyph> elements. that attribute specified a list of languages in bcp 47 format. the glyph was meant to be used if the xml:lang attribute exactly matched one of the languages given in the value of this parameter, or if the xml:lang attribute exactly equaled a prefix of one of the languages given in the value of this parameter such that the first tag character following the prefix was "-". all elements are using this attribute. <svg viewbox="0 0 200 100" xmlns="http://www.w3.org/2000/svg"> <text lang="en-us">this is some english text</text> </svg> usage notes value <language-tag> default value none animatable no <language-tag> this value specifies the language used for the element. the syntax of this val...
..." xmlns="http://www.w3.org/2000/svg"> <text lang="en-us">this is some english text</text> </svg> usage notes value <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...
pointer-events - SVG: Scalable Vector Graphics
the pointer-events attribute is a presentation attribute that allows defining whether or when an element may be the target of a mouse event. note: as a presentation attribute pointer-events can be used as a css property. html,body,svg { height:100% } <svg viewbox="0 0 20 10" xmlns="http://www.w3.org/2000/svg"> <!-- the circle will always intercept the mouse event. to change the color of the rect underneath you have to click outside the circle --> <rect x="0" y="0" height="10" width="10" fill="black" /> <circle cx="5" cy="5" r="4" fill="white" pointer-events="visiblepoint" /> <!-- the circle below will never catch a mouse event. the rect underneath will change color whether you are clicking on the circle or the rect itself --> <rect x="10" y="0" heig...
...between #000000 and #ffffff const color = math.round(math.random() * 0xffffff) // let's format the color to fit css requirements const fill = '#' + color.tostring(16).padstart(6,'0') // let's apply our color in the // element we actually clicked on e.target.style.fill = fill }) as a presentation attribute, it can be applied to any element but it is mostly relevant only on the following twenty-three elements: <a>, <circle>, <clippath>, <defs>, <ellipse>, <foreignobject>, <g>, <image>, <line>, <marker>, <mask>, <path>, <pattern>, <polygon>, <polyline>, <rect>, <svg>, <switch>, <symbol>, <text>, <textpath>, <tspan>, <use> usage notes value bounding-box | visiblepainted | visiblefill | visiblestroke | visible | painted | fill | stroke | all | none default ...
r - SVG: Scalable Vector Graphics
Web › SVG › Attribute › r
e cx="150" cy="50" r="25"/> <circle cx="250" cy="50" r="50"/> <rect x="20" y="120" width="60" height="60" fill="url(#mygradient000)" /> <rect x="120" y="120" width="60" height="60" fill="url(#mygradient050)" /> <rect x="220" y="120" width="60" height="60" fill="url(#mygradient100)" /> </svg> circle for <circle>, r defines the radius of the circle and therefor its size. with a value lower or equal to zero the circle won't be drawn at all. value <length> | <percentage> default value 0 animatable yes note: starting with svg2, r is a geometry property meaning this attribute can also be used as a css property for circles. radialgradient for <radialgradient>, r defines the radius of the end circle for the radial gradient. the gradient wi...
... default value 0 animatable yes note: starting with svg2, r is a geometry property meaning this attribute can also be used as a css property for circles. radialgradient for <radialgradient>, r defines the radius of the end circle for the radial gradient. the gradient will be drawn such that the 100% gradient stop is mapped to the perimeter of this end circle. a value of lower or equal to zero will cause the area to be painted as a single color using the color and opacity of the last gradient <stop>. value <length> | <percentage> default value 50% animatable yes specifications specification status comment scalable vector graphics (svg) 2the definition of 'r' in that specification. candidate r...
stop-opacity - SVG: Scalable Vector Graphics
gradient calculation is the product of the value of stop-opacity and the opacity of the value of the stop-color attribute. for stop-color values that donʼt include explicit opacity information, the opacity is treated as 1. note: as a presentation attribute, stop-opacity 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 element: <stop> usage notes value <opacity-value> default value 1 animatable yes <opacity-value> this value is either a <number> between 0 and 1 or a <percentage> value specifying the opacity of the color gradient stop. specifications specification status comment scalable vector graphics (svg) 2the definition of 'st...
...e yes <opacity-value> this value is either a <number> between 0 and 1 or a <percentage> value specifying the opacity of the color gradient stop. specifications specification status comment scalable vector graphics (svg) 2the definition of 'stop-opacity' in that specification. candidate recommendation refers to the definition in css colors 3, but allows percentage values. scalable vector graphics (svg) 1.1 (second edition)the definition of 'stop-opacity' in that specification. recommendation initial definition ...
stroke-dashoffset - SVG: Scalable Vector Graphics
the stroke-dashoffset attribute is a presentation attribute defining an offset on the rendering of the associated dash array. note: as a presentation attribute stroke-dashoffset can be used as a css property. ...
...> <line x1="0" y1="7" x2="30" y2="7" stroke="black" stroke-dasharray="3 1" stroke-dashoffset="-3" /> <!-- the start of the dash array computation is pulled by 1 user units which ends up in the same rendering as the previous example --> <line x1="0" y1="9" x2="30" y2="9" stroke="black" stroke-dasharray="3 1" stroke-dashoffset="1" /> <!-- the following red lines highlight the offset of the dash array for each line --> <path d="m0,5 h-3 m0,7 h3 m0,9 h-1" stroke="rgba(255,0,0,.5)" /> </svg> usage notes value <percentage> | <length> default value 0 animatable yes the offset is usually expressed in user units resolved against the pathlength but if a <percentage> is used, the value is resolve...
stroke-miterlimit - SVG: Scalable Vector Graphics
iterlimit attribute is a presentation attribute defining a limit on the ratio of the miter length to the stroke-width used to draw a miter join. when the limit is exceeded, the join is converted from a miter to a bevel. note: as a presentation attribute stroke-miterlimit can be used as a css property. ...
... m2, 0 l0.75,-3 l0.75,3 m2, 0 l0.5 ,-3 l0.5 ,3" /> <!-- impact of a large miter limit (8) --> <path stroke="black" fill="none" stroke-linejoin="miter" stroke-miterlimit="8" id="p3" d="m1,29 l7 ,-3 l7 ,3 m2, 0 l3.5 ,-3 l3.5 ,3 m2, 0 l2 ,-3 l2 ,3 m2, 0 l0.75,-3 l0.75,3 m2, 0 l0.5 ,-3 l0.5 ,3" /> <!-- the following pink lines highlight the position of the path for each stroke --> <path stroke="pink" fill="none" stroke-width="0.05" d="m1, 9 l7,-3 l7,3 m2,0 l3.5,-3 l3.5,3 m2,0 l2,-3 l2,3 m2,0 l0.75,-3 l0.75,3 m2,0 l0.5,-3 l0.5,3 m1,19 l7,-3 l7,3 m2,0 l3.5,-3 l3.5,3 m2,0 l2,-3 l2,3 m2,0 l0.75,-3 l0.75,3 m2,0 l0.5,-3 l0.5,3 m1,29 l7,-3 l7,3 m2,0 l3.5,-3 l3.5,3 m2,0 l2,-3 l2,3 ...
stroke-opacity - SVG: Scalable Vector Graphics
the stroke-opacity attribute is a presentation attribute defining the opacity of the paint server (color, gradient, pattern, etc) applied to the stroke of a shape. note: as a presentation attribute stroke-opacity can be used as a css property. ...
... it's important to know that the stroke partially covers the fill of a shape, so a stroke with an opacity different than 1 will partially show the fill underneath. to avoid this effect, it is possible to apply a global opacity with the opacity attribute or to put the stroke behind the fill with the paint-order...
systemLanguage - SVG: Scalable Vector Graphics
eral alternative language objects are enclosed in a <switch> and none of them matches, this may lead to situations where no content is displayed. it is thus recommended to include a "catch-all" choice at the end of such a <switch> which is acceptable in all cases. the attribute evaluates to "true" if one of the language tags indicated by user preferences is a case-insensitive match or prefix (followed by a "-") of one of the language tags given in the value of this parameter. otherwise it evaluates to "false". note: the prefix matching rule does not imply that if a user understands a language with a certain tag, that the user will also understand all languages with the tag as prefix. if the attribute is not present, then it implicitly evaluates to "true". if a null string or empty string v...
.... otherwise it evaluates to "false". note: the prefix matching rule does not imply that if a user understands a language with a certain tag, that the user will also understand all languages with the tag as prefix. if the attribute is not present, then it implicitly evaluates to "true". if a null string or empty string value is given, the attribute evaluates to "false". the prefix rule simply allows the use of prefix tags if this is the case. multiple languages may be listed for content that is intended for multiple audiences. for example, content that is presented simultaneously in the original maori and english versions, would call for: <text systemlanguage="mi, en"><!-- content goes here --></text> however, just because multiple languages are present within the object on which the sys...
type - SVG: Scalable Vector Graphics
Web › SVG › Attribute › type
tribute and it has different meaning based on the context in which it's used. for the <animatetransform> element, it defines the type of transformation, whose values change over time. for the <fecolormatrix> element, it indicates the type of matrix operation. the keyword matrix indicates that a full 5x4 matrix of values will be provided. the other keywords represent convenience shortcuts to allow commonly used color operations to be performed without specifying a complete matrix. for the <fefuncr>, <fefuncg>, <fefuncb>, and <fefunca> elements, it indicates the type of component transfer function. for the <feturbulence> element, it indicates whether the filter primitive should perform a noise or turbulence function. for the <style> and <script> elements, it defines the content type of t...
...ories none value fractalnoise | turbulence animatable yes normative document svg 1.1 (2nd edition) for the <style> and <script> elements categories none value <content-type> animatable no normative document svg 1.1 (2nd edition) : script svg 1.1 (2nd edition) : style example elements the following elements can use the values attribute <animatetransform> <fecolormatrix> <fefunca> <fefuncb> <fefuncg> <fefuncr> <feturbulence> <script> <style> ...
visibility - SVG: Scalable Vector Graphics
layout calculations. depending on the value of attribute pointer-events, graphics elements which have their visibility attribute set to hidden still might receive events. note: as a presentation attribute, visibility can be used as a css property. see the css visibility property for more information. ...
.... hidden this value indicates that the element will not be painted. though it is still part of the rendering tree, i.e. it may receive pointer events depending on the pointer-events attribute, may receive focus depending on the tabindex attribute, contributes to bounding box calculations and clipping paths, and does affect text layout. collapse this value is equal to hidden. example the following example toggles the css visibility of the svg image path. html <button id="nav-toggle-button" > <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewbox="0 0 24 24" class="button-icon"> <path d="m16.59 8.59l12 13.17 7.41 8.59 6 10l6 6 6-6z" /> <path d="m12 8l-6 6 1.41 1.41l12 10.83l4.59 4.58l18 14z" class="invisible" /> <path d="m0 0h24v24h0z" fill="none" /> </s...
widths - SVG: Scalable Vector Graphics
Web › SVG › Attribute › widths
if this attribute is used, the units-per-em attribute must also be used. if the range is omitted, a range of u+0-7fffffff is assumed which covers all characters and their glyphs. if not enough glyph widths are given, the last in the list is replicated to cover that range. if too many widths are provided, the extras are ignored. ...
... if this attribute is used, the units-per-em attribute must also be used. if the range is omitted, a range of u+0-7fffffff is assumed which covers all characters and their glyphs. if not enough glyph widths are given, the last in the list is replicated to cover that range. if too many widths are provided, the extras are ignored. ...
writing-mode - SVG: Scalable Vector Graphics
. (note that the inline-progression-direction can change within a <text> element due to the unicode bidirectional algorithm and properties direction and unicode-bidi.) note: as a presentation attribute, writing-mode can be used as a css property. see the css writing-mode 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 <tspan> usage notes default value horizontal-tb value horizontal-tb | vertical-rl | vertical-lr animatable yes horizontal-tb this value defines a top-to-bottom block flow direction. both the writing mode and the typographic mode are horizontal. vertical-rl this value defines a right-to-...
...ments: <altglyph>, <text>, <textpath>, <tref>, and <tspan> usage notes default value horizontal-tb value horizontal-tb | vertical-rl | vertical-lr animatable yes horizontal-tb this value defines a top-to-bottom block flow direction. both the writing mode and the typographic mode are horizontal. vertical-rl this value defines a right-to-left block flow direction. both the writing mode and the typographic mode are vertical. vertical-lr this value defines a left-to-right block flow direction. both the writing mode and the typographic mode are vertical. specifications specification status comment css writing modes module level 3the definition of 'writing-mode' in that specification. proposed recommendation de...
x-height - SVG: Scalable Vector Graphics
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'x-height' in that specification. ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'x-height' in that specification. ...
xml:lang - SVG: Scalable Vector Graphics
there is also a lang attribute (without namespace). if both of them are defined, the one with namespace is used and the one without is ignored. all elements are using this attribute. ...
...lns="http://www.w3.org/2000/svg"> <text xml:lang="en-us">this is some english text</text> </svg> usage notes value <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 attri...
<animateTransform> - SVG: Scalable Vector Graphics
the animatetransform element animates a transformation attribute on its target element, thereby allowing animations to control translation, scaling, rotation, and/or skewing. ...
... the animatetransform element animates a transformation attribute on its target element, thereby allowing animations to control translation, scaling, rotation, and/or skewing. ...
<discard> - SVG: Scalable Vector Graphics
Web › SVG › Element › discard
the <discard> svg element allows authors to specify the time at which particular elements are to be discarded, thereby reducing the resources required by an svg user agent. this is particularly useful to help svg viewers conserve memory while displaying long-running documents. the <discard> element may occur wherever the <animate> element may. ...
...lows authors to specify the time at which particular elements are to be discarded, thereby reducing the resources required by an svg user agent. this is particularly useful to help svg viewers conserve memory while displaying long-running documents. the <discard> element may occur wherever the <animate> element may. ...
<ellipse> - SVG: Scalable Vector Graphics
Web › SVG › Element › ellipse
fset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
... candidate recommendation added auto value for rx and ry scalable vector graphics (svg) 1.1 (second edition)the definition of '<ellipse>' in that specification. ...
<feColorMatrix> - SVG: Scalable Vector Graphics
r value [r,g,b,a] is matrix multiplied by a 5 by 5 color matrix to create new color [r',g',b',a']. the prime symbol ' is used in mathematics indicate the result of a transformation. | r' | | r1 r2 r3 r4 r5 | | r | | g' | | g1 g2 g3 g4 g5 | | g | | b' | = | b1 b2 b3 b4 b5 | * | b | | a' | | a1 a2 a3 a4 a5 | | a | | 1 | | 0 0 0 0 1 | | 1 | in simplified terms, below is how each color channel in the new pixel is calculated. the last row is ignored because its values are constant. r' = r1*r + r2*g + r3*b + r4*a + r5 g' = g1*r + g2*g + g3*b + g4*a + g5 b' = b1*r + b2*g + b3*b + b4*a + b5 a' = a1*r + a2*g + a3*b + a4*a + a5 take the amount of red in the new pixel, or r': it is the sum of r1 times the old pixel's red r, r2 times the old pixel's green g, r3...
...dness on every pixel of the new image by x. an identity matrix looks like this: r g b a w r' | 1 0 0 0 0 | g' | 0 1 0 0 0 | b' | 0 0 1 0 0 | a' | 0 0 0 1 0 | in it, every new value is exactly 1 times its old value, with nothing else added. it is recommended to start manipulating the matrix from here. usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in type values dom interface this element implements the svgfecolormatrixelement interface. example svg <svg width="100%" height="100%" viewbox="0 0 150 500" preserveaspectratio="xmidymid meet" xml...
<feComponentTransfer> - SVG: Scalable Vector Graphics
th <fecomponenttransfer> svg filter primitive performs color-component-wise remapping of data for each pixel. it allows operations like brightness adjustment, contrast adjustment, color balance or thresholding. the calculations are performed on non-premultiplied color values. the colors are modified by changing each channel (r, g, b, and a) to the result of what the children <fefuncr>, <fefuncb>, <fefuncg>, and <fefunca> return. ...
...erations like brightness adjustment, contrast adjustment, color balance or thresholding. the calculations are performed on non-premultiplied color values. the colors are modified by changing each channel (r, g, b, and a) to the result of what the children <fefuncr>, <fefuncb>, <fefuncg>, and <fefunca> return. usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<fefunca>, <fefuncr>, <fefuncb>, <fefuncg> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in dom interface this element implements the svgfecomponenttransferelement interface. example svg <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 600 300"> <defs> <linear...
<feComposite> - SVG: Scalable Vector Graphics
uff compositing operations: over, in, atop, out, xor, and lighter. additionally, a component-wise arithmetic operation (with the result clamped between [0..1]) can be applied. the arithmetic operation is useful for combining the output from the <fediffuselighting> and <fespecularlighting> filters with texture data. ...
... chosen, each result pixel is computed using the following formula: result = k1*i1*i2 + k2*i1 + k3*i2 + k4 where: i1 and i2 indicate the corresponding pixel channel values of the input image, which map to in and in2 respectively k1, k2, k3 and k4 indicate the values of the attributes with the same name usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes » presentation attributes » filter primitive attributes » class style specific attributes in in2 operator k1 k2 k3 k4 dom interface this element implements the svgfecompositeelement interface. example svg <svg width="330" height="195" viewbox="0 0 1100 650" version="1.1" xmlns...
<feConvolveMatrix> - SVG: Scalable Vector Graphics
. note in the above formulas that the values in the kernel matrix are applied such that the kernel matrix is rotated 180 degrees relative to the source and destination images in order to match convolution theory as described in many computer graphics textbooks. to illustrate, suppose you have a 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). assuming the simplest case (where the input image's pixel grid aligns perfectly with the kernel's pixel grid)...
... example svg <svg width="200...
<feMerge> - SVG: Scalable Vector Graphics
Web › SVG › Element › feMerge
the <femerge> svg element allows filter effects to be applied concurrently instead of sequentially. this is achieved by other filters storing their output via the result attribute and then accessing it in a <femergenode> child. ...
... the <femerge> svg element allows filter effects to be applied concurrently instead of sequentially. this is achieved by other filters storing their output via the result attribute and then accessing it in a <femergenode> child. ...
<foreignObject> - SVG: Scalable Vector Graphics
the <foreignobject> svg element includes elements from a different xml namespace. in the context of a browser, it is most likely (x)html. ...
...fset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
<g> - SVG: Scalable Vector Graphics
Web › SVG › Element › g
fset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
...table, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriescontainer element, structural elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> specifications specification status comment scalable vector graphi...
<image> - SVG: Scalable Vector Graphics
Web › SVG › Element › image
try <use> with an external url. to include svg files and run scripts inside them, try <object> inside of <foreignobject>. note: the html spec defines <image> as a synonym for <img> while parsing html. this specific element and its behavior only apply inside svg documents or inline svg. usage context categoriesgraphics element, graphics referencing elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elements attributes global attributes conditional processing attributes core attributes graphical event attributes presentation attributes xlink attributes class style externalresourcesrequired transform specific attributes x: positions the image horizontally from the origin. y: positions the image vertically from the orig...
... recommendation initial definition ...
<line> - SVG: Scalable Vector Graphics
Web › SVG › Element › line
fset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
... candidate recommendation changed the x1, y1, x2 and y2 attributes to take <length>s, <percentage>s and <number>s scalable vector graphics (svg) 1.1 (second edition...
<marker> - SVG: Scalable Vector Graphics
Web › SVG › Element › marker
fset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
...ine, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriescontainer elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> specifications specification status comment svg markersthe definit...
<mpath> - SVG: Scalable Vector Graphics
Web › SVG › Element › mpath
the <mpath> sub-element for the <animatemotion> element provides the ability to reference an external <path> element as the definition of a motion path. usage context categoriesanimation elementpermitted contentany number of the following elements, in any order:descriptive elements attributes global attributes core attributes » xlink attributes » externalresourcesrequired specific attributes xlink:href dom interface this element implements the svgmpathelement interface. example svg <svg width="100%" height="100%" viewbox="0 0 500 300" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" > <rect x="1" y="1" width="498" height="298" fill="none" stroke="blue" stroke-width="2" /> <!-- draw the outline of the motion path in b...
...="17.64" fill="blue" /> <circle cx="250" cy="100" r="17.64" fill="blue" /> <circle cx="400" cy="250" r="17.64" fill="blue" /> <!-- here is a triangle which will be moved about the motion path. it is defined with an upright orientation with the base of the triangle centered horizontally just above the origin. --> <path d="m-25,-12.5 l25,-12.5 l 0,-87.5 z" fill="yellow" stroke="red" stroke-width="7.06" > <!-- define the motion path animation --> <animatemotion dur="6s" repeatcount="indefinite" rotate="auto" > <mpath xlink:href="#path1"/> </animatemotion> </path> </svg> result specifications specification status comment svg animations level 2the definition of '<mpath>' in that specification. editor's dra...
<path> - SVG: Scalable Vector Graphics
Web › SVG › Element › path
fset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
... working draft scalable vector graphics (svg) 2the definition of '<path>' in that specification. candidate recommendation scalable vector graphics (svg) 1.1 (second edi...
<polygon> - SVG: Scalable Vector Graphics
Web › SVG › Element › polygon
fset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
... candidate recommendation no change scalable vector graphics (svg) 1.1 (second edition)the definition of '<polygon>' in that specification. recommendation ...
<polyline> - SVG: Scalable Vector Graphics
Web › SVG › Element › polyline
fset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
... candidate recommendation scalable vector graphics (svg) 1.1 (second edition)the definition of '<polyline>' in that specification. recommendation initia...
<rect> - SVG: Scalable Vector Graphics
Web › SVG › Element › rect
fset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
... candidate recommendation scalable vector graphics (svg) 1.1 (second edition)the definition of '<rect>' in that specification. recommendation initial defini...
<script> - SVG: Scalable Vector Graphics
Web › SVG › Element › script
the svg script element allows to add scripts to an svg document. ...
... the svg script element allows to add scripts to an svg document. ...
<set> - SVG: Scalable Vector Graphics
Web › SVG › Element › set
nt provides a simple means of just setting the value of an attribute for a specified duration. it supports all attribute types, including those that cannot reasonably be interpolated, such as string and boolean values. for attributes that can be reasonably be interpolated, the <animate> is usualy prefered. note: the <set> element is non-additive. the additive and accumulate attributes are not allowed, and will be ignored if specified. html,body,svg { height:100%; margin:0; padding:0; } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <style> rect { cursor: pointer } .round { rx: 5px; fill: green; } </style> <rect id="me" width="10" height="10"> <set attributename="class" to="round" begin="me.click" dur="2s" /> </rect> </svg> attributes to this a...
... editor's draft scalable vector graphics (svg) 1.1 (second edition)the definition of '<set>' in that specification. recommendation initial definition ...
<svg> - SVG: Scalable Vector Graphics
Web › SVG › Element › svg
fset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
...table, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriescontainer element, structural elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> specifications specification status comment scalable vector graphi...
<text> - SVG: Scalable Vector Graphics
Web › SVG › Element › text
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-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
... candidate recommendation scalable vector graphics (svg) 1.1 (second edition)the definition of '<text>' in that specification. recommend...
<textPath> - SVG: Scalable Vector Graphics
Web › SVG › Element › textPath
fset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, 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, ari...
... candidate recommendation scalable vector graphics (svg) 1.1 (second edition)the definition of '<textpath>' in...
Specification Deviations - SVG: Scalable Vector Graphics
there are a few places where we have consciously decided to make gecko deviate from or extend the svg specification. this page lists those deviations/extensions and our reasoning for them. the 'class' and 'style' attributes unlike html and mathml, the svg specification does not specify the 'style' and 'class' attributes on all svg elements. nevertheless, to allow mozilla to more cleanly share internal 'class' and 'style' related code, we will implement these attributes on all svg elements as of firefox 3. in general this change will not be visible to svg authors (the elements for which the svg specification does not define the 'class' and 'style' attribute are elements that are not displayed directly). however, there are two exceptions. extending the 'class' attribute to apply to a...
...d 'style' related code, we will implement these attributes on all svg elements as of firefox 3. in general this change will not be visible to svg authors (the elements for which the svg specification does not define the 'class' and 'style' attribute are elements that are not displayed directly). however, there are two exceptions. extending the 'class' attribute to apply to all svg elements will allow svg authors to use the selectors api to select any svg element based on class. this seems like a good thing. requiring svg authors to know which elements can and cannot take a 'class' attribute would just put an extra burden on them. extending the 'style' attribute to apply to all svg elements should only really be visible to svg authors if they call viewcss.getcomputedstyle on the element or one...
Fills and Strokes - SVG: Scalable Vector Graphics
), 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 stroke-opacity attributes. note: in firefox 3+, rgba values are also allowed, and will give the same effect. but for compatibility with other viewers, it's often best to specify the fill/stroke opacity separately. if you specify both an rgba value and a fill/stroke opacity value, both will be applied. stroke in addition to its color properties, there are a few other attributes available to control the way a stroke is drawn on a line. <?xml version="1.0" standalone=...
...ch 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 addition to the gradient and pattern versions of those shown below. attributes like width, height, or <path> commands cannot be set through css. it's easiest just to test and find out what is available and what isn't. note: the svg specification decides strictly between attributes that are properties and other attributes. the former can be modified with css, the latter not. css can be inserted inline with the element via the style attribute: <rect x="10" hei...
Gradients in SVG - SVG: Scalable Vector Graphics
s as you need, but the offsets should always increase from 0% (or 0 if you want to drop the % sign) to 100% (or 1). duplicate values will use the stop that is assigned furthest down the xml tree. also, like with fill and stroke, you can specify a stop-opacity attribute to set the opacity at that position (again, in ff3 you can also use rgba values to do this). <stop offset="100%" stop-color="yellow" stop-opacity="0.5"/> to use a gradient, we have to reference it from an object's fill or stroke attributes. this is done the same way you reference elements in css, using a url. in this case, the url is just a reference to our gradient, which i've given the creative id, "gradient". to attach it, set the fill to url(#gradient), and voila! our object is now multicolored. you can do the same with...
...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 the first point described where the edges of the gradient were, the focal point describes where its middle is. this is easier to see with an example. center and focal point <?xml version="1.0" standalone="no"?> <sv...
Introduction - SVG: Scalable Vector Graphics
ssary, by modifying already existing raster images, or by a combination of both. the image and its components can also be transformed, composited together, or filtered to change their appearance completely. svg came about in 1999 after several competing formats had been submitted to the w3c and failed to be fully ratified. svg is supported by all major browsers. a downside is loading svg can be slow. svg does offer benefits, some of which include having a dom interface available for it, and not requiring third-party extensions. whether or not to use it often depends on your specific use case. basic ingredients html provides elements for defining headers, paragraphs, tables, and so on. in much the same way svg provides elements for circles, rectangles, and simple and complex curves. a s...
... flavors of svg since becoming a recommendation in 2003, the most recent "full" svg version is 1.1. it builds on top of svg 1.0, but adds more modularization to ease implementation. the second edition of svg 1.1 became a recommendation in 2011. "full" svg 1.2 was meant to be the next major release of svg. it was dropped for the upcoming svg 2.0, which is under heavy development right now and follows a similar approach to css 3 in that it splits components into several loosely coupled specifications. apart from the full svg recommendations, the working group at the w3c introduced svg tiny and svg basic in 2003. these two profiles are aimed mainly at mobile devices. the first, svg tiny, should yield graphics primitives for small devices with low capabilities. svg basic offers many features o...
Patterns - SVG: Scalable Vector Graphics
Web › SVG › Tutorial › Patterns
tterns is defining a unit system and their size. in the example above, we've defined a width and height attribute on the pattern element to describe how far the pattern should go before it begins repeating itself again. there are also x and y attributes available if you want to offset the start point of this rectangle somewhere within your drawing. the reason they've been used here is described below. as with the gradientunits attribute used above, patterns also have an attribute, patternunits, which specifies the units that these attributes will take. it defaults to "objectboundingbox" as it did above, so a value of 1 is scaled to the width/height of the object you're applying the pattern to. since, in this case, we wanted the pattern to repeat 4 times horizontally and vertically, the heigh...
... « previousnext » ...
Referer header: privacy and security concerns - Web security
there are privacy and security risks associated with the referer http header. this article describes them, and offers advice on mitigating those risks. the referrer problem the referer (sic) header contains the address of the previous web page from which a link to the currently requested page was followed, which has lots of fairly innocent uses including analytics, logging, or optimized caching. ...
... by the same logic, an image hosted on a third party side but embedded in your page could result in sensitive information being leaked to the third party. ...
Secure contexts - Web security
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. a particular document is considered to be in a secure context when it is ...
...n 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 to have been delivered securely. resources that are not local, to be considered secure, must meet the following criteria: must be served over https:// or wss:// urls the security properties of the network channel used to deliver the resource must not be considered deprecated feature detection pages can use feature detection to check whether they are in a secure context or not by using the issecurecontext boolean, which is exposed on the global scope. if (window.issecurecontext) { // page is a ...
Securing your site - Web security
there are a number of things you can do to help secure your site. this article offers an assortment of suggestions, as well as links to other articles providing more useful information. note: this article is a work in progress, and is neither complete nor does following its suggestions guarantee your site will be fully secure. user 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 us...
...facement or distribution of malware. code is executed by the victims and lets the attackers bypass access controls and impersonate users. according to the open web application security project, xss was the seventh most common web app vulnerability in 2017. the x-frame-options response header the x-frame-options: http response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>. sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites. access control by configuring a website it is the best way to secure your site. you can ignore specific ips, restrict access to certain areas of website, protect different files, protect against image hotlinking, and a lot more. for example, .htac...
Types of attacks - Web security
er than what the user thinks it is. this can be used, for example, to steal login credentials or to get the user's unwitting permission to install a piece of malware. (click-jacking is sometimes called "user interface redressing", though this is a misuse of the term "redress".) cross-site request forgery (csrf) cross-site scripting (xss) cross-site scripting (xss) is a security exploit which allows an attacker to inject into a website malicious client-side code. this code is executed by the victims and lets the attackers bypass access controls and impersonate users. according to the open web application security project, xss was the seventh most common web app vulnerability in 2017. these attacks succeed if the web app does not employ enough validation or encoding. the user's browser cann...
...s to example.com or other sub-domains by setting the domain attribute: set-cookie: csrf=e8b667; secure; domain=example.com if a vulnerable application is available on a sub-domain, this mechanism can be abused in a session fixation attack. when the user visits a page on the parent domain (or another subdomain), the application may trust the existing value sent in the user's cookie. this could allow an attacker to bypass csrf protection or hijack a session after the user logs in. alternatively, if the parent domain does not use http strict-transport-security with includesubdomains set, a user subject to an active mitm (perhaps connected to an open wifi network) could be served a response with a set-cookie header from a non-existent sub-domain. the end result would be much the same, with the...
Tutorials
he links on this page lead to a variety of tutorials and training materials. whether you are just starting out, learning the basics, or are an old hand at web development, you can find helpful resources here for best practices. these resources are created by forward-thinking companies and web developers who have embraced open standards and best practices for web development and that provide or allow translations, through an open content license such as creative commons. for complete beginners to the web getting started with the web getting started with the web is a concise series introducing you to the practicalities of web development. you'll set up the tools you need to construct a simple webpage and publish your own simple code. html tutorials introductory level introduction...
...ed more practice. advanced level using css transforms apply rotation, skewing, scaling, and translation using css. css transitions css transitions, part of the draft css3 specification, provide a way to animate changes to css properties, instead of having the changes take effect instantly. quick guide to implement web fonts (with @font-face) the @font-face feature from css3 allows you to use custom typefaces on the web in an accessible, manipulatable, and scalable way. starting to write css an introduction to tools and methodologies to write more succinct, maintainable, and scalable css. canvas tutorial learn how to draw graphics using scripting using the canvas element. html5 doctor articles about using html5 right now. javascript tutorials introductory ...
Axes - XPath
Web › XPath › Axes
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes there are thirteen different 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, in...
...attribute and namespace nodes are not included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents. descendant-or-self indicates the context node and all of its descendants. attribute and namespace nodes are not included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents. following indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes. following-sibling indicates all the nodes that have the same parent as the context node and appear after the context node in the source document. namespace (not supported) indicates all the nodes that are in scope for the context node. in this case, the context node must be a...
<xsl:sort> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › sort
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:sort> element defines a sort key for nodes selected by <xsl:apply-templates> or <xsl:for-each> and determines the order in which they are processed. ...
... | "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. order specifies whether the nodes should be processed in "ascending" or "descending" order. the default is "ascending". case-order indicates whether upper- or lowercase letters are to be ordered first. the allowable values are "upper-first" and "lower-first". lang specifies which language is to be used by the sort. data-type defines whether items are to be ordered alphabetically or numerically. the allowable values are "text" and "number" with "text" being the default. type subinstruction, always appears as a child of <xsl:for-each>, where it ...
XSLT elements reference - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element
f xslt elements can also include what is known as an attribute value template. an attribute value template is simply a string that includes an embedded xpath expression which is used to specify the value of an attribute. at run-time the expression is evaluated and the result of the evaluation is substituted for the xpath expression. ...
...e value of an attribute. at run-time the expression is evaluated and the result of the evaluation is substituted for the xpath expression. for example, assume that a variable "image-dir" is defined as follows: <xsl:variable name="image-dir">/images</xsl:variable> the expression to be evaluated is placed inside curly brackets: <img src="{$image-dir}/mygraphic.jpg"/> this would result in the following: <img src="/images/mygraphic.jpg"/> the element annotations that follow include a description, a syntax listing, a list of required and optional attributes, a description of type and position, its source in the w3c recommendation and an explanation of the degree of present gecko support. use the {{listsubpages}} macro once the bcd for <xsl:fallback>, <xsl:import>, <xsl:namespace-alias>, <x...
The Netscape XSLT/XPath Reference - XSLT: Extensible Stylesheet Language Transformations
development of the xslt processor is ongoing, and this document will be updated as functionality is expanded. ...
...ing-instruction xsl:sort (supported) xsl:strip-space (supported) xsl:stylesheet (partially supported) xsl:template (supported) xsl:text (partially supported) xsl:transform (supported) xsl:value-of (partially supported) xsl:variable (supported) xsl:when (supported) xsl:with-param (supported) axes ancestor ancestor-or-self attribute child descendant descendant-or-self following following-sibling namespace (not supported) parent preceding preceding-sibling self functions boolean() (supported) ceiling() (supported) concat() (supported) contains() (supported) count() (supported) current() (supported) document() (supported) element-available() (supported) false() (supported) floor() (supported) format-number() (supported) function-availa...
Transforming XML with XSLT - XSLT: Extensible Stylesheet Language Transformations
...
...processing-instruction xsl:sort (supported) xsl:strip-space (supported) xsl:stylesheet (partially supported) xsl:template (supported) xsl:text (partially supported) xsl:transform (supported) xsl:value-of (partially supported) xsl:variable (supported) xsl:when (supported) xsl:with-param (supported) axes ancestor ancestor-or-self attribute child descendant descendant-or-self following following-sibling namespace (not supported) parent preceding preceding-sibling self functions boolean() (supported) ceiling() (supported) concat() (supported) contains() (supported) count() (supported) current() (supported) document() (supported) element-available() (supported) false() (supported) floor() (supported) format-number() (supported) function-available() (suppo...
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
t 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. transforming html unfortunately it is currently not supported to transform html nodes using xslt. some things work if you use lower case node-names in patterns and expressions, and treat the nodes as if they are in the null namespace, however this is not very well tested so it might not work in all situations. it is also possible that this will change in a future release. transforming xhtml should work as expected though. setting parameters you can control parameters for the stylesheet using the xsltprocessor.setparamete...
...or.setparameter() taking a third - the value of the parameter to be set. see the xslt/javascript interface in gecko for an example. resetting the xsltprocessor object also implements a xsltprocessor.reset() method, which can be used to remove all stylesheets and parameters then put the processor back into its initial state. this method is implemented in mozilla 1.3 and later. resources the following reflect the interface of the xsltprocessor object: nsixsltprocessor.idl xsltprocessor.webidl using xsltprocessor from xpcom components instantiating an xsltprocessor from an xpcom component requires a different syntax as the constructor is not defined inside components. instead of this: var processor = new xsltprocessor(); do this: var processor = components.classes["@mozilla.org/d...
XSLT: Extensible Stylesheet Language Transformations
Web › XSLT
d 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 in mozilla 1.2 and up. spec...
...n 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 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...
Web technology for developers
documentation for web developers web developer reference a list of all references for web technologies, including those for html, css, and so on. web developer guide the web developer guide provides useful how-to content to help you actually use web technologies to do what you want or need to do. ...
...iptability, including the dom and all of the related apis and interfaces you can use to build web content and apps. html hypertext markup language is the language used to describe and define the content of a web page. css cascading style sheets are used to describe the appearance of web content. svg scalable 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 technologiesdev...
Index - WebAssembly
found 12 pages: # page tags and summary 1 webassembly landing, webassembly, wasm webassembly is a new type of code that can be run in modern web browsers — it is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages such as c/c++ with a compilation target so that they can run on the web. it is also designed to run alongside javascript, allowing both to work together. 2 caching compiled webassembly modules caching, indexeddb, javascript, module, webassembly, compile, wasm caching is useful for improving the performance of an app — we can store compiled webassembly modules on the client so they don't have to be downloaded and compiled every time. this article ex...
...emscripten, webassembly, wasm when you’ve written a new code module in a language like c/c++, you can compile it into webassembly using a tool like emscripten. let’s look at how it works. 4 compiling an existing c module to webassembly c++, compiling, emscripten, webassembly, wasm a core use-case for webassembly is to take the existing ecosystem of c libraries and allow developers to use them on the web. 5 compiling from rust to webassembly compiling, webassembly, rust, wasm if you've written some rust code, you can compile it into webassembly! this tutorial takes you through all you need to know to compile a rust project to wasm and use it in an existing web app. 6 converting webassembly text format to wasm webassembly, assem...
Compiling an Existing C Module to WebAssembly - WebAssembly
these libraries often rely on c's standard library, an operating system, a file system and other things. emscripten provides most of these features, although there are some limitations. as an example, let's compile an encoder for webp to wasm. the source for the webp codec is written in c and available on github as well as some extensive api documentation. that's a pretty good starting point. ...
...ter); note: new uint8array(somebuffer) will create a new view onto the same memory chunk, while new uint8array(sometypedarray) will copy the data. depending on the size of your image, you might run into an error where wasm can't grow the memory enough to accommodate both the input and the output image: luckily, the solution to this problem is in the error message. you just need to add -s allow_memory_growth=1 to your compilation command. and there you have it. you have compiled a webp encoder and transcoded a jpeg image to webp. to prove that it worked, turn your result buffer into a blob and use it on an <img> element: const blob = new blob([result], {type: 'image/webp'}); const bloburl = url.createobjecturl(blob); const img = document.createelement('img'); img.src = bloburl; docume...
Builder - Archive of obsolete content
the add-on builder tool was retired on april 1, 2014. the add-on builder was a web-based development environment that allowed developers to create add-ons using the sdk apis, but without needing to use the jpm command line tool. it was retired on april 1, 2014, and the "builder.addons.mozilla.org" domain now redirects to this page. ...
Contributor's Guide - Archive of obsolete content
classes and inheritance a class is a blueprint from which individual objects are created. these individual objects are the instances of the class. each class defines one or more members, which are initialized to a given value when the class is instantiated. data members are properties that allow each instance to have their own state, whereas member functions are properties that allow instances to have behavior. inheritance allows classes to inherit state and behavior from an existing classes, known as the base class. unlike languages like c++ and java, javascript does not have native support for classical inheritance. instead, it uses something called prototypal inheritance. as it turns out, it is possible to emulate classical inheritance using prototypal inheritance, but not without wr...
SDK and XUL Comparison - Archive of obsolete content
xibility xul overlays offer a great deal of options for building a ui and integrating it into the browser. using only the sdk's supported apis you have much more limited options for your ui. xpcom traditional add-ons have access to a vast amount of firefox functionality via xpcom. the sdk's supported apis expose a relatively small set of this functionality. low-level apis and third-party 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 ...
Testing the Add-on SDK - Archive of obsolete content
th jpm jpm tests all use the new toolkit/loader. with jpm (which is not part of the add-on sdk repo, and must be installed separately) things more difficult without the gulp commands provided by the gulpscript.js file in the addon-sdk repo. with gulp installed, and after installing the addon-sdk's npm dependencies, we can run the latter three test suites mentioned for cfx with jpm using the following commands: gulp test:examples --filter <addon_example_folder_name> gulp test:addons --filter <addon_folder_name> gulp test:modules --filter <file_name>:<test_name> or run all of the tests with gulp test. with travis if you merely make a pull request for the mozilla/addon-sdk then all of the jpm tests mentioned above will be run on travis-ci automatically and you will see the pass/fail ...
Two Types of Scripts - Archive of obsolete content
modules such as page-mod and panel. content scripts may be supplied as literal strings or maintained in separate files and referenced by filename. if they are stored in separate files you should store them under the data directory under your add-on's root. to learn all about content scripts read the working with content scripts guide. api access for add-on code and content scripts the table below summarizes the apis that are available to each type of script. api add-on code content script the global objects defined in the core javascript language, such as math, array, and json. see the reference at mdn. ✔ ✔ the require() and exports globals defined by version 1.0 of the commonjs module specification. you use require() to import...
clipboard - Archive of obsolete content
currently the image type doesn't support transparency on windows. examples set and get the contents of the clipboard. var clipboard = require("sdk/clipboard"); clipboard.set("lorem ipsum dolor sit amet"); var contents = clipboard.get(); set the clipboard contents to some html. ...
hotkeys - Archive of obsolete content
require("sdk/hotkeys"); var showhotkey = hotkey({ combo: "accel-shift-o", onpress: function() { showmypanel(); } }); var hidehotkey = hotkey({ combo: "accel-alt-shift-o", onpress: function() { hidemypanel(); } }); choosing hotkeys hotkeys should be chosen with care. it's very easy to use combinations that clash with hotkeys defined for firefox or for other add-ons. the following commonly used hotkey combinations will not pass amo review: accel-z, accel-c, accel-x, accel-v or accel-q if you choose to use a key combination that's already defined, choose one which makes sense for the operation it will perform. for example, accel-s is typically used to save a file, but if you use it for something completely different, then it would be extremely confusing for users. no...
indexed-db - Archive of obsolete content
me(); var request = store.put({ "name": name, "time": time }); request.onerror = database.onerror; }; function getitems(callback) { var cb = callback; var db = database.db; var trans = db.transaction(["items"], "readwrite"); var store = trans.objectstore("items"); var items = new array(); trans.oncomplete = function() { cb(items); } var keyrange = idbkeyrange.lowerbound(0); var cursorrequest = store.opencursor(keyrange); cursorrequest.onsuccess = function(e) { var result = e.target.result; if(!!result == false) return; items.push(result.value.name); result.continue(); }; cursorrequest.onerror = database.onerror; }; function listitems(itemlist) { console.log(itemlist); } open("1"); var add = require("sdk/ui/button/acti...
l10n - Archive of obsolete content
n developer in .properties files stored in the add-ons "locale" directory. the gettext tools uses "_" for the name of the function that retrieves localized strings. for compatibility with tools that expect this syntax, you can assign this function to "_": var _ = require("sdk/l10n").get; given a .properties file for the current locale containing an entry like: hello_string= hello! and the following code: var _ = require("sdk/l10n").get; console.log(_("hello_string")); the following output will be logged: info: hello! if this function can't find the string referenced by the identifier parameter, it returns the identifier itself. this enables you to write functional, localizable code without localizing any strings - just make the identifiers the default language: var _ = require("sdk...
request - Archive of obsolete content
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. ...
system - Archive of obsolete content
able by setting the property: var system = require("sdk/system"); system.env.foo = "bar"; console.log(system.env.foo); you can unset a variable by deleting the property: var system = require("sdk/system"); delete system.env.foo; you can't enumerate environment variables. platform the type of operating system you're running on. this will be one of the values listed as os_target, converted to lower case. var system = require("sdk/system"); console.log("platform = " + system.platform); architecture the type of processor architecture you're running on. this will be one of: "arm"``,"ia32", or"x64"`. var system = require("sdk/system"); console.log("architecture = " + system.architecture); compiler the type of compiler used to build the host application. for example: "msvc", "n32", "gcc2...
ui - Archive of obsolete content
this page just provides a quick overview. actionbutton an action button is a button in the main firefox toolbar. ...
chrome - Archive of obsolete content
intend to deprecate it in future releases. if you use this api you can expect your add-on to get an extra security review by addons.mozilla.org. this module should not be confused with the "chrome" global variable that webextensions can use to access apis. 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. chrome is a built-in pseudo module of the toolkit loader. see the chrome authority tutorial for more details. you can see an example of using this api in the xul migration guide. ...
console/traceback - Archive of obsolete content
lineno the line number is being executed at the stack frame. ...
dev/panel - Archive of obsolete content
the toolbox: the panel gets a tab in the toolbox toolbar which enables the user to open it: you specify the panel's content and behavior using html, css, and javascript. when the panel's created, the framework passes it a debuggee: this is a messageport object that you can use to exchange json messages with the browser that the developer tools are currently debugging. the messages follow the remote debugging protocol. for a simple walkthrough of using the dev/panel api to add a new tool, see adding a panel to the toolbox. basic usage defining the panel constructor to add a new tool you first need to define a constructor that inherits from the panel class, and in that constructor you need to supply values for various properties . you can set the constructor up manually if you...
event/core - Archive of obsolete content
usage many modules in the sdk can broadcast events. for example, the tabs module emits an open event when a new tab is opened. also see the tutorial on implementing event targets to get started with this api. an event listener may be registered to any event target using the on function: var { on, once, off, emit } = require('sdk/event/core'); var target = { name: 'target' }; on(target, 'message', function listener(event) { console.log('hello ' + event); }); on(target, 'data', console.log); an event of a specific type may be emitted on any event target object using the emit function. ...
frame/hidden-frame - Archive of obsolete content
it is also useful in the construction of apis that load web content for intermittent display, such as panel. usage the module exports a constructor function, hiddenframe, and two other functions, add and remove. hiddenframe constructs a new hidden frame. add registers a hidden frame, preparing it to load content. remove unregisters a frame, unloading any content that was loaded in it. ...
io/file - Archive of obsolete content
rned stream. if the string contains "r", the file is opened in read-only mode. "w" opens the file in write-only mode. "b" opens the file in binary mode. if "b" is not present, the file is opened in text mode, and its contents are assumed to be utf-8. if mode is not given, "r" is assumed, and the file is opened in read-only text mode. apart from these options, this api always passes the following options: create_file, truncate (see //github.com/realityripple/uxp/blob/master/nsprpub/pr/include/prio.h#550). this means that: if the file does not exist it is created if the file exists, its length is truncated to zero it is not possible to open the file in append mode. returns stream : if the file is opened in text read-only mode, a textreader is returned, and if text write-only mo...
lang/type - Archive of obsolete content
epresentation of value, containing property descriptors and types of properties contained within the object. ...
net/xhr - Archive of obsolete content
h that they're "sandboxed" and don't communicate potentially sensitive cookie information. globals constructors xmlhttprequest() creates an xmlhttprequest. this is a constructor, so its use should always be preceded by the new operator. for more information about xmlhttprequest objects, see the mdn page on using xmlhttprequest and the security concerns section in this page. functions forceallowthirdpartycookie(xhr) force relevant cookies to be sent with this xmlhttprequest even if normally they would not be. parameters xhr: xmlhttprequest the xmlhttprequest to allow third-party cookies for. ...
places/history - Archive of obsolete content
ray of objects containing // data about visits to any site on developers.mozilla.org // ordered by visit count }); // complex query // the query objects are or'd together // let's say we want to retrieve all visits from before a week ago // with the query of 'ruby', but from last week onwards, we want // all results with 'javascript' in the url or title. ...
remote/parent - Archive of obsolete content
cesses.port.emit("message-from-main", "hello from main"); processes.port.on("message-from-remote", function(process, message) { console.log("remote says: " + message); }); child process privileges a module loaded into a child process can't do everything that the same module loaded into the parent process can. multiprocess firefox restricts the things that code running in child processes is allowed to do. for example, when the child process is sandboxed, modules won't be able to access the file system. we don't yet have a full list of all the modules that a module in the child process can't load, but the sorts of things listed in limitations of frame scripts broadly apply. examples property retrieval this first example shows fetching a simple property from every existing and future pr...
stylesheet/style - Archive of obsolete content
r an array of strings, that represents local uri to stylesheet. source string,array a string, or an array of strings, that contains css rules. those rules are applied after the rules in the stylesheet specified with uri options, if provided. optional options: name type type string the type of the sheet. it accepts the following values: "agent", "user" and "author". if not provided, the default value is "author". style properties source an array of strings that contains the css rule(s) specified in the constructor's option; null if no source option was given to the constructor. this property is read-only. uri an array of strings that contains the stylesheet local uri(s) specified in the constructor's o...
system/child_process - Archive of obsolete content
dk/system/child_process") fork() is not supported gid and uid are not supported in node.js, spawn() and exec() inherit the environment variables from the parent process, by default. the sdk versions don't: so when you specify a command you must pass in a complete path to the command or use the env option to set up the child process environment. ...
system/events - Archive of obsolete content
you can find a list of events dispatched by the firefox codebase here. var events = require("sdk/system/events"); var { ci } = require("chrome"); function listener(event) { var channel = event.subject.queryinterface(ci.nsihttpchannel); channel.setrequestheader("user-agent", "mybrowser/1.0", false); } events.on("http-on-modify-request", listener); globals functions emit(type, event) send an event to observer service parameters type : string the event type. ...
system/unload - Archive of obsolete content
when ensure() is called. parameters object : object an object that defines a destructor method. name : string optional name of the destructor 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. ...
system/xul-app - Archive of obsolete content
n. parameters name : string a host application name. returns boolean : true if the host application is name and false otherwise. isoneof(names) checks whether the host application is one of the given applications. parameters names : array an array of host application names. returns boolean : true if the host application is one of the names and false otherwise. versioninrange(version, lowinclusive, highexclusive) compares a given version to a version range. see the mdn documentation for details on version comparisons. parameters version : string the version to compare. lowinclusive : string the lower bound of the version range to compare. the range includes this bound. highexclusive : string the upper bound of the version range to compare. the range does not include this b...
util/collection - Archive of obsolete content
pties the collection and adds all the items in the array. parameters object : object the property will be defined on this object. propname : string the name of the property. backingarray : array if given, this will be used as the collection's backing array. collection a collection object provides for...in-loop iteration. items are yielded in the order they were added. for example, the following code... var collection = require("sdk/util/collection"); var c = new collection.collection(); c.add(1); c.add(2); c.add(3); for (item in c) console.log(item); ... would print this to the console: 1 2 3 iteration proceeds over a copy of the collection made before iteration begins, so it is safe to mutate the collection during iteration; doing so does not affect the results of the i...
util/list - Archive of obsolete content
kes any number of elements and creates an instance of list populated with the specified elements. parameters element1 : object|string|number element2 : object|string|number ... : object|string|number functions addlistitem(list, item) function adds a item to a list. removelistitem(list, item) function removes an item from a list list an ordered collection (also known as a sequence) disallowing duplicate elements. list is composed out of iterable, therefore it provides custom enumeration behavior that is similar to array (enumerates only on the elements of the list). list is a base trait and is meant to be part of a composition, since all of its api is private except for the length property. examples: var { list } = require("sdk/util/list"); var mylist = list.compose({ add: func...
util/object - Archive of obsolete content
opertydescriptor(c, "name"); console.log(props.configurable); // true parameters source : object the object that other properties are merged into. arguments : object n amount of additional objects that are merged into source object. returns object : the source object. extend(arguments) returns an object that inherits from the first argument and contains all of the properties from all following arguments, with precedence from right to left. extend(source1, source2, source3) is the equivalent of merge(object.create(source1), source2, source3). let { extend } = require("sdk/util/object"); var a = { alpha: "a" }; var b = { beta: "b" }; var g = { gamma: "g", alpha: null }; var x = extend(a, b, g); console.log(a); // { alpha: "a" } console.log(b); // { beta: "b" } console.log(g); // { ...
cfx to jpm - Archive of obsolete content
en 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 should use a path relative to "main.js", and prefix the path with "./" to indicate that it's a relative path: var utils = require("./utils"); however, with cfx you are also allowed to omit the "./": var utils = require("utils"); // this will not work with jpm! this second form will not work with jpm. requiring modules from test code similarly, suppose you've written some tests for your add-on: my-addon lib my-addon.js test test-my-addon-js with cfx, code inside "test-my-addon.js" can import "my-addon.js" using a...
console - Archive of obsolete content
ing written. but if the logging level is "warn" then only calls to warn() and error() have any effect, and calls to info() and log() are simply discarded. this means that the same code can be more verbose in a development environment than in a production environment - you just need to arrange for the appropriate logging level to be set. ...
jpmignore - Archive of obsolete content
tore # ignore any zip or xpi files *.zip *.xpi # ignore specific directory # you can start patterns with a forward slash (/) to avoid recursivity. # you can end patterns with a forward slash (/) to specify a directory. /sample/ a .jpmignore file with the above contents would ignore all zip files and .ds_store files and sample directory from the xpi generated by jpm xpi. using .jpmignore to allow files everything in your add-on directory will be included in the xpi file you make with jpm xpi. if your project folder contains a lot of files that aren't necessary for the xpi to run, like documentation, jshint, etc., you can use .jpmignore as a whitelist instead of a blacklist. for example: .* * !/data/** !/lib/** !/locale/** !/node_modules/** !/package.json !/icon.png !/icon64.png !/copyin...
Add a Context Menu Item - Archive of obsolete content
to add items and submenus to the firefox context menu, use the context-menu module. here's an add-on that adds a new context menu item. the item is displayed whenever something in the page is selected. ...
Implementing the widget - Archive of obsolete content
& event.shiftkey == true)) self.port.emit('right-click'); event.preventdefault(); }, true); save this in your data/widget directory as widget.js. the widget's icons you can copy the widget's icons from here: or, if you're feeling creative, you can make your own icons. either way, save them in your data/widget directory. ...
Storing annotations - Archive of obsolete content
when you restart firefox, double check you installed the add-on and didn't just use cfx run again. responding to overquota events add-ons have a limited quota of storage space. if the add-on exits while it is over quota, any data stored since the last time it was in quota will not be persisted. so we want to listen to the overquota event emitted by simple-storage and respond to it. ...
Display a Popup - Archive of obsolete content
to display a popup dialog, use the panel module. a panel's content is defined using html. you can run content scripts in the panel: although the script running in the panel can't directly access your main add-on code, you can exchange messages between the panel script and the add-on code. in this tutorial we'll create an add-on that adds an action button to the toolbar that displays a panel when clicked. the panel just contains a <textarea> element: when the user presses the return key, the contents of the <textarea> is sent to the main add-on code. the main add-on code logs the message to the console. ...
Listen for Page Load - Archive of obsolete content
you don't get direct access to any content hosted in the tab. to access tab content you need to attach a script to the tab using tab.attach(). this add-on attaches a script to all open tabs. ...
Open a Web Page - Archive of obsolete content
to open a new web page, you can use the tabs module: var tabs = require("sdk/tabs"); tabs.open("http://www.example.com"); this function is asynchronous, so you don't immediately get back a tab object which you can examine. to do this, pass a callback function into open(). the callback is assigned to the onready property, and will be passed the tab as an argument: var tabs = require("sdk/tabs"); tabs.open({ url: "http://www.example.com", onready: function onready(tab) { console.log(tab.title); } }); even then, you don't get direct access to any content hosted in the tab. to access tab content you need to attach a script to the tab using tab.attach(). ...
Using third-party modules (jpm) - Archive of obsolete content
to install menuitem you'll need to have git command. ...
Add-on SDK - Archive of obsolete content
de to porting xul add-ons to the sdk. this guide includes a comparison of the two toolsets and a working example of porting a xul add-on. reference high-level apis reference documentation for the high-level sdk apis. tools reference reference documentation for the jpm tool used to develop, test and package add-ons, the console global used for logging, and the package.json file. low-level apis reference documentation for the low-level sdk apis. ...
Alerts and Notifications - Archive of obsolete content
it uses nsialertsservice. ...
Cookies - Archive of obsolete content
services.cookies.add(".host.example.com", "/cookie-path", "cookie_name", "cookie_value", is_secure, is_http_only, is_session, expiry_date); see also document.cookie nsicookie nsicookie2 nsicookieservice nsicookiemanager nsicookiemanager2 http cookies ...
Customizing the download progress bar - Archive of obsolete content
this example illustrates how to customize the progress bar displayed for a given download in the downloads window. first you need to overlay the downloads window so that you can add a new stylesheet. ...
Downloading Files - Archive of obsolete content
please use downloads.jsm instead. downloading files to download a file, create an instance of nsiwebbrowserpersist and call its nsiwebbrowserpersist.saveuri() method, passing it a url to download and an nsifile instance representing the local file name/path. ...
Drag & Drop - Archive of obsolete content
the _dragdrop function retrieves the file uri data from the drag session and creates an array of file uris that the xul application can use. ...
Examples and demos from articles - Archive of obsolete content
[article] fade in/out [html] sometimes a page uses dozens and dozens of animations. in such a condition is difficult and unnatural to keep 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. ...
IsDefaultNamespace - Archive of obsolete content
note that all gecko-based browsers (including firefox) support node.isdefaultnamespace. this function is not necessary for gecko-based browsers (though the function will quickly return the standard value for mozilla browsers). ...
Label and description - Archive of obsolete content
...
LookupPrefix - Archive of obsolete content
here is an implementation of lookupprefix which should work cross-browser. note that all gecko-based browsers (including firefox) support node.lookupprefix. this function is not necessary for gecko-based browsers when used in xhtml. ...
Page Loading - Archive of obsolete content
post data to window code to post data to an existing or new window/tab ...
Post data to window - Archive of obsolete content
tance(ci.nsimimeinputstream); postdata.addheader("content-type", "application/x-www-form-urlencoded"); postdata.addcontentlength = true; postdata.setdata(stringstream); // postdata is ready to be used as apostdata argument ... posting data to the current tab there is a convenience method in global scope (in firefox, chrome://browser/content/browser.js): loaduri(auri, areferrer, apostdata, aallowthirdpartyfixup); posting data to a new window window.opendialog('chrome://browser/content', '_blank', 'all,dialog=no', auri, aflags, areferrer, apostdata); ...
JavaScript timers - Archive of obsolete content
the setinterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. the setimmediate() function can be used instead of the settimeout(fn, 0) method to execute heavy operations in ie. ...
xml:base support in old browsers - Archive of obsolete content
note however, that this code is not based on a thorough examination of the specs related to forming base uris and could well have a number of errors. however, it is working in some of the cases tested. ...
XPath - Archive of obsolete content
notes and sample code for xpath and ajax (the following was moved from document.evaluate) obj.evaluate(xpathexpression,contextnode,namespaceresolver,resulttype,result); //obj and contextnode should be the same object, if context is a ajax xml object (example: returnedxml) this should be used as : returnedxml.evaluate(xpathexpression,returnedxml,namespaceresolver,returntype,result); //contextnode should be used in the one in which it was created //add by mooring 2008-11-15 16:00 china var xhr = new ajax('post','demo.xml',parsexml,'xml'); //ajax is a class written by javascript which return responsexml object to parsexml function function parsexml(obj)//obj is the returnxml object now { if(!obj.documentelement) { alert("your browser does't support this script!"); return...
Deploying a Plugin as an Extension - Archive of obsolete content
ugins directory, or, on windows, place it into your own directory and modify the windows registry to let firefox know where to find the plugin. the downside to this method is that once the plugin is installed, it might be difficult for users to upgrade, uninstall, or disable the plugin. with firefox 1.5, you can use the built-in extension mechanism to make a plugin available to your users. this allows the plugin to be treated like other firefox extensions; it can be upgraded, disabled, or uninstalled using the firefox user interface. in this article, we will create an extension for the rhapsody player engine. normally, this plugin is installed in a local directory, and a registry item is used to let firefox know about the plugin. first, let's take a look at the structure of the xpi file used ...
Extension Packaging - Archive of obsolete content
w. the xpi file must contain only uncompressed files, or files compressed using the deflate algorithm. the mime type recognized by firefox for xpi files is application/x-xpinstall. since most http servers are not configured to return this mime type for the .xpi extension by default, you will probably need to configure your http server. in the apache http server, this can be done by adding the following directive to the configuration file or .htaccess: addtype application/x-xpinstall .xpi install extension files directly if you know the location of the application (if you are installing an extension as part of the application installer, for example), you can install the extension files directly to <appdir>/extensions/<extensionid>. the extension will be found automatically by the extensio...
Extension Theming Guidelines - Archive of obsolete content
this is a set of guidelines on how to control the look and feel of your extension while leaving it open for styling by custom themes. skin packages just as extension code should exist in chrome content packages, all of the styling for an extension including css and images should exist in a chrome skin package. custom themes may then register a replacement for your skin package allowing them to provide their own styles for all of your content. branding certain items of your extensions style, in particular logos and icons can be kept in the chrome content package such that they are not replaceable by custom themes stylesheets guidelines include stylesheets for every new window that your extension adds and for every window that your extension overlays content into be sure to add a sty...
Offering a context menu for form controls - Archive of obsolete content
on form controls. this article presents information based on ehsan akhgari's form control context menu extension, which was created specifically to demonstrate how to do this. there is ongoing discussion about this topic; please see bug 433168 for the latest information. overlay the content the first thing to do is to establish an overlay over the chrome for the window in which you want to allow context menus on form controls. <overlay id="formcontrolcontextmenu-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://formcontrolcontextmenu/content/overlay.js"/> </overlay> change the right-click behavior the overlaid code is responsible for adjusting the behavior of right-clicking on form controls. ...
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
ed 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. xml coding css coding basic javascript syntax xml: a text-based structural language extensible markup language (xml) is a meta-language for expressing various kinds of data. it was specified in 1998 by w3c, the organization that sets standards for web-related technologies. it has a number of useful qualities: it i...
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
d event handler: // rest of overlay code goes here. window.addeventlistener( "load", function() { xulschoolchrome.browseroverlay.init(); }, false); then all we need is some persistent flag that ensures that the first run code is only run once. the best approach in this case is to use a preference, as explained in the handling preferences section. so, if we were to use fuel, we can do the following in the init function: init : function() { let firstrunpref = "extensions.xulschoolhello.firstrundone"; if (!application.prefs.getvalue(firstrunpref, false)) { application.prefs.setvalue(firstrunpref, true); // all the rest of the first run code goes here. } } in this case you would need to declare the first run preference in your default preferences file, with a default value ...
Introduction - Archive of obsolete content
uilt using mozilla technologies. even this project, called xul school, covers several other technologies such as javascript, css, xbl and xpcom. xulrunner xulrunner includes the gecko rendering engine, the necko networking library, and several other components that provide os-independent file management, accessibility, and localization, among others. it is this very powerful platform that has allowed such a fast growth of the development community surrounding mozilla and firefox. xulrunner is available in binary form at the xulrunner page, and it is the base for several projects, such as songbird, miro and eudora. there's a very comprehensive list of xulrunner applications in the xulrunner hall of fame. gecko the gecko engine is the part of firefox used to render web pages and its own us...
Observer Notifications - Archive of obsolete content
ript code modules or xpcom. as we saw in previous sections, you can use javascript code module and xpcom objects very easily from the chrome. but given that chrome is window-dependent and non-chrome objects are not, it's tricky to send a message to the chrome. you would have to invoke a method for the chrome objects in all windows. it's much easier to use observers in this case. let's see the following example code on how to send out a notification from non-chrome code. /** * notifies all the registered observers with the test notification topic. */ notifytest : function() { let observerservice = components.classes["@mozilla.org/observer-service;1"]. getservice(components.interfaces.nsiobserverservice); let subject = components.classes["@mozilla.org/supports-string;1"]. ...
XUL School Tutorial - Archive of obsolete content
its contents have been modified from the original source as necessary. ...
Signing an XPI - Archive of obsolete content
temporarily install the test certificate authority into your mozilla browser rename the x509.cacert file generated earlier to x509.cert import it into mozilla firefox as a software developer certificate authority. don't forget to delete the certificate from mozilla firefox once you've finished testing firefox 1.5: from the tools menu choose options->advanced->security->vie...
Add-ons - Archive of obsolete content
offers some best practices and suggestions that can not only improve the performance and speed of your extension, but also of firefox itself. security best practices in extensions this document is intended as a guide for developers to promote best practices in securing your extension. your goal is to keep your users safe. some items mentioned are strict guidelines, meaning that if you don't follow them then your add-on will not be approved on mozilla add-ons. other items are recommendations. the difference will be clearly flagged. setting up an extension development environment this article provides suggestions for how to set up your mozilla application for extension development. these details apply to firefox, thunderbird, and seamonkey (version 2.0 and above). tabbed browser here you...
DOMSubtreeModified - Archive of obsolete content
this event has been deprecated in favor of the mutation observer api this event can cause infinite loops if you decide to change the dom inside the event handler, hence it has been disabled in a number of browsers (see domattrmodified and domsubtreemodified events are no longer fired when style attribute is changed via cssom for example). ...
Install.js - Archive of obsolete content
nkey from the xsidebar project. pros: this version consolidates all the changable information at the top of the file. and it also knows how to install packaged components, search engines and default preferences. cons: code is bloated since it has to cater for several different ways an extension author can package the .jar file contained in the .xpi file. xpi file structure you can use the code below (taken from pike's extensions ). it assumes the following structure of your xpi file: sampleext.xpi chrome\ sampleext.jar content\ sampleext\ locale\ (optional) en-us\ sampleext\ ... skin\ (optional) classic\ sampleext\ ... install.js install.rdf (optional -- see above) code // install.js // xpiinstall...
List of Former Mozilla-Based Applications - Archive of obsolete content
a list of actively maintained mozilla-based applications is also available. ...
List of Mozilla-Based Applications - Archive of obsolete content
this list is likely to be incomplete since we think 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. a list of former mozilla-based applications is also available. name description additional information 389 directory server ldap server uses nss a380 seatback entertainment system media software this blog post mentions a reference to mozilla being used but i couldn't find more information about it. ...
Bypassing Security Restrictions and Signing Code - Archive of obsolete content
these privilege manager feature was not used much (aside from abuse), and its complexity made performance improvements difficult. signed script segregation was removed in bug 726125, the enableprivilege prompt was removed in bug 750859, and enableprivilege itself was nerfed in bug 757046. the privilege manager has been deprecated in firefox 12 and disabled in firefox 17. ...
Monitoring WiFi access points - Archive of obsolete content
example this example simply displays a list of the available access points. ...
Using XML Data Islands in Mozilla - Archive of obsolete content
this feature is not based on multi-vendor web standards and is not supported in firefox (or other non-ie browsers). xml data islands are no longer supported from internet explorer 10 onwards. html5 has a more general feature called "data blocks" that can carry almost any textual data, including xml. javascript can use the content of a <script> element as a data block if the src attribute is omitted and the type attribute does not specify an executable script type. ...
Kill the XUL.mfl file for good - Archive of obsolete content
la creates in its profile directory a file named xul.mfl, which contains pre-compiled ui elements. this is meant to speed up the operation of mozilla, however in a fileserver based environment, this can be problematic: at several megabytes a pop, these files will take up a considerable amount of space, because each user has his own... loading these files from the server, and storing them back slows down the network, thus it may actually be faster without than with xul.mfl occasionnally gets corrupted, needing a manual intervention to wipe it out, before mozilla again works correctly. with quicklauncer (see above), mozilla's speed is actually quite adequate, even without xul.mfl for these reasons, it is desirable to disable the xul.mfl functionality. unfortunately, there appears to be no...
Locked config settings - Archive of obsolete content
s can be put into a mozilla.cfg file in the c:\program files\mozilla.org\mozilla directory. the mozilla.cfg file is an encoded file of javascript commands. the encoding is a simple "byte-shifting" with an offset of 13 (netscape 4 used a similar encoding, but with a of 7 instead). this file also needs to be "called" from c:\program files\mozilla.org\mozilla\defaults\pref\all.js by appending the following line at the end: pref("general.config.filename", "mozilla.cfg"); note: newer versions of mozilla or firefox store the all.js file in greprefs rather than defaults\pref the moz-byteshift.pl script allows to encode...: moz-byteshift.pl -s 13 <mozilla.cfg.txt >mozilla.cfg ... and to decode mozilla.cfg files: moz-byteshift.pl -s -13 <mozilla.cfg >mozilla.cfg.txt example of an unencoded file:...
Protecting Mozilla's registry.dat file - Archive of obsolete content
serprofile%\application data, including mozilla's . in order to prevent this, it's preferable to have mozilla's registry.dat file copied over from the server using the logon script. moreover, it's advisable to "protect" the mozilla registry using attrib +r +s in case the logon script is finished before ie's "personnalized settings" have completed their dirty deed... ...
Automatically Handle Failed Asserts in Debug Builds - Archive of obsolete content
a.org\windbgdlg and hkcu\software\mozilla.org\windbgdlg. at the first match, it will take the action specified by the dword's value. the valid values are: 0x5 automatically ignore 0x4 automatically retry 0x3 automatically abort note that you can also force windbgdlg to prompt, by setting a value of 0xfffffffe. to "comment out" a value, set its value to 0xffffffff. ...
BlackConnect - Archive of obsolete content
the goal was to be able to implement xpcom components written in java instead of c++. ...
Chromeless - Archive of obsolete content
chromeless apps have access to a collection of javascript apis that provide them with deep desktop integration. one of the core capabilities of the chromeless platform is the ability to safely embed untrusted web applications inside these applications. ...
Creating a Firefox sidebar extension - Archive of obsolete content
ox are installed with packages ("bundles"). an extension package usually contains a "content" provider, which contains the xul code and application logic. optionally locales and skins can be included. most additions are provided with a default tree structure, although not required it is recommended to use this structure. here the package for the sidebar is created, the files included are listed below. example 1. package structure emptysidebar \- chrome |- content |- locale | \- en-us \- skin create all folders, except for skin. it is not used for this tutorial. the locale holds the locale, only the en-us locale is created. it is listed in example 2. the locale includes the name and shortcut keys for the sidebar. example 2. chrome/locale/emptysidebar.dtd <!entity emptysid...
Enabling the behavior - updating the status periodically - Archive of obsolete content
nkey/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 css code into that file back in specifying the appearance.
Finding the file to modify - Archive of obsolete content
box in mozilla 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)...
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
nt to the right place. after that we'll create a contents.rdf file describing the tinderstatus component for the chrome registry and an install.js script to perform the installation. finally we'll zip the files into an archive. start out by creating a directory called tinderstatus-installer. create a tinderstatus subdirectory in it and a content sub-subdirectory in that subdirectory. copy the following files into the content sub-subdirectory: tinderstatusoverlay.xul tinderstatus.js tinderstatus.css tb-busted.png tb-nostatus.png tb-success.png tb-testfailed.png these are the files we're going to put into the xpi. we need to change some urls in the copy of tinderstatusoverlay.xul to point to the new locations the files will be in when they get installed via the xpi: <?xml version="...
Making it into a static overlay - Archive of obsolete content
r child elements of the statusbar element in the overlay file to be added to the interface's dom and thus show up in the interface as if they were defined on the same element in navigator.xul. note that we've added a new attribute to the statusbarpanel element: insertbefore. this attribute identifies another statusbarpanel element within statusbar before which our element should appear. thus it allows us to define the exact position of our element relative to the other statusbarpanel elements within statusbar. if insertbefore is omitted, the element will be added as the last child of statusbar, usually before the resizer grippy. we could instead have used an insertafter attribute to place the element after another. to use this overlay instead of our changes to navigator.xul we need to remove ...
Prerequisites - Archive of obsolete content
you should also understand tag-based languages like html as well as basic javascript, css, and the dom. you might install mozilla multiple times in the course of this tutorial, so you will find it handy to keep around a mozilla installer. if you currently use mozilla, you should install a new copy of the software in a different location from the existing installation for the purposes of this demo. ...
Specifying the appearance - Archive of obsolete content
if you restart mozilla now you should see the "no status" icon appear in the browser's status bar. « previousnext » ...
chrome.manifest - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "chrome.manifest": skin global my_theme jar:chrome/my_theme.jar!/global/ skin mozapps my_theme jar:chrome/my_theme.jar!/mozapps/ skin messenger my_theme jar:chrome/my_theme.jar!/messenger/ skin messenger-newsblog my_theme jar:chrome/my_theme.jar!/messenger-newsblog/ skin communicator my_theme jar:chrome/my_theme.jar!/communicator/ skin help my_theme jar:chrome/my_theme.jar!/help/ skin navigator my_theme jar:chrome/my_theme.jar!/navigator/ skin editor my_theme jar:chrome/my_theme.jar!/editor/ ...
install.rdf - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "install.rdf": <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>author@oftheme.com</em:id> <em:version>2.0b1</em:version> <!-- seamonkey --> <em:targetapplication> <description> <em:id>{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}</em:id> <em:minversion>2.0b1pre</em:minversion> <em:maxversion>2.0b2pre</em:maxversion> </description> </em:targetapplication> <!-- front end metadata --> <em:name>my_theme</em:name> <em:description>my first theme</em:description> <!-- front end integration hooks (used by ...
Getting Started - Archive of obsolete content
to whatever you want your theme called and then its version number. then scroll down to the next section. <rdf:description about="urn:mozilla:skin:myskin/1.0" chrome:displayname="my skin" chrome:accesskey="m" chrome:author="me" chrome:description="this is my custom skin for mozilla" chrome:name="myskin/1.0" chrome:image="preview.png"> the blue areas are explained below. the first line should match the line that you modified in the previous section. the display name. that is what the user sees in the preference panels list of themes. the access key is what key you can press to activate the skin in the preferences. replace the author section with your name. the description shows up below the preview image. place your theme name and version number on this l...
contents.rdf - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "contents.rdf": <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:chrome="http://www.mozilla.org/rdf/chrome#"> <!-- list all the skins being supplied by this theme --> <rdf:seq about="urn:mozilla:skin:root"> <rdf:li resource="urn:mozilla:skin:myskin/1.0" /> </rdf:seq> <rdf:description about="urn:mozilla:skin:myskin/1.0" chrome:displayname="my skin" chrome:accesskey="m" chrome:author="me" chrome:description="this is my custom skin for mozilla" chrome:name="myskin/1.0" chrome:image="preview.png"> <chrome:packages> <rdf:seq about="urn:mozilla:skin:myskin/1.0:packages"> <rdf:li resource=...
toolbarBindings.xml - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "toolbarbindings.xml": <bindings id="toolbarbindings"> <binding id="toolbar-primary" extends="chrome://global/content/bindings/toolbar.xml#toolbar-primary"> <content> <xul:hbox class="toolbar-holder toolbar-primary-holder" flex="1" xbl:inherits="orient=tborient,buttonstyle"> <xul:hbox class="toolbar-button-box" flex="1"> <children/> </xul:hbox> <xul:image class="toolbar-primary-icon" xbl:inherits="buttonstyle"/> </xul:hbox> </content> </binding> </bindings> ...
DTrace - Archive of obsolete content
probe data can be collected with scripts written in d (no, not that one). mozilla dtrace support has been added by the sun dtrace team and can be used on solaris 10 and mac os x 10.5. dtrace has been largely supplanted by the gecko profiler and other tools, so this documentation has been archived. if you find that there are still use cases of consequence, you're welcome to file a documentation bug. ...
Dehydra Frequently Asked Questions - Archive of obsolete content
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. ...
Dehydra - Archive of obsolete content
edorahosted.org/gcc-python-plugin/. dehydra was a lightweight, scriptable, general purpose static analysis tool capable of application-specific analyses of c++ code. in the simplest sense, dehydra could be thought of as a semantic grep tool. it presented a wealth of semantic information that can be queried with concise javascripts. it was also useful to find bugs in source code as it allows for much more error checking than c++ is capable of by itself. dehydra was built as a gcc plugin, thus it is easy to use for projects that already support gcc. dehydra is also useful for generating language bindings and is used to bootstrap treehydra, a heavy-duty static analysis gcc plugin. documentation installing dehydra download, installation and dependency ...
Developing New Mozilla Features - Archive of obsolete content
ect job. and since few of us are perfect, chances are that revisions will be requested. if you’ve got a large patch, let the likely reviewers know when they might expect to see it if your timeframe is tight, check out the mozilla roadmap for milestone dates and see if your feature will arrive at a time of furious activity. if so, and if your feature is not of general interest, prepare to be a low priority for a while. get connected with mozilla.org staff mitchell@mozilla.org is a good contact for project management discussions. let us know what you’re doing. if you can find the resources, designate someone on your team as the liaison to mozilla.org for project management issues. review and super-review take time improving the code as requested by the reviewers takes time. poor quali...
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; ...
Download Manager preferences - Archive of obsolete content
a boolean value that indicates whether or not to delete the temporary file used by the download manager after the download is complete. on mac the default value is false. on other oses the default value is true if a preference is not set when the download manager looks it up, the download manager assumes the default value but doesn't necessarily add the missing preference. the following table however, includes preferences which must be included in any product for the download manager to function. preference description browser.download.dir a local folder the user may have selected for downloaded files to be saved. migration of other browser settings may also set this path. this folder is enabled when browser.download.folderlist equals 2. brow...
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. ...
Exception logging in JavaScript - Archive of obsolete content
. in other words, all unhandled javascript exceptions (except those in rules 3 and 4 above) will be logged before control returns to the outermost c++ caller. forcing logging of exceptions in inner js frames sometimes you might actually want to see all exceptions from inner javascript frames logged (in the call chain above that would be when an exception is unhandled in frame 4). note that the following will have no effect on the ns_nointerface exceptions outlined in rules 3 and 4 above - those exceptions will not be reported in any case. there are two ways you can accomplish this. first, you can set the boolean preference dom.report_all_js_exceptions. if this preference is true, all exceptions from inner frames will be logged. alternatively, you can set the environment variable moz_report_al...
External CVS snapshots in mozilla-central - Archive of obsolete content
those directories shall be considered read-only, changes shall be delivered to the upstream software projects. eventually we'd like to have acls, but as of today there is no protection for accidental commits to those directories. such changes will get overwritten without warning on importing the next updated version. ...
Downloading Nightly or Trunk Builds - Archive of obsolete content
builds. for the trunk and the latest two branches, there are machines at mozilla and maybe elsewhere compiling builds as fast as they can make them for at least all three of firefox, thunderbird and seamonkey on all three of linux-i686, mac-universalbinary and win32. these are the "tinderbox builds", also known as "hourly builds" though it usually takes more than one hour to make one; they are followed by automatic tests and their main purpose is to check that nothing is horridly wrong with the latest change to the source: what they are doing is to constantly check that the current source can be built into an executable and that that executable passes a certain more-or-less fixed set of tests. nightly builds. the same machines produce about every 24 hours a "nightly" build which can be down...
JSS build instructions for OSX 10.6 - Archive of obsolete content
the generic instructions didn't work to build on osx 10.6.7. ...
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-...
GRE Registration - Archive of obsolete content
zilla.org/gre/<version> and will try alternate keys <version>_1 _2 until an available key is found. mac on mac, the only gre is the libxul framework xul.framework. this framework is installed either in /library/frameworks/xul.framework/versions/<version> or in ~/library/frameworks/xul.framework/versions/<version>. linux on linux, registration information is kept in ini-style files of the following form: [1.7.10] gre_path=/usr/lib/mozilla-1.7.10 feature=value feature2=value2 these ini files can be in any of the following locations: /etc/gre.conf /etc/gre.d/*.conf ~/.gre.conf ~/.gre.d/*.conf mozilla has never officially shipped a linux gre based on the mozilla suite. however, some linux distributors including red hat/fedora core ship /etc/gre.d/*.conf files with the mozilla suite rpms. ...
Helper Apps (and a bit of Save As) - Archive of obsolete content
when this fails, uriloader asks an nsiexternalhelperappservice to handle the load. the nsexternalhelperappservice looks up the nsimimeinfo for the load and creates an nsihelperapplauncher to manage the load. the nsexternalapphandler (which implements nsihelperapplauncher) uses the nsimimeinfo and an nsihelperapplauncherdialog to decide what to do with the data. the nsexternalapphandler does whatever it decided to do. ...
Isp Data - Archive of obsolete content
tools needed the files are simple text files, in utf-8 encoding, so use your favorite modern text editor. a working install of thunderbird is also handy for testing. ...
JavaScript OS.Shared - Archive of obsolete content
tiveone_or_fd (unix only) negativeone_or_nothing (unix only) string (unix only) null_or_string (unix only) handle (windows only) maybe_handle (windows only) dword (windows only) negative_or_dword (windows only) zero_or_dword (windows only) zero_or_nothing (windows only) declareffi() intn_t() uintn_t()instances of os.shared.type convert_from_c() releasewith() attributes global object os.shared.hollowstructure in_ptr out_ptr inout_ptr ...
Content - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development. ...
Extenders - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development. ...
Twitter - Archive of obsolete content
jquery.ajax(), and so they are called like so: success(data, textstatus) data is twitter's decoded json response. textstatus is a simple string describing the status. error(xmlhttprequest, textstatus, errorthrown) xmlhttprequest is the xhr used in the request. textstatus is a simple string describing the type of error. errorthrown is an exception object, if one was thrown. the examples below all use this first, simpler style. the second style will be familiar if you have used jquery.ajax() -- in fact the object is passed as-is (almost) to it. in other words, define a data property that is itself an object whose properties correspond to the parameters of the twitter method. with this style you can use any of the various jquery.ajax() options in your request: data, success, complete, e...
Libraries - 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! namespace: jetpack.lib jetpack provides libraries for interacting with web and other services not part of the jetpack core. they live in the jetpack.lib namespace. the following libraries are available: twitter ...
Enabling Experimental Jetpack Features - Archive of obsolete content
nality that foo yields to the script. in jetpack, we propse adding a new function to the base namespace called importfromfuture. methods import(stringmountpath string)imports the requested experimental feature into the script. stringmountpathstring that enumerates where, starting from the jetpack base, the feature will be mounted. to get a list of mount paths that are available, see the method below. string here is an example of how to import a feature (the clipboard) from the future. jetpack.future.import("clipboard"); the goal here is to be able to remove the jetpack.future.import() call when the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration). list() arrayreturns an array of the set of potentia...
Enabling - Archive of obsolete content
onality that foo yields to the script. in jetpack, we propse adding a new function to the base namespace called importfromfuture. methods import(stringmountpath string)imports the requested experimental feature into the script. stringmountpathstring that enumerates where, starting from the jetpack base, the feature will be mounted. to get a list of mount paths that are available, see the method below. string here is an example of how to import a feature (the clipboard) from the future. jetpack.future.import("clipboard"); the goal here is to be able to remove the jetpack.future.import() call when the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration). list()returns an array of the set of potential str...
Me - Archive of obsolete content
Archive › Mozilla › Jetpack › Meta › Me
ad 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! the jetpack.me namespace provides mechanisms for introspecting the dynamic state of your jetpack. the namespace currently lives in the future and must be imported before it is used: jetpack.future.import("me"); methods onfirstrun(funcfunction)jetpack.me.onfirstrun() allows jetpacks to be notified after they are successfully installed. onfirstrun() accepts a callback which is called after installation. note that this mechanism is independent of the first-run page; in particular, the callback is not a load event listener or jquery ready callback. onfirstrun() may be called anywhere in your jetpack, but if it is called as the result of some asynchronous operation suc...
File access - Archive of obsolete content
...
slideBar - Archive of obsolete content
about status: in development instantiation: jetpack.future.import('slidebar') last update: v0.6 summary: slidebar is a reinvention of the old sidebar feature of browsers. they allow quick access to a wide range of both temporary and permanent information at the side of your browser window. when a slidebar feature is selected, its contents will be revealed from behind the current web page. creating a slidebar and adding options to implement a new slidebar within your jetpack code, use the method jetpack.slidebar.append(options) ...
slideBar - 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! slidebar is a reinvention of the old sidebar features of browsers. they allow quick access to a wide range of both temporary and permanent information at the side of your browser window. when a slidebar feature is selected its contents will be revealed from behind the current webpage. it currently under development and lives in the future. jetpack.future.import("slidebar"); methods append(iconurihtmlhtml/xmlurluriwidthintpersistboolautoreloadboolonclickfunctiononselectfunctiononreadyfunction)this is a list of options to specify modifications to your slidebar in...
UI - Archive of obsolete content
idebar ui mechanism for displaying jetpack content in a slide-out animated vertical column toolbar including entries and access elements into the toolbar panel a movable, expandable, and custom styled content element to display jetpack content tabs adding events and interacting with browser tabs and their contained documents statusbar low-level functions and basic calls notifications a system for alerting users via provided ui mechanisms selection interacting with user-selected content window mitigates and eases interactions between different browser windows ...
Enabling Experimental Jetpack Features - Archive of obsolete content
Archive › Mozilla › Jetpack › docs › Meta › Future
onality that foo yields to the script. in jetpack, we propse adding a new function to the base namespace called importfromfuture. methods import(stringmountpath string)imports the requested experimental feature into the script. stringmountpathstring that enumerates where, starting from the jetpack base, the feature will be mounted. to get a list of mount paths that are available, see the method below. string here is an example of how to import a feature (the clipboard) from the future. jetpack.future.import("clipboard"); the goal here is to be able to remove the jetpack.future.import() call when the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration). list() arrayreturns an array of the set of potenti...
Jetpack - Archive of obsolete content
jetpack jetpack is a project to make it easy to build firefox add-ons using common web technologies. ...
Mac OS X Build Prerequisites/fink - Archive of obsolete content
ent 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/autoconf. do not install the autoconf2.5 or autoconf2.54 packages. $ sudo apt-get install autoconf ...
Makefile.mozextension.2 - Archive of obsolete content
azine knowledge base (2005). note that the original makefile.mozextention merely repeats the steps in getting started with extension development - mozillazine knowledge base (2008). the same goes for this slight makefile rework here. ...
Message Summary Database - Archive of obsolete content
attributes, e.g., keywords. there are a set of generic property methods so that core code and extensions can set attributes on msg headers without changing nsimsghdr.idl.msg threads we store thread information persistently in the database and expose these object through the [nsimsgthread interface. so the db knows which messages are in a thread, which message a message is in reply to, etc. this allows us to store watch/ignore information on a thread object, and avoids having to generate threading information whenever a folder is open. this has arguably been more trouble than it's been worth, especially when we've threaded incorrectly. meta information the nsidbfolderinfo interface handles the folder meta data. this also supports generic properties. there is a method on nsimsgdatabase to get t...
Metro browser chrome tests - Archive of obsolete content
running the metro browser chrome tests to run mochitest, first build mozilla with your changes; then run ./mach mochitest-metro this will launch metro browser chrome tests in the default immersive browser. for information on setting your local build as the default, visit the windows 8 integration wiki page. it is possible to run individual tests as well. ...
Monitoring downloads - Archive of obsolete content
discouraged since it could be removed at any time. try to avoid using it.this interface is deprecated as of firefox 26. please use downloads.jsm instead. firefox 3 makes it easier than ever to monitor the status of downloads. although it was possible to do so in previous versions of firefox, it was previously only possible for one observer to do so at a time. firefox 3 introduces new api that allows any number of listeners to observe downloads. this article demonstrates how to monitor downloads in firefox 3, using the download manager. as a nice bonus, it also demonstrates how to use the storage api to issue sqlite commands on a database. the result is a window you can open by choosing "download log" in the tools menu, which lists all downloads that have been started since you installed th...
Overview of how downloads work - Archive of obsolete content
there are two ways of downloading files in mozilla. one way is to encounter a file with an unknown content type, the other is to choose "save link target as" from the context menu of a link. things like file|save page as, save image as, etc. are all part of the second codepath. this document describes both codepaths (see below for the second one). click on the images to display them "stand-alone" in the browser, which may resize them to fit the browser window. downloads via the helper app service this diagram is an uml sequence diagram, and was created using dia. get the .dia file here: mozilla_downloads.dia downloads via "save link target as" and friends this diagram is an uml sequence diagram, and was created using dia. get the .dia file here: mozilla_downloads_path2.dia ...
Plug-n-Hack Phase2 - Archive of obsolete content
the next phase of plug-n-hack (pnh) is still being planned but is intended to allow browsers to advertise their capabilities to security tools. this will allow the tools to obtain information directly from the browser, and even use the browser as an extension of the tool. if you are interested in working on this aspect then please get in touch. related links plug-n-hack overview ...
HostWindow - Archive of obsolete content
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. ...
Prism - Archive of obsolete content
p.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 for running web applications. using configuration file...
PyDOM - Archive of obsolete content
globals and namespaces this is taken from a mail to the pyxpcom list - it should be expanded, but a copy-paste will do for now normal module semantics don't exist here. the globals are 'bound' to the global object (i.e., the window), instead of to a module's __dict__ as you expect in the python world. note that we don't actually 'import' anything here - the scripts and event handlers do not exist in a python module. the intent is to provide similar semantics to js. for example, when a top-level window has something like: <window ... ...
Reading textual data - Archive of obsolete content
eam.init(istream); var chunk = scriptablestream.read(4096); var text = converter.converttounicode(chunk); however, you must be aware that this method will not work for character encodings that have embedded null bytes, such as utf-16 or utf-32. reading lines there is no easy, general way to read a unicode line from a stream. for the limited use case of reading lines from a local file, the following code using nsiscriptableunicodeconverter works. this code will not work for character encodings that contain embedded nulls such as utf-16 and utf-32 // first, get and initialize the converter var converter = components.classes["@mozilla.org/intl/scriptableunicodeconverter"] .createinstance(components.interfaces.nsiscriptableunicodeconverter); converter.charset = /* ...
Remote debugging - Archive of obsolete content
res quite a bit of trust, in both directions. the developer trusts that his time is not being wasted: the crash is a real bug in firefox. (that is, there's a legitimate reason it happens only on some computers, but that reason just hasn't been discovered.) the crash victim, in turn, trusts the developer with full access to his computer. a good place to start is a detailed stack (in gdb, use bt followed by bt full). there give more information about the stack than a breakpad crash report: not only the names of the functions on the stack, but also the values they were passed. core dump a core dump includes all of the memory of a crashed program. it allows you to see the crash in a debugger even after the program has long exited. transferring a core dump is tricky, because it is large and can c...
Running Windows Debug Builds Downloaded From Tinderbox - Archive of obsolete content
looking in at firefox.exe with http://www.dependencywalker.com/. unfortunately these dlls are not redistributable. ...
SpiderMonkey coding conventions - Archive of obsolete content
use the spidermonkey c++ coding style page on wikimo which is more up to date and the canonical source. the spidermonkey project owners enforce coding conventions pretty strictly during code reviews. naming conventions public function names begin with js_ followed by capitalized "intercaps", e.g. 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. but static native methods of js objects have lowercase, underscore-separated or intercaps names, e.g., str_indexof. and library-private and static data use underscores, not intercaps (but library-private data do use a js_ prefix). scalar type names are lowercase and js-prefixed: jsdouble. ag...
open - Archive of obsolete content
not be used when the file is not open. other methods, such as remove may not be used when the file is open. ...
File object - Archive of obsolete content
s for the file and blocks until any pending data has been committed to disk. file.seek() moves the file position pointer forward or backwards. file.read() read a fixed number of bytes from the file. file.readln() read line from the file. file.readall() read the entire file in, returning an array of lines. file.write() write bytes to the file. file.writeln() write bytes to the file, followed by a line separator, flushing the buffer if file.hasautoflush. file.writeall() writes an array of lines to the file, obeying the same semantics as writeln. file.list() get a list of files, potentially matching a regular expression filter, from the file. only has meaning when the file is a directory. file.mkdir() create a directory. directory will be created in the same directory as the fi...
String Quick Reference - Archive of obsolete content
function declarations what: use abstract classes instead of concrete classes when passing strings across function boundaries why: using abstract classes allows the caller to choose the storage mechanism, allowing for possible sharing or more efficient handling of string fragments. old way: use nsstring& and nscstring& void mymethod(const nsstring& input, nsstring& output); new way: use nsastring& and nsacstring& void mymethod(const nsastring& input, nsastring& output); substrings what: get direct references to string fragments why: avoid making multiple copies of the string old way: use a bunch of nsautostrings, and use left(), right() and mid() to grab a segment of a string: // get an 8-character string starting at the 4th position nsautostring leftside; str.left(leftside,...
Supporting per-window private browsing - Archive of obsolete content
channel into private mode usually, network channels inherit the privacy status of the document that created them, which means that they work correctly most of the time. however, sometimes you need to adjust the privacy status on a channel manually, for example, if you have created the channel directly yourself. you can use the nsiprivatebrowsingchannel interface for this purpose. the example below creates a channel to load a url, and forces it to be in private mode. var channel = services.io.newchannel("http://example.org", null, null); channel.queryinterface(components.interfaces.nsiprivatebrowsingchannel); channel.setprivate(true); // force the channel to be loaded in private mode similarly, xmlhttprequest objects created via createinstance(ci.nsixmlhttprequest) will often require explic...
Treehydra Build Instructions - Archive of obsolete content
this automatically builds treehydra for you. ...
Treehydra - Archive of obsolete content
treehydra is intended for precise static analyses. most of treehydra is generated by dehydra. a dehydra script walks the gcc tree node structure using the gty attributes present in gcc. treehydra is included in dehydra source, and is built when a plugin-enabled cxx is detected. ...
Using addresses of stack variables with NSPR threads on win16 - Archive of obsolete content
as one would imagine. with the speed of today's processors (even those running win-16), the copying of 10 - 50 kilobytes of data between two locations in memory is barely measurable 1. what is a hardship is that addresses of dynamic variables, those allocated on the call stack, in a function's local frame, are not valid across thread boundaries. ...
Venkman Internals - Archive of obsolete content
ttributes. scriptwrapper newsgroup, 2002, rgrinda here is a bit more information about how venkman tracks files and functions... a scriptwrapper is a pure js object defined only inside venkman. as you pointed out, there is a 1:1 relationship between scriptwrappers and functions. scriptwrapper has-a jsdscript property, which is an object which supports the jsdiscript interface. jsdiscript is a lower level access to the function than the scriptwrapper. in order to set a breakpoint in a particular function, you'll want to call scriptwrapper.setbreakpoint(pc[, parentbp]); where |pc| is the program counter location to set the breakpoint, and |parentbp| is an optional "future breakpoint" object to use as the parent for this breakpoint. if you set the breakpoint right from the jsdscript instead,...
When To Use ifdefs - Archive of obsolete content
itor/ui/ is built by the suite, standalone composer, and thunderbird, 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 ...
DOM Interfaces - Archive of obsolete content
ocument (the one on which the loadbindingdocument method was invoked). the binding document can then be modified programmatically using the dom. any subsequent bindings that are attached to elements within the document will be constructed from the modified binding document. parameters documenturl of type domstring - the url of a binding document. no return value example the following snippet checks to see if any anonymous child of "element" is itself an element. if (element.ownerdocument instanceof ci.nsidomdocumentxbl) { var anonchildren = element.ownerdocument.getanonymousnodes(element); if (anonchildren) { for (var i = 0; i < anonchildren.length; i++) { if (anonchildren[i].nodetype == 1) return false; } ...
XBL - Archive of obsolete content
in spirit to mozilla's xbl, but there are a few subtle (and not-so-subtle) differences. for example, names of the elements are different. also sxbl lacks some features of xbl, such as bindings inheritance and defining methods/properties on bound elements. xbl 2.0 (w3c candidate recommendation) was developed to address problems found in xbl 1.0 and to allow for implementations in a broader range of web browsers. in 2009 mozilla announced plans to implement xbl2 in future versions of gecko. some differences between sxbl and xbl2 are listed in an article by anne van ke ( seesteren (november, 2005). an overview of differences between mozilla xbl and x...
Mac stub installer - Archive of obsolete content
ng it from the miw.mcp codewarrior project. how we get setup to debug the xpinstall engine from the mac installer? once you have the mac installer built and ready to debug you may want to debug the xpinstall engine in the context of the installer rather than in the context of the browser. ...
InstallTrigger.installChrome - Archive of obsolete content
installtrigger.installchrome trigger scripts are typically invoked by javascript event handlers on hyperlinks. when a user clicks the link "install the new blue theme" in the example below, xpinstall downloads, registers, and installs the theme contained in newblue.xpi to the user's profile directory. <a href="#" onclick="installtrigger.installchrome( installtrigger.skin, 'http://wildskins/newblue.xpi', 'newblue/1.0');"> install the new blue theme</a> ...
Examples - Archive of obsolete content
examples trigger scripts and install scripts describes typical kinds of script that use the xpinstall api. ...
copy - Archive of obsolete content
dest a filespecobject object representing the destination directory. returns an integer error code. ...
dirCreate - Archive of obsolete content
dircreate creates a new directory. method of file object syntax int dircreate( filespecobject dirtocreate ); parameters the dircreate method has the following parameters: dirtocreate a filespecobject representing the pathname of the directory to create. returns an integer error code. for a list of possible values, see return codes. description the input parameter is a filespecobject that you have already created with the install object's getfolder method. the following simple example demonstrates the use of the dircreate method. note that the getfolder method does not require that the folder or directory you specify exist in order for the object reference to be a valid one. example f = getfolder("program", "mynewdirectory"); err = file.dircreate(f); ...
dirGetParent - Archive of obsolete content
dirgetparent returns an object representing the parent directory of the current directory or file. method of file object syntax filespecobject dirgetparent( filespecobject fileordir ); parameters the dirgetparent method has the following parameters: fileordir a filespecobject representing the pathname of the file or directory whose parent is being requested. returns a filespecobject if successful; null if not successful. example f = getfolder("program", "mynewdirectory"); err = file.dircreate(f); err = file.getparent(f) // returns "program" ...
dirRemove - Archive of obsolete content
dirremove removes a directory. method of file object syntax int dirremove( filespecobject dirtoremove [, boolean recursive] ); parameters the dirremove method has the following parameters: dirtoremove a filespecobject representing the directory to be removed. recursive an optional boolean value indicating whether the remove operation is to be performed recursively (1) or not (0). returns an integer error code. for a list of possible values, see return codes. ...
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
diskspaceavailable returns the amount of disk space available in bytes on the local disk. method of file object syntax double diskspaceavailable ( string nativefolderpath ); parameters the diskspaceavailable method has the following parameters: nativefolderpath a string representing the pathname of the partition, a file, or a directory on the partition whose space is being queried. returns a double number representing the amount of space, in bytes, on the queried drive. description use this function to make sure there is adequate space on the local disk for extracting and installing 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 disk...
execute - Archive of obsolete content
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. ...
exists - Archive of obsolete content
exists returns a value indicating whether the specified file or directory exists. method of file object syntax boolean exists( filespecobject target ) parameters the exists method has the following parameters: target a filespecobject representing the file or directory being tested for existence. returns a boolean value specifying whether the file or directory does indeed exist or does not. example f = getfolder( "program", "sample.txt" ); if ( file.exists(f) ) // do something with the file ...
isDirectory - Archive of obsolete content
summary returns a boolean value indicating whether the specified filespecobject is a directory. method of file object syntax boolean isdirectory ( filespecobject nativefolderpath ); parameters the isdirectory method has the following parameters: nativefolderpath a filespecobject representing the queried directory. returns a boolean value indicating whether the object is a directory or not. ...
isFile - Archive of obsolete content
summary returns a boolean value indicating whether the given filespecobject is a file. method of file object syntax boolean isfile (filespecobject nativefolderpath); parameters the isfile method has the following parameter: nativefolderpath a filespecobject representing the queried file object. returns a boolean value indicating whether the filespecobject is a file or not. example f = getfolder( "program", "sample.txt" ); if ( file.isfile(f) ) // the object represents a file ...
macAlias - Archive of obsolete content
filename a string representing the name of the file to be installed. aliasdir a filespecobject that represents the directory into which the alias file will be installed (e.g.,"mac desktop"). ...
modDate - Archive of obsolete content
returns a double number representing the date that the file was last modified. ...
modDateChanged - Archive of obsolete content
summary returns whether file has been modified since a certain date. method of file object syntax boolean moddatechanged (filespecobject asourcefolder, number anolddate); parameters the moddatechanged method has the following parameters: asourcefolder a filespecobject representing the file to be queried. anolddate a double representing the date. returns a boolean value indicating whether the file has been modified since the input date or has not. description most often, the date passed in as the second parameter in moddatechanged is the returned value from a moddate on a separate file, as in the following example, in which the dates of two files are compared. example filesource1 = getfolder("program", "file1.txt"); filesource2 = getfolder("...
move - Archive of obsolete content
dest a filespecobject representing the target directory. returns an integer error code. for a list of possible values, see return codes. description you must create a filespecobject for the destination directory to pass in for this function. ...
remove - Archive of obsolete content
summary deletes a specified file. method of file object syntax int remove( filespecobject file ) parameters the remove method has the following parameters: file a filespecobject representing the file to be removed. returns an integer error code. for a list of possible values, see return codes. ...
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. ...
size - Archive of obsolete content
summary return the size of the given file in bytes. method of file object syntax int size (string nativefolderpath); parameters the size method has the following parameters: nativefolderpath the full pathname to the file. returns a number representing the size, in bytes, of the queried file. ...
windowsGetShortName - Archive of obsolete content
returns a string with the windows shortname. ...
windowsRegisterServer - Archive of obsolete content
summary windowsregisterserver registers installed dlls with the windows registry. method of file object syntax int windowsregisterserver( object localdirspec ) parameters the windowsregisterserver method has the following parameters: localdirspec a filespecobject representing a directory obtained by getcomponentfolder or getfolder. returns an integer error code. for a list of possible values, see return codes. example filecdtool = getfolder("file:///", faod + "cdtool.dll"); err = file.windowsregisterserver(filecdtool); ...
windowsShortcut - Archive of obsolete content
summary creates a windows shortcut to the installed software. method of file object syntax int windowsshortcut( folderobject atarget, folderobject ashortcutpath, string adescription, folderobject aworkingpath, string aparams, folderobject aicon, number aiconid); parameters the windowsshortcut method has the following parameters: atarget a filespecobject representing the absolute path (including filename) to file that the shortcut will be created for. ashortcutpath a filespecobject representing the absolute path (not including filename) to where the shortcut is to be created. adescription string description for the shortcut to be used as the shortcut name with a .lnk extension (do not include .lnk in the string). aw...
init - Archive of obsolete content
min minor version number. rev revision number. bld build number. ...
toString - Archive of obsolete content
returns the major, 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. ...
addDirectory - Archive of obsolete content
an absolute pathname is used as specified. a relative pathname is appended to the registry name of the package as specified by the pa...
addFile - Archive of obsolete content
this parameter can be an absolute pathname, such as /royalairways/royalsw/executable or a relative pathname, such as executable. typically, absolute pathnames are only used for shared components, or components that come from another vendor, such as /microsoft/shared/msvcrt40.dll.typically, relat...
cancelInstall - Archive of obsolete content
ode ) parameters none. returns an integer error code. the optional argument is an error code that can be returned to the triggering page. for most purposes, it's recommended that one of the standard return codes be used. but a script can, in fact, return any valid integer. for a list of possible values, and any custom errorcode created by install writer, see return codes. example use the following code to abort or to finalize an installation, based on a variable you set earlier in your code: initinstall("royal airways tripplanner","/royalairways/ tripplanner","1.0.0.0"); ... err = getlasterror(); if (!err) performinstall(); else cancelinstall(err); ...
confirm - Archive of obsolete content
he constants above to have standard 'ok' and 'cancel' buttons. if you leave out abuttonflags, this is the default. std_yes_no_buttons: use this instead of the constants above to have standard 'yes' and 'no' buttons. warning: do not make 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. abu...
deleteRegisteredFile - Archive of obsolete content
returns an integer error code. ...
gestalt - Archive of obsolete content
returns returns the requested information. the format depends on the select code specified in the selector parameter. ...
getWinProfile - Archive of obsolete content
you create this object by passing a string representing the directory to the getfolder method. file a relative pathname to an initialization file in the directory specified by the folder parameter, such as "royal/royal.ini". ...
initInstall - Archive of obsolete content
the name of the software is displayed to the user. package the client version registry pathname for the software (for example: plugins/adobe/acrobat or /royalairways/royalpi/). it is an error to supply a null or empty name. the name can be absolute or relative. a ...
patch - Archive of obsolete content
typically, absolute pathnames are only used for shared components, or components that come from another vendor, such as /microsoft/shar...
performInstall - Archive of obsolete content
tions, 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. example use the following code to abort or to finalize an installation, based on a variable you set earlier in your code: initinstall("royal airways tripplanner", "/royalairways/tripplanner", "1.0.0.0"); ... err = getlasterror(); if (!err) performinstall(); else cancelinstall(err); ...
refreshPlugins - Archive of obsolete content
refreshplugins refreshes the list of plug-ins registered for the browser. method of install object syntax int refreshplugins( [ areloadpages ] ); parameters the refreshplugins method has the following parameter: areloadpages areloadpages is an optional boolean value indicating whether you want to reload the open web pages after you have refreshed the plug-in list. 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 th...
registerChrome - Archive of obsolete content
registerchrome registers chrome with the chrome registry. method of install object syntax int registerchrome( switch, srcdir, xpipath); parameters the registerchrome method has the following parameters: switch switch is the chrome switch indicating what type of file is being registered. skin is used to register skins, locale is used to register language packs. package, a third possibility is the equivalent of skin and/or locale, and ensures that everything in the xpi is registered. one final option for the switch parameter is delayed_chrome, which registers the switch only after a relaunch of the browser. note that you can combine switches as in the example below. srcdir srcdir is a filespecobject representing the source destination of the insta...
setPackageFolder - Archive of obsolete content
you create this object by passing a string representing the directory to the getfolder or getcomponentfolder method. returns none. description the setpackagefolder method to set the default package folder that is saved with the root node. ...
Methods - Archive of obsolete content
lugin as an extension. methods adddirectory unpacks an entire subdirectory. addfile unpacks a single file. alert displays an alert dialog box with a message and an ok button. cancelinstall aborts the installation of the software. confirm displays a confirm dialog box with the specified message and ok and cancel buttons. also allows custom button labels and a checkbox. deleteregisteredfile deletes the specified file and its entry in the client version registry. execute extracts a file from the xpi file to a temporary location and schedules it for later execution. gestalt retrieves information about the operating environment. (mac os only) getcomponentfolder returns an ...
Install Object - Archive of obsolete content
ers should see how to package a plugin as an extension. install use the install object to manage the downloading and installation of software with the xpi installation manager. overview the install object is used primarily in installation scripts. in all cases, the install object is implicit--like the window object in regular web page scripts--and needn't be prefixed to the object methods. the following two lines, for example, are equivalent: f = getfolder("program"); f = install.getfolder("program"); an installation script is composed of calls to the install object, and generally takes the following form: initialize the installation call initinstall with the name of the installation and the necessary registry and version information. add the files to the installation ...
Return Codes - Archive of obsolete content
in mozilla/seamonkey, these constants are defined as part of the xpinstall object (formerly the softwareupdate object in netscape communicator 4.5). name code explanation success 0 success. reboot_needed 999 the files were installed, but one or more components were in use. restart the computer and the application to complete the installation process. on windows nt, you may only need to restart the application as long as you did not replace operating system files. ...
getString - Archive of obsolete content
key the key in that section whose value to return. returns the value of the key or an empty string if none was found. description the getstring method is similar to the windows api function getprivateprofilestring. unlike that function, this method does not support using a null key to return a list of keys in a section. ...
writeString - Archive of obsolete content
key the key in that section whose value to change. value the new 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. ...
WinProfile Object - Archive of obsolete content
ould see how to package a plugin as an extension. winprofile (windows only) windows developers use this object to manipulate the content of a windows .ini file. overview this object does not have a public constructor. instead, you construct an instance of this object by calling the getwinprofile method of the install object. the two methods of the winprofile object, getstring and writestring, allow you to read and write the data in the key/value pairs of a windows .ini file. ...
createKey - Archive of obsolete content
classname usually an empty string. for information on this parameter, see the description of regcreatekeyex in your windows api documentation. returns 0 if it succeeded; a nonzero number if it failed to schedule the creation. for a list of possible values, see return codes. ...
deleteKey - Archive of obsolete content
deletekey removes a key from the registry. method of winreg object syntax int deletekey ( string subkey); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". returns 0 if it succeeded; a nonzero number if it failed to schedule the deletion. for a list of possible values, see return codes. ...
deleteValue - Archive of obsolete content
deletevalue removes the value of an arbitrary key. method of winreg object syntax int deletevalue ( string subkey, string valname); parameters the deletevalue method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair you want to remove. returns 0 if it succeeded; a nonzero number if it failed to schedule the deletion. ...
enumKeys - Archive of obsolete content
enumkeys enumerates the registry subkeys for the given key. method of winreg object syntax string enumkeys ( string key, int subkeyindex ); parameters the enumkeys method has the following parameters: key the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". subkeyindex an integer representing the 0-based index of the subkey being sought. returns the name if it succeeded; null if the referenced value does not exist. description enumkeys can be used to iterate through the subkeys at a given key location. the following example shows how to use enumkeys to find the plugins subdirectory below the various mozilla-based browser installations. var winreg = getwinregistry(); winreg.setrootkey(winreg.hkey_lo...
enumValueNames - Archive of obsolete content
enumvaluenames enumerates the value of a given key. method of winreg object syntax string enumvaluenames ( string key, int subkeyindex ); parameters the enumvaluenames method has the following parameters: key the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". subkeyindex an integer representing the 0-based index of the key value being sought. returns the value of the key as a string if it succeeded; null if the referenced subkey does not exist. description enumvaluenames can be used to iterate through the values for a given key. the following brief example retrieves a key value using this method. var winreg = getwinregistry(); winreg.setrootkey(winreg.hkey_local_machine); v1 = winreg.enumvaluenam...
getValue - Archive of obsolete content
valname the name of the value-name/value pair whose value you want. ...
getValueNumber - Archive of obsolete content
getvaluenumber gets the value of a key when that value is a number. method of winreg object syntax number getvaluenumber ( string subkey, string valname); parameters the getvaluestring method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair whose value you want. returns number value of the specified key or null if there's an error, the value is not found, or the value is not a string. ...
getValueString - Archive of obsolete content
valname the name of the value-name/value pair whose value you want. ...
isKeyWritable - Archive of obsolete content
iskeywritable returns whether the given registry key is writable or not. method of winreg object syntax boolean iskeywritable( string key); parameters the method has the following parameter: key a string representing the path to the key returns a boolean value: true if the key is writable; false if not. example winreg = getwinregistry(); if ( winreg != null ) { winreg.setrootkey ( winreg.hkey_local_machine ); if(winreg.iskeywritable("software")) { //iskeywritable returned true } else { //iskeywritable returned false } ...
keyExists - Archive of obsolete content
keyexists returns whether the key exists. method of winreg object syntax boolean keyexists ( string key); parameters the method has the following parameter: key a string representing the path to the key returns boolean value description if the user does not have read access to the given key, this will also return false. example winreg = getwinregistry(); if ( winreg != null ) { winreg.setrootkey( winreg.hkey_local_machine); if(winreg.keyexists("software\\mozilla")) { //keyexists returned true } else { //keyexists returned false } } ...
setRootKey - Archive of obsolete content
returns nothing. description the setrootkey changes the root key. when you create a winreg object, it is set to access keys under the hkey_classes_root portion of the registry. if you want to access keys in another portion, you must use this method to change the root key. on 16-bit windows platforms, hkey_classes_root is the only valid value and this method does nothing. ...
setValue - Archive of obsolete content
valname the name of the value-name/value pair whose value you want to change. ...
setValueNumber - Archive of obsolete content
valname the name of the value-name/value pair whose value you want to change. value a number representing the new string value. ...
setValueString - Archive of obsolete content
valname the name of the value-name/value pair whose value you want to change. value the new string value. returns 0 if it succeeded; a nonzero number if it failed to schedule the action. ...
valueExists - Archive of obsolete content
value a string representing the value being queried. returns boolean value: true if the key exists and the user has read access to it, otherwise false. ...
WinRegValue - Archive of obsolete content
winregvalue constructor (windows only) creates a winregvalue object. syntax winregvalue ( int datatype, byte[] regdata); parameters the winregvalue constructor takes the following parameter: datatype an integer indicating the type of the data encapsulated by this object. the possible values are: winregvalue.reg_sz = 1 winregvalue.reg_expand_sz = 2 winregvalue.reg_binary = 3 winregvalue.reg_dword = 4 winregvalue.reg_dword_little_endian = 4 winregvalue.reg_dword_big_endian = 5 winregvalue.reg_link = 6 winregvalue.reg_multi_sz = 7 winregvalue.reg_resource_list = 8 winregvalue.reg_full_resource_descriptor = 9 ...
XPJS Components Proposal - Archive of obsolete content
component manager and the js code. xjs components are not run in browser windows. each .js file (let's call it a module) is started up and run in the context of a relatively 'raw' js global object. the standard (non-dom) js classes will be available. the xpconnectcomponents object will be available. and some additional yet to be defined objects may be available. the xpconnectcomponents object allows access to the whole repository of native and js xpcom components, so this is not as isolated an environment as it might at first sound. a 'load' or 'import' function will also be provided to let the js code import other .js files where libraries of code might be stored. this is akin to 'static' libraries. accessing other components/services via xpcom/xpconnect is more akin to 'dynamic' librarie...
XTech 2006 Presentations - Archive of obsolete content
ty in 2006. work on this compiler and the new features of js2 is presented by the inventor of javascript. layout algorithm improvements for web user interfaces (slides, slides as one page) - david baron a discussion of problems with existing standards and potential improvements in two areas: layout systems for user interfaces (rather than documents) and mechanisms for reordering content to allow the author to use good 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ć t...
Flexgroup - Archive of obsolete content
when those elements have reached their maximum sizes, the elements with the next higher flexgroup are flexed. this process continues until there are no more elements remaining. ...
accelerated - Archive of obsolete content
...
accesskey - Archive of obsolete content
ey, the first of those characters in the label will be underlined. if a label doesn't have the specified character, the character will be appended to the label with parentheses. for example, when an accesskey of an 'open' label is 'a', the generated label will be 'open (a)'. however, if the last character of the label is an ellipsis or a colon, the accesskey text is inserted before them. this allows a label of 'open…' with an accesskey of 'a', to have a generated label of 'open (a)…'. similarly, when the label is 'your name:' and the accesskey is 'b', the generated label will be 'your name (b):'. it is recommended that you only use characters that appear in the label. however in some languages, for example, in japanese, characters will not always map directly to single keys, and it is...
align - Archive of obsolete content
for boxes that have horizontal orientation, it specifies how its children will be aligned vertically. for boxes that have vertical orientation, it specifies how its children will be aligned horizontally. start child elements are aligned starting from the left or top edge of the box. if the box is larger than the total size of the children, the extra space is placed on the right or bottom side. ...
button.type - Archive of obsolete content
if this attribute is not present, a normal button is created. leave the attribute out for a normal button. checkbox this type of button can be in two states. the user can click the button to switch between the states. this is not the same as a checkbox because it looks like a button. menu set the type attribute to the value menu to create a button with a menu popup. place a menupopup element inside the button in this case. the user may click anywhere on the button to open and close the menu. menu-button you can also use the value menu-button to create a button with a menu. ...
closemenu - Archive of obsolete content
auto this, the default value if the closemenu attribute is not specified, closes up the menu and all parent menus. ...
coalesceduplicatearcs - Archive of obsolete content
...
currentset - Archive of obsolete content
« xul reference home 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". this isn't necessary the *current* set, i.e. it might not be equal the value of the currentset property which is computed from the actual dom ...
datepicker.type - Archive of obsolete content
this is the default value so do not specify the type attribute if this kind is desired. grid a datepicker that displays a calendar grid where one month is shown at a time. popup a datepicker with three entry fields but an additional dropdown button, which, when pressed, will display a popup calendar grid. ...
dir - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › dir
normal for scales, the scale's values are ordered from left to right (for horizontal scales) or from top to bottom (for vertical scales) for other elements, the elements are placed left to right or top to bottom in the order they appear in the xul code. reverse for scales, the scale's values are ordered from right to left (for horizontal scales) or from bottom to top (for vertical scales). for other elements, they are placed right to left or bottom to top. this is reverse of the order in which they appear in the xul code. ...
disabled - Archive of obsolete content
disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. // disabling ...
drawintitlebar - Archive of obsolete content
« xul reference home drawintitlebar type: boolean if this attribute is true, the top of the window's content area will begin at the top edge of the title bar, instead of below the title bar. this allows the window to draw in the title bar. this is supported only from window elements, and is ignored on platforms that don't support drawing into the title bar. ...
droppedLinkHandler - Archive of obsolete content
« xul reference home droppedlinkhandler type: function this function is called when links are dropped to the browser element, with the following arguments. droppedlinkhandler(event, uri, name) -- firefox 51 or older droppedlinkhandler(event, links) -- firefox 52 or newer event -- drop event, or null if no event is available uri -- uri string of the dropped link name -- name string of the dropped link links -- array of the dropped items with nsidroppedlinkitem interface ...
editortype - Archive of obsolete content
this value will be overridden depending on the content type of the document in the editor. ...
equalsize - Archive of obsolete content
always for a horizontally oriented element, this will make all of its children have the width of the widest child. for a vertically oriented element, this will make its children all have the height of the tallest child. ...
eventnode - Archive of obsolete content
if this attribute is not specified, events are listened to from the tabbox. thus, if this attribute is not used, the tabbox or an element inside it must have the focus for the keyboard navigation to apply. parent keyboard navigation is captured at the parent of the tabbox. window keyboard navigation is captured at the window level. tab navigation will occur as long as any element in the window is focused. document keyboard navigation is captured at the document level. ...
events - Archive of obsolete content
« xul reference home events type: comma-separated list a comma-separated list of event names that the command updater will update upon. if this attribute is not specified, or you set it to the value '*', all events are valid. valid events are listed below, or you can use your own events. you can send a custom event by calling the updatecommands method of the command dispatcher. focus: occurs when the focused element changes. select: occurs when the selected text changed. clipboard: occurs when the clipboard is changed. undo: occurs when the undo buffer is changed. ...
flags - Archive of obsolete content
two flags are defined, which may be the value of this attribute. dont-test-empty: for template generated content, the builder will not check that a container is empty. dont-build-content: this flag may be used on a tree to indicate that content elements should not be generated. ...
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. ...
fullscreenbutton - Archive of obsolete content
« xul reference home fullscreenbutton type: boolean set this attribute to true to display a button 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. ...
hidespinbuttons - Archive of obsolete content
the value may still be adjusted with the keyboard. the default value is false. ...
homepage - Archive of obsolete content
it does not have any correlation with the user's browser homepage; instead it is a convenient property to hold a home page. ...
id - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › id
ton was pressed'); } </script> a more abstract version of the above would be a <button id="foo" label="click me" oncommand="setwidgetlabel(this, 'i was pressed')"/> <script> function setwidgetlabel(idname, newcaption){ document.getelementbyid( idname.id ).setattribute('label',newcaption) } </script> not specifying the id attribute for a window or a prefwindow fills the console with the following warning message: warning: empty string passed to getelementbyid() see also name ...
iframe.transparent - Archive of obsolete content
« xul reference hometransparenttype: one of the values belowset the background of an iframe as transparent.transparentthis results in the iframe's background being transparent. this can be used to workaround things like bug 540911 ...
maxlength - Archive of obsolete content
...
menuitem.type - Archive of obsolete content
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. ...
modifiers - Archive of obsolete content
multiple keys may be separated by spaces or commas. keys will map to other keys on platforms that do not have them. shift: the shift key. alt: the alt key. on the macintosh, this is the option key. on macintosh this can only be used in conjunction with another modifier, since alt+letter combinations are reserved for entering special characters in text. meta: the meta key. on the macintosh, this is the command key. control: the control key. os: windows logo key on windows, super or hyper key on linux. ...
multiline - Archive of obsolete content
...
newlines - Archive of obsolete content
« xul reference home newlines type: one of the values below how the text box handles pastes with newlines in them. possible values: pasteintact paste newlines unchanged pastetofirst paste text up to the first newline, dropping the rest of the text replacewithcommas pastes the text with the newlines replaced with commas replacewithspaces pastes the text with newlines replaced with spaces strip pastes the text with the newlines removed stripsurroundingwhitespace pastes the text with newlines and adjacent whitespace removed ...
notification.type - Archive of obsolete content
info a notification that is of lesser importance. warning a normal warning notification. ...
orient - Archive of obsolete content
the default value depends on the element. you can also use the -moz-box-orient style property. horizontal child elements of the element are placed next to each other in a row in the order that they appear in the xul source. vertical child elements of the element are placed under each other in a column in the order that they appear in the xul source. ...
pack - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › pack
for boxes with horizontal orientation, it is used to indicate the position of children horizontally. for boxes with vertical orientation, it is used to indicate the position of children vertically. the align attribute is used to specify the position in the opposite direction. you can also specify the value of pack using the style property -moz-box-pack. start child elements are placed starting from the left or top edge of the box. ...
panel.fade - Archive of obsolete content
« xul reference homefadetype: one of the values belowthe fade attribute, which may only be used with arrow panels, lets you set up a panel that will automatically fade away after a short time. the default is none. nonethe panels doesn't automatically fade away.slowthe panels slowly fades away after a short time.fastthe panels quickly fades away after a short time. ...
panel.level - Archive of obsolete content
if this attribute is not set, the popup window level depends on the platform. on linux, the default value is top, otherwise, the default value is parent. if a panel has one or more text fields, this attribute should not be set, otherwise ime or on-screen keyboard popups will appear incorrectly. for these reasons, you should avoid setting the level if not needed. top the panel is shown in front of all other normal windows, including those of other applications. ...
panel.type - Archive of obsolete content
autocomplete-richlistbox specify this for a panel that provides a richlistbox for an autocomplete element. arrow specify this for a panel that provides an arrow pointing at its anchor. drag specify this for a panel that's being used as a drag image for a drag and drop operation. otherwise leave this attribute out. ...
popup.position - Archive of obsolete content
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. ...
popupanchor - Archive of obsolete content
« xul reference homepopupanchortype: one of the values belowpopupanchor is an optional attribute for specifying where popup content should be anchored on the element.noneno anchortopleftanchor to the top left cornertoprightanchor to the top right cornerbottomleftanchor to the bottom left cornerbottomrightanchor to the bottom right cornersyntax<element popupanchor="none | topleft | topright | bottomleft | bottomright" /> example<element id="edit-context" popup="editor-popup" popupanchor="topleft" popupalign="bottomright" /> notesthe popupanchor attribute can be used to specify that the popup content should come up anchored to one of the four corners of the content object (e.g., the button popping up the content). if omitted, no anchoring occurs. instead the popup content comes u...
preference.type - Archive of obsolete content
bool a boolean set to either true or false. usually a checkbox would be connected to these preferences. int an integer string a string unichar a unicode string wstring a localized string. in this situation the preference will save the path to a property file which contains the actual value of the preference. file a file. ...
primary - Archive of obsolete content
...
progressmeter.mode - Archive of obsolete content
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. ...
query.type - Archive of obsolete content
« xul reference home type type: one of the values below the type of the parameter's value integer 32 bit integer int64 64 bit integer double double-precision floating-point number string string literal, the default value ...
rel - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › rel
equals the subject and value must match exactly. ...
resizeafter - Archive of obsolete content
« xul reference home 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 below the splitter resizes. grow the elements to the right or below the splitter do not change size (unless they are flexible) when the splitter is dragged, but instead the entire container changes size. flex the closest flexible element resizes. see also resizebefore ...
resizebefore - Archive of obsolete content
closest the element immediately to the left or above the splitter resizes. farthest the element that is the farthest away from the splitter to the left or above the splitter resizes. ...
resizer.dir - Archive of obsolete content
left resized to the left. right resized to the right. top resized up. bottom resized down. bottomstart resized down and toward the start of the line (toward the left for left-to-right locales, toward the right for right-to-left locales). bottomend resized down and toward the end of the line (toward the right for left-to-right locales, toward the left for right-to-left locales). bottomleft resized down and to the left. bottomright resized down and to the right. topleft resized up and to the left. ...
searchSessions - Archive of obsolete content
« xul reference home searchsessions obsolete since gecko 26 type: space-separated list of session names set to a keyword indicating what type of data to look up for autocomplete. you may set multiple types by separating their names by spaces. the following values are possible, although custom components may be installed which add others. history: the user's url history is searched. obsolete since gecko 3 addrbook: the user's address book is searched. obsolete since gecko 3 ldap: the user's ldap directories are searched. obsolete since gecko 25 ...
seltype - Archive of obsolete content
« xul reference home seltype type: one of the values below used to indicate whether multiple selection is allowed. single only one row may be selected at a time. (default in listbox and richlistbox.) multiple multiple rows may be selected at once. (default in tree.) for trees, you can also use the following values: cell individual cells can be selected text rows are selected; however, the selection highlight appears only over the text of the primary column. for richlistbox, this is new in firefox 3.5. ...
separator.orient - Archive of obsolete content
note that the values are the reverse of what seems more likely. horizontal the separator separates vertically placed elements. ...
sizemode - Archive of obsolete content
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. ...
sizetopopup - Archive of obsolete content
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. 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. ...
sortDirection - Archive of obsolete content
use the sortresource attribute to specify the sort key. ascending the data is sorted in ascending order. descending the data is sorted in descending order. ...
state - Archive of obsolete content
this attribute will be updated automatically as the splitter is moved, and is generally used in a stylesheet to apply a different appearance for each state. open the content either before or after the splitter, depending 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 - Archive of obsolete content
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. ...
textbox.autoFill - Archive of obsolete content
...
textbox.disableAutocomplete - Archive of obsolete content
...
textbox.forceComplete - Archive of obsolete content
...
textbox.ignoreBlurWhileSearching - Archive of obsolete content
...
textbox.minResultsForPopup - Archive of obsolete content
...
textbox.showCommentColumn - Archive of obsolete content
...
textbox.tabScrolling - Archive of obsolete content
...
textbox.type - Archive of obsolete content
« xul reference home type type: one of the values below you can set the type attribute to one of the values below for a more specialized type of textbox. don't set the type if you wish to use a regular textbox. autocomplete a textbox that supports 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 enteri...
toolbar.mode - Archive of obsolete content
« xul reference home mode not in seamonkey 1.x type: one of the values below how the toolbarbuttons on the toolbar are displayed. icons show only icons. text show only text. full show both. ...
treecell.editable - Archive of obsolete content
also useful for disabling editing of individual treecells. when the user double-clicks an editable cell, a text field appears in which the user can edit the contents of the cell. the tree and treecol must also be marked as editable in order for this to work. ...
treecell.mode - Archive of obsolete content
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. ...
treecol.editable - Archive of obsolete content
when the user double-clicks an editable cell, a text field appears in which the user can edit the contents of the cell. the tree must also be marked as editable in order for this to work. ...
treecol.type - Archive of obsolete content
the default is a text column that displays the content as text. checkbox the content of the columns are checkboxes. progressmeter the content of the columns are a progress meters. this is used in mozilla's download manager window. text the content of the columns is text. if you are using type="checkbox", then the tree and each treecol must be editable. you need to apply css to make the checkbox toggle. here is an example css style using the current theme's checkboxes: treechildren::-moz-tree-checkbox { /* unchecked checkbox treecells. ...
treecol.width - Archive of obsolete content
...
userAction - Archive of obsolete content
possible values: none the user is not interacting with the textbox. typing the user is typing into the textbox. ...
validate - Archive of obsolete content
« xul reference home validate type: one of the values below this attribute indicates whether to load the image from the cache or not. this would be useful if the images are stored remotely or you plan on swapping the image frequently. the following values are accepted, or leave out the attribute entirely for default handling: always the image is always checked to see whether it should be reloaded. never the image will be loaded from the cache if possible. ...
value - Archive of obsolete content
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 merely associate data with an element, you could 1) use another attribute like "value2" or "data-myatt" (as in the html5 draft), as xul does not require validation (less future-proof); 2) use setattributens() to put custom attributes in a non-xul namespace (serializable and future-proof); 3) use setuserdata() (future-proof and clean, but not easily serializable). ...
Attribute (XUL) - Archive of obsolete content
« xul reference home acceltext accessible accesskey activetitlebarcolor afterselected align allowevents allownegativeassertions alternatingbackground alwaysopenpopup attribute autocheck autocompleteenabled autocompletepopup autocompletesearch autocompletesearchparam autofill autofillaftermatch autoscroll beforeselected buttonaccesskeyaccept buttonaccesskeycancel buttonaccesskeydisclosure buttonaccesskeyextra1 buttonaccesskeyextra2 buttonaccesskeyhelp buttonalign buttondir buttondisabledaccept buttonlabelaccept buttonlabelcancel buttonlabeldisclosure buttonlabelextra1 buttonlabelextra2 buttonlabelhelp buttonorient buttonpack buttons checked checkstate clicktoscroll class closebutton closemenu coalesceduplicatearcs collapse collapsed c...
Deprecated and defunct markup - Archive of obsolete content
{many elements on this page are wrongly marked as deprecated, this page needs review} the following xul tags and attribute should be considered deprecated, if not defunct. the list below may include a few elements which are actually in use, but at a deeper level in the code. even some of the information on the tags below may be out of date, but is provided here for historical reference and to help anyone who comes across them in old code or documentation. elements <actions> (listed here by mistake or was it a container tag?) typo for <action> --neil 03 march 2011 <autorepeatbutton> (action occurs repeatedly on mouse hover--used to construct other elements; used in <arrowscrollbox> and large drop-down menus) so, not deprecated? --neil 03 march 2011 <bulletinboard> (made t...
close - Archive of obsolete content
note that the close event is only fired when the user presses the close button on the titlebar; (i.e. not file -> quit). the unload event should be used to capture all attempts to unload the window. general info specification xul interface event bubbles no cancelable no target window default action the window is closed. ...
findbar - Archive of obsolete content
ext" toolbar button in the findbar. findpreviousaccesskey type: string the access key for the "find previous" toolbar button in the findbar. highlightaccesskey type: string the access key for the "highlight" toolbar button in the findbar. matchcaseaccesskey type: string the access key for the "match case" checkbox in the findbar. ...
Menus - Archive of obsolete content
firefox menus element id description main-menubar the menubar element. ...
How to implement a custom XUL query processor component - Archive of obsolete content
emplating to create a block of content from a datasource query. the xul template guide has lots of detailed information on using xul templates. xul provides template query processors for rdf, xml and sql (mozstorage). the templating system also supports building custom query processors. custom query processors are xpcom components, must implement the nsixultemplatequeryprocessor interface and follow some conventions for when registering the component. in this example, we will create a simple javascript xpcom component. the component will hold a small array of javascript objects as its datasource. in practice, you would use your own custom source of data. here is an example of what our xul might look like when using a custom query processor: <?xml version="1.0"?> <?xml-stylesheet href="ch...
advance - Archive of obsolete content
Archive › Mozilla › XUL › Method › advance
« xul reference home advance( pageid ) return type: no return value call this method to go to the next page. this is equivalent to pressing the next button. the canadvance property must be set to true for the page to be changed. the code in the onwizardnext attribute is called before the page is changed. the pageid argument allows you to specify the index of the page to which to jump. supply null as the argument to go to the next page in the sequence. ...
loadURIWithFlags - Archive of obsolete content
« xul reference home loaduriwithflags( uri, flags, referrer, charset, postdata ) return type: no return value load a url into the document, with the specified load flags, the given referrer, character set, and post data. in addition to the flags allowed for the reloadwithflags method, the following flags are also valid: load_flags_is_refresh: this flag is used when the url is loaded because of a meta tag refresh or redirect. load_flags_is_link: this flag is used when the url is loaded because a user clicked on a link. the http referer header is set accordingly. load_flags_bypass_history: do not add the url to the session history. load_flags_replace_history: replace the current url in the session history with a new one. this flag might be used for a redirect. (see...
openSubDialog - Archive of obsolete content
the arguments are similar to the window's opendialog method except that the window name does not need to be supplied. the url should be a xul file. ...
reloadWithFlags - Archive of obsolete content
you may combine flags using a or symbol ( | ). load_flags_none: no special flags. the document is loaded normally. load_flags_bypass_cache: reload the page, ignoring if it is already in the cache. this is the flag used when the reload button is pressed while the shift key is held down. ...
showPopup - Archive of obsolete content
pens a popup element. there are two ways of specifying where the popup appears, either at a specific screen position, or relative to some element in the window. if either x or y are set to values, the popup will appear at the screen coordinate (x,y). if x and y are -1, the popup will be positioned relative to the element specified as the first argument. this is what you might do to show a popup below a button, for example. in this latter case, the anchor and align arguments may be 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 ...
ContextMenus - Archive of obsolete content
/> <textbox/> </row> </rows> </grid> the same context menu can be attached to multiple elements. just set the context attribute on those elements you want the context menu to apply to. one technique is to attach a context menu to an entire document area. for instance, the firefox browser applies a single context menu to the browser area which displays web pages. for example, the following will attach a context menu with the id 'contentareacontextmenu' to a browser element: <browser context="contentareacontextmenu"> indicating the default item on some platforms, one of the items in a context menu is marked as being a default operation. typically, this will cause the menuitem's label to appear in the context menu in bold. what constitutes the default item isn't specified, but...
Special per-platform menu considerations - Archive of obsolete content
some menu items have specific common labels or locations where certain menu items would go that differ on each platform. for instance, on windows, the menu item which exits the application is labeled "exit" and is normally placed at the end of the file menu. ...
builderView - Archive of obsolete content
« xul reference builderview type: nsixultreebuilder a reference to the tree builder which constructed the tree data. the builder provides access to the rdf resources for each row in the tree, and allows sorting the data by column. in newer versions of mozilla, the builderview property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in javascript. this property is read-only. ...
buttons - Archive of obsolete content
this button will also be the default button. cancel: the cancel button which will cancel the operation. help: a help button for displaying help about the dialog. disclosure: a button to show more information. this might be a button or a disclosure triangle. extra1: an optional additional button. ...
canAdvance - Archive of obsolete content
« xul reference canadvance type: boolean this property is set to true if the user can press the next button to go to the next page. if this property is false, the user cannot navigate to the next page. set this property to true to indicate that the user can go to the next page. set to false to disallow moving to the next page. this has the effect of enabling or disabling the next button, or, on the last page of the wizard, the finish button. ...
canRewind - Archive of obsolete content
this has the effect of enabling or disabling the back button. ...
currentSet - Archive of obsolete content
« xul reference currentset not in seamonkey 1.x type: comma-separated list of strings holds a comma-separated list of the ids of the items currently on the toolbar. for spacers, separators, and flexible spacers the following strings are used instead of ids: "spacer", "separator", "spring". an empty toolbar has a currentset value of "__empty". you may change the current set of items by setting this property. be careful, as setting this property doesn't automatically update the currentset attribute. ...
editortype - Archive of obsolete content
this value will be overridden depending on the content type of the document in the editor. html an html editor. ...
is24HourClock - Archive of obsolete content
this value is determined from the user's locale. ...
maxLength - Archive of obsolete content
...
view - Archive of obsolete content
Archive › Mozilla › XUL › Property › view
« xul reference 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. ...
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...
Notes - Archive of obsolete content
implementing an nsicommandlinehandler on windows may trigger a bug that causes an error message ("windows cannot find the file specified") to be displayed when opening external links (like from a shortcut or from an external application). deleting the "(default)" values in the following registry keys will fix this: hkey_classes_root\http\shell\open\ddeexec hkey_classes_root\https\shell\open\ddeexec you can also do this from within your xpcom component using windows registry interface. some more links on the matter: a mozillazine post. a blog post. ...
statusbarpanel-menu-iconic - Archive of obsolete content
« xul reference home statusbarpanel-menu-iconic use this class to have an image appear on the statusbarpanel, and also allow a popup menu. specify the image using the src attribute, and place a menupopup element inside the statusbarpanel. the image will appear instead of the label. ...
Additional Template Attributes - Archive of obsolete content
to use this technique, place a template attribute on the root element set to the id of a template. ...
Building Hierarchical Trees - Archive of obsolete content
<rule> <treechildren> <treeitem uri="rdf:*"> <treerow> <treecell label="rdf:http://purl.org/dc/elements/1.1/title"/> </treerow> </treeitem> </treechildren> </rule> </template> </tree> the first rule is for the houses as indicated by the rule's condition and the second rule is for the streets. as shown in the snippet of the data below, the street is a seq, so it will become a container. the houses are not containers, so they will not have children in the tree. <rdf:bag rdf:about="http://www.xulplanet.com/rdf/myneighbourhood"> <rdf:li> <rdf:seq rdf:about="http://www.xulplanet.com/rdf/marion" dc:title="marion street"> the result is a two level tree with two columns. for an xml source, a container is a node...
Introduction - Archive of obsolete content
some other systems call this databinding. effectively, xul templates are the xul way of doing databinding. ...
Namespaces - Archive of obsolete content
xml namespaces can be used in xul templates by binding the namespace uri and prefix to the template element. ...
SQLite Templates - Archive of obsolete 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. ...
Static Content - Archive of obsolete content
tside 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 builder would then just create a menupopup, but it doesn't. instead, it looks to see if a menupop...
Using Multiple Queries to Generate More Results - Archive of obsolete content
generate another set of results. if a result from the second query wasn't also matched by the first query, it will have content created for it. recall that when the member resource for a query matches several rules, only the earliest query that matches will have content generated for it. if resources don't overlap, we can generate content for two different parts of the rdf data. ...
Using Recursive Templates - Archive of obsolete content
ime, the query generates a result for each person in the xml source. the content of the action body is again generated for each result, but instead of being inserted inside the outermost groupbox, this new content is inserted inside the content generated from the previous iteration. the content is always inserted directly inside the element with the uri attribute. the result is output like the following: <groupbox> ... <vbox id="row2" container="true" empty="false" class="indent"> <label value="male"/> <vbox id="row4" class="indent"><label value="napoleon bonaparte"/></vbox> <vbox id="row5" class="indent"><label value="julius caesar"/></vbox> <vbox id="row6" class="indent"><label value="ferdinand magellan"/></vbox> </vbox> <vbox id="row3" container="true" empty="false"...
Template Guide - Archive of obsolete content
interwiki language links ...
Toolbars - Archive of obsolete content
documentation xul school: adding toolbars and toolbar buttons a helpful tutorial to creating toolbars and toolbar buttons. toolbar customization events a look at the events that are sent during toolbar customization; you can use these to be kept aware of changes to toolbars. ...
Accesskey display rules - Archive of obsolete content
.properties file or something. then, you should provide a way for specifying accesskeys which are independent from their labels. note that using '&' in label text is bad way. because japanese localizers "&cancel" need to localize to "キャンセル(&c)". this label will be displayed as "キャンセル(c)(c)" on the localized build. so, "(c)" will be doubled. for this issue, we recommend the following format if you use .properties: <command-name>.label=cancel <command-name>.accesskey=c note that apis of nsipromptservice are using the bad way. because the apis are already frozen. therefore, xul toolkit removes accesskey text before setting the label to the buttons. however, xul application developers should not make same mistake. ...
Features of a Window - Archive of obsolete content
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 always appear behind other windows. alwaysraised the window will alw...
More Wizards - Archive of obsolete content
f a field is invalid, you might display an alert. in some cases, it would be more convenient to disable the next button until valid input has been entered. the wizard has a property canadvance, which can be set to true to indicate that the next button should be enabled. if set 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="chro...
Open and Save Dialogs - Archive of obsolete content
it is most commonly used for the open and save menu commands, but you can use it any place in which the user needs to select a file. the xpcom interface nsifilepicker is used to implement a file picker. note that the file picker only works from chrome urls. you can use the file picker in one of three modes: open - the user is asked to select a file for opening. get folder - the user is asked to select a folder (directory). ...
Scroll Bars - Archive of obsolete content
, we'll discuss creating a stand-alone scroll bar. the user will set the value by adjusting the scroll bar. you probably won't use this too often. a scroll bar is made up of several parts: the slider, which is the main part of the scroll bar with the adjustable box, and the two arrow buttons on the end. a scroll bar creates all of these elements automatically. the syntax of a scroll bar is as follows: <scrollbar id="identifier" orient="horizontal" curpos="20" maxpos="100" increment="1" pageincrement="10"/> the attributes are as follows: id the unique identifer of the scroll bar orient this specifies the direction of the scroll bar. the default is horizontal, which creates a scroll bar that extends from left to right. you can also specif...
Simple Menu Bars - Archive of obsolete content
« previousnext » in this section, we'll see how to create a menu bar with menus on it. creating a menu xul has a number of different ways of creating menus. the most basic way is to add a menu bar with a row of menus on it like many applications have. you can also create popup menus. the menu features of xul consist of a number of different elements which allow you to create menu bars or popup menus. the items on the menus can be customized quite easily. we've already seen part of how to make menus using the menulist. this section will build on that. menu bars are usually created much like a toolbar. the menu bar can optionally be placed inside a toolbox and the menu would work just like any other toolbar. xul does have some special elements which provide special function...
Toolbars - Archive of obsolete content
lbar buttons to the toolbar palette, rather than adding them directly to the toolbar. for more information about customizable toolbars, see creating toolbar buttons. our find files example let's add a toolbar to the find files dialog. we don't really need one but we'll add one anyway to demonstrate its use. two buttons will be added, an open button and a save button. presumably, they would allow the user to save search results and re-open them later. <vbox flex="1"> <toolbox> <toolbar id="findfiles-toolbar"> <toolbarbutton id="opensearch" label="open"/> <toolbarbutton id="savesearch" label="save"/> </toolbar> </toolbox> <tabbox> a toolbar with two buttons has been added here. in the image, you can see them appear horizontally along the top. notice...
XBL Inheritance - Archive of obsolete content
g button code. any binding can be extended with another. the child binding can add properties, methods and event handlers. the child binding will have all the features it defines in addition to the features from the binding it inherits from (and any that binding inherits from and so on up the tree). to extend an existing binding, add an extends attribute on to the binding tag. for example, the following binding creates a textbox which adds the text 'http://www' to the beginning of its value when the f4 key is pressed. example 1 : source <binding id="textboxwithhttp" extends="chrome://global/content/bindings/textbox.xml#textbox"> <handlers> <handler event="keypress" keycode="vk_f4"> this.value="http://www"+value; </handler> </handlers> </binding> the xbl here extend...
Using nsIXULAppInfo - Archive of obsolete content
or example, for extensions that support several mozilla-based applications or several versions of a single application. this is not useful for scripts on webpages, which should continue using the navigator object when it's not possible to rely on feature-detection. nsixulappinfo interface to distinguish between different mozilla-based applications, use the frozen nsixulappinfo interface. the following sections provide a few examples of using nsixulappinfo from javascript. note that while firefox 1.5, thunderbird 1.5, and xulrunner 1.8-based applications support nsixulappinfo, older applications, such as firefox and thunderbird 1.0, do not support it. you'll need to have additional code for those older versions. getting nsixulappinfo to get a component implementing nsixulappinfo use this ...
Using the standard theme - Archive of obsolete content
. meaning, some internal default will be applied, which does by no means correspond to the standard theme (the theme currently chosen by the user in the theme selector), or even the default theme delivered with your the base application. applying the standard theme in order to use the theme currently chosen by the user of the base application (the so called "global skin"), you have to add the following line to your xul file: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> this imports the styles found in the <tt>global/skin</tt> chrome directory and will make the standard xul widgets of your application use the selected chosen theme. 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 go...
XULBrowserWindow - Archive of obsolete content
see the linked interfaces for the definition of the implemented methods. you may also wish to refer to the implementation of xulbrowserwindow in browser/base/content/browser.js. ...
Accessibility/XUL Accessibility Reference - Archive of obsolete content
/> <menuitem label="<!--option2-->" selected="true" /> <menuitem label="<!--option3-->" /> </menupopup> </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. progressmeter <progressmeter mode="determined" value="10" /> as progress advances, jaws indicates percentage to the user radio see radiogroup radiogroup <label value='<!--radio group-->' control='radioid' /> <radiogroup id='radioid'> <radio selected="true" label='<!--option1-->' /> <radio l...
XUL and RDF - Archive of obsolete content
wo-fold. the first section of the document describes the motivation and reasoning behind using rdf as the foundation of xul. this section makes a technical argument both for having xul in the first place and for using rdf as the underlying implementation of xul's content model. the second section describes the xul/rdf architecture itself and outlines enhancements to the xul language in order to allow the markup language to reference local data and to indicate how and when it would like to be annotatable with local data. ...
menubar - Archive of obsolete content
ement, the label on the statusbar will update to the statustext of the items on the menu as the user moves the mouse over them. properties accessibletype type: integer 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. ...
notification - Archive of obsolete content
ox's removetransientnotifications method does 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 ...
prefpane - Archive of obsolete content
ata events paneload this event is fired on the pane element when the pane is fully loaded (e.g. after the overlay is merged.) you can put the handler for this event in the onpaneload attribute on the element. using multiple prefpanes note that when using multiple prefpanes in the same prefwindow, you must not put the <script> elements above the prefpane elements, but instead below them. otherwise the dialog will show erratic behavior and not display correctly. place the <script> tags as in the following example for preference dialogs to work correctly: <prefwindow> <prefpane id="panegeneral" label="general"> ... </prefpane> <prefpane id="panesecurity" label="security"> ... </prefpane> <script type="application/javascript" src="chrome://myext/content/scr...
rule - Archive of obsolete content
Archive › Mozilla › XUL › rule
one or more child elements. parent type: element tag name if set, the rule will only match the corresponding tag. this may be used to have separate rules for leaf and container nodes 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. ...
tabbox - Archive of obsolete content
if this attribute is not specified, events are listened to from the tabbox. thus, if this attribute is not used, the tabbox or an element inside it must have the focus for the keyboard navigation to apply. parent keyboard navigation is captured at the parent of the tabbox. window keyboard navigation is captured at the window...
tabs - Archive of obsolete content
Archive › Mozilla › XUL › tabs
disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. in the case of form elements, it will not be submitted. do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case. the disabled attribute is allowed only for form controls. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. 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. onclose...
toolbox - Archive of obsolete content
<toolbarbutton label="back"/> <toolbarbutton label="forward"/> <toolbarbutton label="home"/> </toolbar> <toolbar> <toolbarbutton label="stop"/> <toolbarbutton label="reload"/> </toolbar> </toolbox> <textbox multiline="true" value="we have two toolbars inside of one toolbox above." width="20"/> </window> 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, sortd...
treeitem - Archive of obsolete content
attribute should be placed on the element where content generation should begin. thus, it should be placed on an element that is a descendant of a template. the value should be set to rdf:*. 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. ...
wizardpage - Archive of obsolete content
ges has a next attribute, all of the pages should have one, except that last page. pageid type: string wizardpage id this attribute should be set to a string that identifies the page's 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. ...
Custom app bundles for Mac OS X - Archive of obsolete content
on 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. ...
Dialogs in XULRunner - Archive of obsolete content
. 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; var fp = components.classes["@mozilla.org/filepicker;1"].crea...
XULRunner FAQ - Archive of obsolete content
e development tools (the ajax toolkit framework, for example). in the future there will be a xulrunner developer kit which will contain various development tools. how does xulrunner compare to other runtimes like java or .net (or python or ...)? the goal of xulrunner is to facilitate development and deployment of internet applications. it is not meant to be a full-featured runtime; this allows xulrunner to maintain a smaller footprint and simpler deployment strategy than generic full-featured runtimes. if i use xulrunner do i have to write my application in xul? no! you can write your application in any language supported by the mozilla web platform, including html, xhtml, svg, or xul. so why is it called xulrunner, instead of htmlrunner or something? xul was always th...
XULRunner Hall of Fame - Archive of obsolete content
pensource tool for making diagrams and gui prototyping that everyone can use. source qiqqa research manager, reference manager, and pdf manager. xulrunner is embedded to provide automatic search against journal archives, automatic acquisition of bibtex information, and automatic downloading of pdfs. slimerjs slimerjs is a xulrunner application that can be launched with firefox, allowing to execute an external javascript script which can manipulate web content. its goal is to provide a tool like phantomjs, with the same api, except that it runs gecko instead of webkit, and it is not headless (but you can still use xvfb to have a headless slimerjs). sqlite manager manage all your sqlite databases using this lightweight extension for firefox, thunderbird, seamonkey, ...
How to enable locale switching in a XULRunner application - Archive of obsolete content
.setattribute("label", locale); if (locale == selectedlocale) { // is this the current locale? selecteditem = listitem; } localelistbox.appendchild(listitem); } // highlight current locale localelistbox.selecteditem = selecteditem; } catch (err) { alert (err); } 4. code to update the locale user preference and restart the application mozilla xulrunner doesn't allow runtime switching of the locale, therefore the application must be restarted to activate the new choice. here is an example event handler which is fired when the user clicks on the button to change the locale. it saves the new locale to the user application preferences (thereby overriding the default prefs.js above) and then asks xulrunner to restart. function changelocale() { try { // which ...
MacFAQ - Archive of obsolete content
e. ...
Make your xulrunner app match the system locale - Archive of obsolete content
any of the locale specific resources are loaded. democracy does this by creating a command line handler called democracyclh, and then creating a new object of our pybridge component. the code described lives in the pybridge component's onstartup method which gets called automatically. the second step is to figure out the system locale. to be finished later. then set the locale preference. the following is python code to set this preference. from xpcom import components ps_cls = components.classes["@mozilla.org/preferences-service;1"] ps = ps_cls.getservice(components.interfaces.nsiprefservice) branch = ps.getbranch("general.useragent.") branch.setcharpref("locale", lang) i also set the language environment variable to match the system locale so that python's gettext functionality will work...
Opening a Link in the Default Browser - Archive of obsolete content
"] .getservice(components.interfaces.nsiexternalprotocolservice); // now, open it! extps.loaduri(uritoopen, null); by default, the external protocol service will warn the user about opening the link in another application. to suppress this warning for particular protocols that are safe to open in the default application, you must set default prefs (thunderbird sets the following prefs): // suppress external-load warning for standard browser schemes pref("network.protocol-handler.warn-external.http", false); pref("network.protocol-handler.warn-external.https", false); pref("network.protocol-handler.warn-external.ftp", false); you can also check whether an external handler for a scheme exists. this is how you do it: var extps = components.classes["@mozilla.org/urilo...
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 ...
Using Crash Reporting in a XULRunner Application - Archive of obsolete content
xulrunner application authors who wish to use crash reporting must run a crash reporting server. please see the socorro project for more information. to enable crash reporting on the client, set the following items in application.ini: [crash reporter] enabled=true serverurl=https://your.server.url/submit note: because crash reports can contain private data including passwords, in production environments they should only be sent via https. ...
XUL Application Packaging - Archive of obsolete content
rchive with the extension .xulapp or .xpi. they can be installed to xulrunner with a command line flag "--install-app" if xulrunner is registered on the system. see command line options for more details. note: for instructions on deploying your applications see deploying xulrunner. application.ini the application.ini manifest is located at the root of the extension and provides metadata that allows xulrunner to launch the application properly. it is parsed as a windows-style ini file with [headings] and key=value pairs. lines beginning with ; or # are treated as comments. a sample application.ini file can be found in the mozilla source tree. the [app] section the app section specifies metadata about the application name specifies the application name. required name example: na...
toolkit.defaultChromeFeatures - Archive of obsolete content
see also: xulrunner:specifying startup chrome window, dom:window.open, toolkit.defaultchromeuri, toolkit.singletonwindowtype. ...
toolkit.defaultChromeURI - Archive of obsolete content
type: string specified by: default prefs of xulrunner applications default: none example: pref("toolkit.defaultchromeuri", "chrome://myapp/content/"); the toolkit.defaultchromeuri preference allows simple xulrunner-based applications to open a new window when the application is launched. the preference specifies the uri of a chrome window to be opened. see also: xulrunner:specifying startup chrome window, toolkit.defaultchromefeatures, toolkit.singletonwindowtype. ...
XULRunner - Archive of obsolete content
getting started with xulrunner a short introduction to xulrunner. xulrunner is a mozilla runtime package that can be used to bootstrap xul+xpcom applications that are as rich as firefox and thunderbird. it provides mechanisms for installing, upgrading, and uninstalling these applications. xulrunner also provides libxul, a solution which allows the embedding of mozilla technologies in other projects and products. releases until version 41, xulrunner could be downloaded from ftp.mozilla.org. firefox (from version 3) ships with a private xulrunner package, which can run any compatible xulrunner application using the -app switch: firefox -app application.ini is equivalent to xulrunner -app application.ini older builds are also available. overv...
xbDesignMode.js - Archive of obsolete content
erg <doron@netscape.com> (original author) * * * * ***** end license block ***** */ /* xbdesignmode a javascript wrapper for browsers that support designmode */ function xbdesignmode(aiframe){ this.meditordocument = null; this.miframeelement = null; // argument is a string, therefore an id if ( (typeof(aiframe) == "string") && (document.getelementbyid(aiframe).tagname.tolowercase()=="iframe") ){ this.miframeelement = document.getelementbyid(aiframe); } else if( (typeof(aiframe)=="object") && (aiframe.tagname.tolowercase() == "iframe") ){ this.miframeelement = aiframe; } else { throw "argument isn't an id of an iframe or an iframe reference"; } if (this.miframeelement.contentdocument){ // gecko this.meditordocument = this.miframeelement.c...
Mozilla.dev.apps.firefox-2006-10-06 - Archive of obsolete content
summary: mozilla.dev.apps.firefox - september 30 - october 6, 2006 announcements vista compatibility lab mike schroepfer announced the current work being done testing mozilla products with vista. a wiki and irc channel have been created to track their progress. discussions firefox trunk and rc1 slowdown using tabs discussion regarding certain theme components (specifically alpha-transparency) creating a high cpu load on os/2. title case capitalization rules in firefox discussion regarding rules for capitalizing the first letter of firefox menu items in the ff ui. engineering student project - industry coach paul betts from ohio state university is looking for someone from mozilla to be his "industry coach" for engineering 494 - how great ideas turn into great products. mozil...
2006-10-06 - Archive of obsolete content
summary: mozilla.dev.apps.firefox - september 30 - october 6, 2006 announcements vista compatibility lab mike schroepfer announced the current work being done testing mozilla products with vista. a wiki and irc channel have been created to track their progress. discussions firefox trunk and rc1 slowdown using tabs discussion regarding certain theme components (specifically alpha-transparency) creating a high cpu load on os/2. title case capitalization rules in firefox discussion regarding rules for capitalizing the first letter of firefox menu items in the ff ui. engineering student project - industry coach paul betts from ohio state university is looking for someone from mozilla to be his "industry coach" for engineering 494 - how great ideas turn into great products. mozil...
2006-10-26 - Archive of obsolete content
g since 20-oct-2006 17:45 pdt? tony inquires why tinderbox is showing that the fx 1.5.0.x (linux) has failed since october 20. gavin replies that "[t]he log file shows a "no space left on device" error when trying to link the final executable." learn the traffic magic 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 ...
2006-10-27 - Archive of obsolete content
g since 20-oct-2006 17:45 pdt? tony inquires why tinderbox is showing that the fx 1.5.0.x (linux) has failed since october 20. gavin replies that "[t]he log file shows a "no space left on device" error when trying to link the final executable." learn the traffic magic 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 ...
2006-11-10 - Archive of obsolete content
ow to change the font of a web page before it is displayed using an extenstion. favicon as microsummary/feed/other stuff indicator suggestion about making the favicon create a bookmark for the page with a microsummary. firefox 2.0 - net accessed when bookmark properties viewed question about whether firefox 2.0 downlads the web page again when the properties of the bookmark are viewed. followed by a discussion whether this is an improvement. what is the build date for firefox 2? quesiton about why a user using firefox 2 rc3 didn't get a prompt for updating to firefox 2 after the release date. improving the ue for content control suggestion about how to improve user experience with options controlling the appearance of web content. popup blockers..window handlers inquiry of...
2006-11-24 - Archive of obsolete content
they would like to discuss the use of it in bug 361026 rich results for searches a proposal for a search tool that gives users a quicker path to specific information they are looking for. ...
2006-12-01 - Archive of obsolete content
leted. mozstorage documentation up a revisted discussion surround the mozstorage documentation. rich results for searches a proposal to implement "rich results", a set of registered sites that would provide information as it relates to a user's search. windows dde shell integration removal a call for responses or concerns regarding the removal of the dde shell integration. how do allow an internal web site to have universalbrowserwrite? a question regarding having an internal website use universalbrowserwrite on a local intranet. developping microsummary generator questions and discussion surrounding microsummaries in ff 2.0. applying extensions question regarding the proper application of ff extensions. finding out how blur() works... question regarding how to acc...
2006-11-03 - Archive of obsolete content
suggestion made for e-mail popup it suggested that the e-mail popup duration should depends on number of messages and examples of this idea is provided. xul overlay question -- how to replace an existing element? no respond thus far. links in tb is not sent to firefox directly cédric corazza provided a code solution for this problem. bug found in nslocalmailfolder.cpp david bienvenu is following up on this bug. meetings calendar project weekly status meeting - 2006/11/01 17:00 utc (meeting notes) calendar project weekly qa chat - 2006/11/02 16:30 utc (meeting notes) ...
2006-11-10 - Archive of obsolete content
. 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 section. benjamin smedberg has been "working on some xptcall refactoring which will allow us to expose xptcall via a frozen api (and c linkage)". he is looking for xptcall port maintainers to submit patches to bug 349002. matthew gertner wants to know...
2006-11-17 - Archive of obsolete content
alex vincent ran into some difficulty with xulrunner extension manager not recognizing xulwidgets for verbosio? however he found out that it was a result of his flat-chrome version of xul widgets and works fine with the jarred-chrome version. ...
2006-18-24 - Archive of obsolete content
please see mozilla.dev.platform faq for solution. meetings no meetings this week ...
2006-10-20 - Archive of obsolete content
they must be first saved to the drive. ...
JS-Engine FAQ - Archive of obsolete content
d fix the problem. after applying that patch, recompile js and define js_use_only_nspr_locks in the build. spidermonkey library loading mechanism? to write wrappers in pure javascript to interface with any c library on the system there are mechanisms such as xpcshell, wxjs, 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.
2006-10-27 - Archive of obsolete content
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 currently used for printing, but should or could have been used for print previews and multiple views in editors. meetings none t...
2006-11-10 - Archive of obsolete content
source code so that images could be blocked in mozilla. this can be defined within the nsicontentpolicy. applying site- and page-specific settings during layout discussion on the best possible solution for integrating firefox 3 with the ability to apply site- and page-specific user settings during layout. the idea of using a single sheet and the per-site selectors that dbaron implemented would allow for a quick proof of concept. the pro's and con's of using a single sheet was discussed. meetings none this week. ...
2006-12-24 - Archive of obsolete content
summary: mozilla.dev.tech.layout november 24 -december 1, 2006 announcements none this week. discussions [reset issue for overflow='hidden' in ie and opera there is a very modest horizontal shift of the document due to reflow associated with the removal of the vertical scroll bar (because the document content is using a horizontal centering style). but in firefox the document is reset (shifted both horizontally and vertically) to its 0,0 position before being centered horizontally. ...
2006-12- 02 - Archive of obsolete content
summary: mozilla.dev.tech.layout - november 24 2006 - december 2, 2006 announcements none this week. discussions [reset issue for overflow='hidden' in ie and opera there is a very modest horizontal shift of the document due to reflow associated with the removal of the vertical scroll bar (because the document content is using a horizontal centering style). but in firefox the document is reset (shifted both horizontally and vertically) to its 0,0 position before being centered horizontally. ...
2006-12- 08 - Archive of obsolete content
summary: mozilla.dev.tech.layout - december 2, 2006 - december 8, 2006 announcements none this week. discussions [further computesize changes l. david baron is planning to make an additional change to the computesize api onthe reflow branch to resolve a number of float-related bugs (359135,360093), and some others. ...
Multi-process plugin architecture - Archive of obsolete content
otocol language. in the plugin process, the shim layer serves as a plugin host, implementing the npn_ functions used by the plugin, and forwards the calls to the plugin dll: multi-process plugins, also called out of process plugins or oopp first shipped in firefox 3.6.4 on windows and linux, and in firefox 4 on mac os x. in addition to crash protection, the multi-process plugin architecture allows firefox to see plugins which respond very slowly or have completely stopped responding. for more details on hang protection, see the page on the plugin hang detector. ...
Browser-side plug-in API - Archive of obsolete content
the names of all of these methods begin with npn_ to indicate that they are implemented by the browser and called by the plug-in. for an overview of how these two sides of the plug-in api interact, see the how plug-ins work and overview of plug-in structure sections in the introduction. warning: you must only call these from the main thread; calling them from other threads is not supported and may have unpredictable results. ...
NPAnyCallbackStruct - Archive of obsolete content
description callback structures are used to pass platform-specific information. ...
NPByteRange - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary represents a particular range of bytes from a stream. syntax typedef struct _npbyterange { int32 offset; /* negative offset = from the end */ uint32 length; struct _npbyterange* next; } npbyterange; fields the data structure has the following fields: offset offset in bytes to the start of the requested range. this value may be either positive or negative: positive value: offset from the beginning of the stream. negative value: offset from the end of the stream. length number of bytes to fetch from the specified offset. next points to the next npbyterange request in the list of requests, or null if this is the last request. description the plug-in seeks within a stream by building a linked list o...
NPClass - Archive of obsolete content
herwise the browser calls malloc(). this function is expected to allocate and return enough storage to hold the npobject that is being created. deallocate called by npn_releaseobject() 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 in...
NPEmbedPrint - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary substructure of npprint that contains platform-specific information used during embedded mode printing. syntax typedef struct _npembedprint { npwindow window; void* platformprint; /* platform-specific */ } npembedprint; fields the data structure has the following fields: window the npwindow the plug-in should use for printing. platformprint additional platform-specific printing information. mac os: thprint unix: pointer to a npprintcallbackstruct. description the npp_print function passes a pointer to an npprint object (previously allocated by the browser) to the plug-in. the npembedprint structure is used when the mode field of npprint is set to np_embed. unix the plug-in location and size in th...
NPFullPrint - Archive of obsolete content
e of npprint that contains platform-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 dial...
NPN_CreateObject - Archive of obsolete content
<tt>aclass</tt> the class to instantiate an object of. returns the newly-allocated npobject. ...
NPN_DestroyStream - Archive of obsolete content
stream pointer to current stream, initiated by either the browser or the plug-in. ...
NPN_Enumerate - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary gets the names of the properties and methods of the specified npobject. syntax #include <npruntime.h> bool npn_enumerate(npp npp, npobject *npobj, npidentifier **identifiers, uint32_t *identifiercount); parameters the function has the following parameters: npp the npp indicating which plugin instance is making the request. npobj the object of which the properties and methods are to be retrieved. identifiers a pointer to receive a pointer to the start of an array of string identifiers of the names of the properties and methods of npobj. identifiercount a pointer to receive the number of identifiers in identifiers. returns true if the names of the properties and methods were successfully...
NPN_Evaluate - Archive of obsolete content
npobj the scope object. script the script to evaluate. ...
NPN_ForceRedraw - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary asks the plugin host to immediately (synchronously) repaint invalid areas. note: as of firefox 4, this function no longer has any effect when running with separate plugin processes. syntax #include <npapi.h> void npn_forceredraw(npp instance); parameters the function has the following parameters: instance plug-in instance for which the function forces redrawing. description once a region of a windowless plugin has been invalidated with npn_invalidaterect() or npn_invalidateregion(), a plug-in can call npn_forceredraw() to force a paint message. this causes a synchronous update event or paint message for the plug-in. browsers may ignore this request. see also drawing and event handling npn_invalidaterect() npn_invalidatere...
NPN_GetIntIdentifier - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary returns an opaque identifier for the integer that is passed in. syntax #include <npruntime.h> npidentifier npn_getintidentifier(int32_t intid); parameters the function has the following parameter: <tt>intid</tt> the integer for which an opaque identifier should be returned. returns an npidentifier identifying the integer. description all calls for the same integer are guaranteed to return the same exact identifier. ...
NPN_GetProperty - Archive of obsolete content
<tt>npobj</tt> the object from which a value is to be retrieved. ...
NPN_GetStringIdentifier - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary returns an opaque identifier for the string that is passed in. syntax #include <npruntime.h> npidentifier npn_getstringidentifier(const nputf8 *name); parameters the function has the following parameters: <tt>name</tt> the string for which an opaque identifier should be returned. returns an npidentifier identifying the string. description all calls for the same string are guaranteed to return the same exact identifier. ...
NPN_GetStringIdentifiers - Archive of obsolete content
namecount the number of strings in the names array. ...
NPN_HasMethod - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary determines whether or not the specified npobject has a particular method. 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. returns true if the method exists on the specified object, otherwise false. ...
NPN_HasProperty - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary determines whether or not the specified npobject has a particular property. 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. returns true if the property exists on the specified object, otherwise false. ...
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_IntFromIdentifier - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary returns the integer value corresponding to the given integer identifier. syntax #include <npruntime.h> int32_t npn_intfromidentifier(npidentifier identifier); parameters the function has the following parameter: <tt>identifier</tt> the integer identifier whose corresponding integer value should be returned. returns an integer corresponding to the specified <tt>identifier</tt>. note: the behavior of this function is undefined if <tt>identifier</tt> isn't an integer identifier. ...
NPN_InvalidateRect - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary invalidates the specified portion of the plugin's drawing area, adding it to the region that needs to be redrawn when the plugin next repaints its contents. syntax #include <npapi.h> void npn_invalidaterect(npp instance, nprect *invalidrect); parameters the function has the following parameters: instance pointer to the plug-in instance to invalidate a portion of. invalidrect the area to invalidate, specified in a coordinate system that originates at the top left of the plug-in's content area. description before a windowless plug-in can repaint or refresh part of its drawing area, the plug-in must first invalidate the area with either npn_invalidaterect() or npn_invalidateregion(). npn_invalidatere...
NPN_InvalidateRegion - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary invalidates the specified drawing region prior to repainting or refreshing a windowless plug-in. syntax #include <npapi.h> void npn_invalidateregion(npp instance, npregion invalidregion); parameters the function has the following parameters: instance pointer to the current plug-in instance. invalidregion the area to invalidate, specified in a coordinate system that originates at the top left of the plug-in. description before a windowless plug-in can repaint or refresh part of its drawing area, the plug-in must first invalidate the area with either npn_invalidaterect() or npn_invalidateregion(). npn_invalidateregion() causes the npp_handleevent() method to pass an update event or a paint message...
NPN_Invoke - Archive of obsolete content
npobj the object on which to invoke a method. ...
NPN_InvokeDefault - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary invokes the default method, if one exists, on the given npobject. syntax #include <npruntime.h> bool npn_invokedefault(npp npp, npobject *npobj, const npvariant *args, uint32_t argcount, npvariant *result); parameters the function has the following parameters: npp the npp indicating which plugin wants to call the default method on the object. npobj the object on which to invoke the default method. args an array of arguments to pass to the default method. argcount the number of arguments in the args array. result a pointer to an npvariant to receive the result returned by the default method. returns true if the default method was successfully invoked, otherwis...
NPN_MemFlush - Archive of obsolete content
returns if successful, the function returns the amount of freed memory, in bytes. ...
NPN_MemFree - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary deallocates a block of allocated memory. syntax #include <npapi.h> void npn_memfree (void* ptr); parameters the function has the following parameters: ptr block of memory previously allocated using npn_memalloc. description npn_memfree deallocates a block of memory that was allocated using npn_memalloc only. npn_memfree does not free memory allocated by any other means. see also npn_memalloc ...
NPN NewStream - Archive of obsolete content
type mime type of the stream. ...
NPN_PluginThreadAsyncCall - Archive of obsolete content
n api reference « browser side plug-in api summary thread safe way to request that the browser calls a plug-in function on the browser or plugin thread (the thread on which the plug-in was initiated). syntax #include <npapi.h> void npn_pluginthreadasynccall(npp plugin, void (*func)(void *), void *userdata); parameters the function has the following parameters: plugin pointer to the current plug-in instance. func pointer to the function to call on the correct thread. userdata pointer to the data to pass to the function func once called. returns nothing. description causes asynchronous execution of the specified function pointer on the "plug-in thread", passing in the specified user data ...
NPN_ReleaseObject - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary decrements the reference count of the given npobject. if the reference count reaches 0, the npobject is deallocated by calling its deallocate function if one is provided; if one is not provided, free() is used. syntax #include <npruntime.h> void npn_releaseobject(npobject *npobj); parameters the function has the following parameter: <tt>npobj</tt> the npobject whose reference count should be decremented. returns nothing. ...
NPN_ReleaseVariantValue - Archive of obsolete content
returns nothing. description npn_releasevariantvalue() releases the value in the given variant. this must always be called on result variants and such in this api, i.e. ...
NPN_ReloadPlugins - Archive of obsolete content
if true, all pages are reloaded once the plugins are reloaded; otherwise, they aren't. description npn_reloadplugins() reads the plugins directory for the current platform and reinstalls all of the plug-ins it finds there. ...
NPN_RemoveProperty - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary removes a property from the specified npobject. syntax #include <npruntime.h> bool npn_removeproperty(npp npp, npobject *npobj, npidentifier propertyname); parameters the function has the following parameters: npp the npp indicating which plugin instance is making the request. npobj the object on which a property is to be deleted. propertyname a string identifier indicating the name of the property to remove. returns true if the property was removed successfully, otherwise false. ...
NPN_RequestRead - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary requests a range of bytes from a seekable stream. this initiates a read operation; the actual data is received through subsequent calls to npp_writeready() and npp_write(). syntax #include <npapi.h> nperror npn_requestread(npstream* stream, npbyterange* rangelist); parameters the function has the following parameters: stream stream of type np_seek from which to read bytes. rangelist range of bytes in the form of a linked list of npbyterange objects, each of which specifies a request for a range of bytes. returns if successful, the function returns nperr_no_error. if unsuccessful, the function returns an error code. for possible values, see error codes. description for a s...
NPN_RetainObject - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary increments the reference count of the given npobject. syntax #include <npruntime.h> npobject *npn_retainobject(npobject *npobj); parameters the function has the following parameter: npobj the npobject to retain. returns a pointer back to the same object. ...
NPN_SetException - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary a plugin can call this function to indicate that a call to one of the plugin's npobjects generated an error. syntax #include <npruntime.h> void npn_setexception(npobject *npobj, const nputf8 *message); parameters the function has the following parameters: <tt>npobj</tt> the object on which the exception occurred. <tt>message</tt> a utf-8 string describing the error that occurred. returns nothing. ...
NPN_SetProperty - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary sets the value of a property on the specified npobject. syntax #include <npruntime.h> bool npn_setproperty(npp npp, npobject *npobj, npidentifier propertyname, const npvariant *value); parameters the function has the following parameters: <tt>npp</tt> the npp indicating which plugin instance's is making the request. <tt>npobj</tt> the object on which a value is to be set. <tt>propertyname</tt> a string identifier indicating the name of the property whose value is to be set. <tt>value</tt> the value to store in the specified property. returns true if the value was set successfully, otherwise false. ...
NPN_Status - Archive of obsolete content
message pointer the buffer that contains the status message string to display. ...
NPN_UTF8FromIdentifier - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary returns the utf-8 string corresponding to the given string identifier. syntax #include <npruntime.h> nputf8 *npn_utf8fromidentifier(npidentifier identifier); parameters the function has the following parameter: <tt>identifier</tt> the string identifier whose corresponding string should be returned. returns a utf-8 string as a sequence of nputf8 bytes, or null if the specified <tt>identifier</tt> isn't a string identifier. description once the caller is done with the returned string, the caller is responsible for deallocating the memory used by the string by calling npn_memfree(). ...
NPN_UserAgent - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary returns the browser's user agent field. this can be used to handle variations in different browsers (or versions thereof) when implementing your plug-in. syntax #include <npapi.h> const char* npn_useragent(npp instance); parameters the function has the following parameter: instance pointer to the current plug-in instance. returns a pointer to a buffer that contains the user agent field of the browser. description the user agent is the part of the http header that identifies the browser during transfers. you can use this information to verify that the expected browser is in use, or you can use it in combination with npn_version() to supply different code for different versions of the same browser. see also ...
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. 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. netscape_minor pointer to the browser's version; changes with point release n...
NPN_Write - Archive of obsolete content
stream pointer to the stream into which to push the data. ...
NPObject - Archive of obsolete content
tax struct npobject { npclass *_class; uint32_t referencecount; /* * additional space may be allocated here by types of npobjects */ }; fields _class a pointer to the npclass of which the object is a member. referencecount the reference count for the object. warning: do not manipulate the _class and referencecount fields directly; use the functions below to manipulate the object. functions npn_createobject() npn_retainobject() npn_releaseobject() npn_invoke() npn_invokedefault() npn_evaluate() npn_getproperty() npn_setproperty() npn_removeproperty() npn_hasproperty() npn_hasmethod() npn_setexception() see also npclass ...
NPP - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary represents a single instance of a plug-in. you specify one of these to any npapi function that needs to know which plug-in to work with. syntax typedef struct _npp { void* pdata; /* plug-in private data */ void* ndata; /* mozilla private data */ } npp_t; typedef npp_t* npp; fields the data structure has the following fields: pdata a value, whose definition is up to the plug-in, that the plug-in can use to store a pointer to an internal data structure associated with the instance; this field isn't modified by the browser. ndata a private value, owned by the browser, which is used to store data associated with the instance; this value should not be modified by the plug-in. descri...
NPP_Destroy - Archive of obsolete content
**save state or other information to save for reuse by a new instance of this plug-in at the same url. passed to npp_new. returns if successful, the function returns nperr_no_error. ...
NPP_DestroyStream - Archive of obsolete content
stream pointer to current stream. ...
NPP_GetValue - Archive of obsolete content
variable variable for which the browser (caller) would like a value. the full list is in the npapi headers. value value for the requested variable. returns if successful, the function returns nperr_no_error. if unsuccessful, the function returns an error code. for possible values, see error codes. ...
NPP_HandleEvent - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary delivers a platform-specific window event to the instance. for windowed plug-ins: currently used only on mac os. for windowless plug-ins: all platforms. syntax #include <npapi.h> int16 npp_handleevent(npp instance, void* event); parameters the function has the following parameters: instance pointer to the current plug-in instance. event platform-specific value representing the event handled by the function. values: ms windows: pointer to npevent structure mac os: pointer to a standard mac os eventrecord unix/x11: pointer to a standard xlib xevent for a list of possible events, see npevent. returns if the plug-in handles the event, the function should return true. if the plug-in i...
NPP_New - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary creates a new instance of a plug-in. syntax #include <npapi.h> nperror npp_new(npmimetype plugintype, npp instance, uint16 mode, int16 argc, char *argn[], char *argv[], npsaveddata *saved); parameters the function has the following parameters: plugintype pointer to the mime type for new plug-in instance. instance contains instance-specific private data for 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 i...
NPP_Print - Archive of obsolete content
must be embedded or full-screen. printinfo pointer to npprint structure. ...
NPP_SetValue - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary implemented by plugins. this call is used to inform plugins of variable information controlled by the browser. syntax #include <npapi.h> nperror npp_setvalue(void *instance, npnvariable variable, void *value); parameters the function has the following parameters: instance pointer to plugin instance on which to set the variable. variable the variable being set. value value for the variable being set. returns if successful, the function should return nperr_no_error. if unsuccessful, the function should return the most relevant npapi error code. for possible values, see error codes. description none see also npp_new, npp_getvalue, npn_setvalue, npn_...
NPP_StreamAsFile - Archive of obsolete content
stream pointer to current stream. ...
NPP_URLNotify - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary notifies the plug-in instance of the completion of a url request. syntax #include <npapi.h> void npp_urlnotify(npp instance, const char* url, npreason reason, void* notifydata); parameters the function has the following parameters: instance pointer to the current plug-in instance. url url of the npn_geturlnotify() or npn_posturlnotify() request that has completed. reason reason code for completion of request. values: npres_done (most common): completed normally. npres_user_break: user canceled stream directly by clicking the stop button or indirectly by some action such as deleting the instance or initiating higher-prio...
NPP_Write - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary delivers data to a plug-in instance. (remark: hence the name "npp_write" is misleading - just think of:"data_arrived") syntax #include <npapi.h> int32 npp_write(npp instance, npstream* stream, int32 offset, int32 len, void* buf); parameters the function has the following parameters: instance pointer to the current plug-in instance. stream pointer to the current stream. offset offset in bytes of buf from the beginning of the data in the stream. can be used to check stream progress or by range requests from npn_requestread. len length in bytes of buf; number of bytes accepted. buf buffer of data, delivered by the stream, that contains len bytes of data offs...
NPPrint - Archive of obsolete content
ce « plug-in side plug-in 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 npembedpri...
NPPrintCallbackStruct - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary contains information required by the platformprint field of the npembedprint structure during embedded mode printing on unix systems. this structure is only used on unix. syntax typedef struct { int32 type; file* fp; } npprintcallbackstruct; fields the data structure has the following fields: type always contains np_print. fp pointer to the file to which the plug-in should write its postscript data. description callback structures are used to pass platform-specific information. the npprintcallbackstruct structure contains the file pointer to which the plug-in should write its postscript data. this information is required by the platformprint field of the npembedprint structure during embedded mode print...
NPRect - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary represents a rectangular area of a plug-in's content area. syntax typedef struct _nprect { uint16 top; uint16 left; uint16 bottom; uint16 right; } nprect; fields the data structure has the following fields: top, left, bottom, right the top, left, bottom, and right sides of the rectangle. description nprect defines the bounding box of the area of the plug-in window to be updated, painted, invalidated, or clipped to. see also npn_forceredraw() npn_invalidaterect() npn_invalidateregion() npregion npwindow ...
NPSavedData - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary block of instance information saved after the plug-in instance is deleted; can be returned to the plug-in to restore the data in future instances of the plug-in. syntax typedef struct _npsaveddata { int32 len; void* buf; } npsaveddata; fields the data structure has the following fields: len length in bytes of the buffer pointed to by buf; set by the plug-in. buf pointer to a memory buffer allocated by the plug-in with npn_memalloc(). can be any reasonable size; its contents are private to the plug-in and are not modified by the browser. description the npsaveddata object contains a block of per-instance information that the browser saves after the instance is deleted. this information can be returned to another ...
NPSetWindowCallbackStruct - Archive of obsolete content
plugin api reference « plug-in side plug-in api summary note: this structure is only used on unix platforms. contains information about the plug-in's unix window environment. syntax typedef struct { int32 type; display* display; visual* visual; colormap colormap; unsigned int depth; } npsetwindowcallbackstruct; fields the data structure has the following fields: type always contains np_setwindow. display standard x toolkit attribute. pointer to the display structure that represents the browser-server connection. visual standard x toolkit attribute. x visual for the plug-in window or drawable. colormap standard x toolkit attribute. colormap for the plug-in window or drawable. depth standard x too...
NPString - Archive of obsolete content
making up a utf-8 string, and the number of 8-bit units in the utf-8 string. note: whenever an npstring owns its string data and the data may be released through a call to npn_releasevariantvalue(), the string data must be allocated using npn_memalloc(). syntax typedef struct _npstring { const nputf8 *utf8characters; uint32_t utf8length; } npstring; fields the data structure has the following fields: utf8characters an array of the utf-8 characters comprising the string. utf8length the number of bytes in the utf-8 string (not the number of characters). ...
NPAPI plug-in side API - Archive of obsolete content
the names of all of these methods begin with npp_ to indicate that they are implemented by the plug-in and called by the browser. for an overview of how these two sides of the plug-in api interact, see the how plug-ins work and overview of plug-in structure sections in the introduction. ...
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
still exist when using xembed plugins. there are only two key differences: in the npp_setwindow call, the window parameter will be the xid of the hosting xembed window. as an implementation note, this is really the xid of a gtksocket window. in your plugin instance npp_getvalue call you need to make sure that you support the new nppvpluginneedsxembed value. more information is included on this below. hosting using gtk2.x included below are a couple of code snippits that should help you get started as well as some hints on building a successful plugin. please use the following diagram as a reference: as you can see from the diagram above, it's pretty easy to set up a plugin using gtk2. the general idea is that you use the xid that was passed into your npp_setwindow() call and create a gtkpl...
Plugins - Archive of obsolete content
lines 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 scriptable and also let them access the script objects in the browser. shipping a plugin as a toolkit bundle plugins can be shipped as a toolkit bundle, allowing a user to easily install, uninstall and manage their personal plugins. supporting private browsing in plugins firefox 3.5 introduced support for private browsing; learn how to make your plugin respect the user's privacy wishes. multi-process plugin architecture how firefox loads plugins into a separate process. firefox 3.6.4 introduced out-of-process plugins which execute in a separate ...
Why RSS Slash is Popular - Counting Your Comments - Archive of obsolete content
e slashdot effect, a phenomena that adorns its name. one of the quirks of slashdot is that it includes a comments count, a humorous department, a hit parade, and a section with every blog post. rss does not have any facilites for including this information in an <item>, so the rss slash module exists to fill in this gap. ...
Syndicating content with RSS - Archive of obsolete content
scussed above. linking from the the html web page where the data in an rss feed is also contained makes the rss feed available for use: <a rel="alternate" type="application/rss+xml" href="http://example.com/feed">...</a> feed icons rss (and other) feeds use a special icon. it is recommended that you too use this icon when creating the special <a> link to your feed. the icon looks like the following: you can get more icons like this from feed icons. (other sizes and colors, along with their source files, are available too.) advanced syndication techniques although this advanced technique for syndication is not required, support of this is recommended, especially for web sites and applications with high performance needs. the http protocol, one of the core technologies behind the ...
Getting Started - Archive of obsolete content
because of this, you will be creating your own rss files by hand. who should use this tutorial? this tutorial is mostly meant for beginners to rss (i.e., those with no or very little prior rss experience). ...
Element - Archive of obsolete content
Archive › RSS › Module › Slash › Element
however, use of slash as the xml namespace prefix is not necessary. you are free to to choose your own prefix for this. ...
Element - Archive of obsolete content
however, use of wfw as the xml namespace prefix is not necessary. you are free to to choose your own prefix for this. ...
Module - Archive of obsolete content
rss module list rss modules are microformats injected into an rss document through the use of xml namespaces. they are ways of extending rss. below is a list of the popular rss modules. name common prefix status release date author atomic rss atom july 27, 2005 tim bray blogchannel september 17, 2002 dave winer content content creativecommons cc december 16, 2002 dave winer dublin core dc slash slash well-formed web wfw joe gregorio and chris...
0.90 - Archive of obsolete content
Archive › RSS › Version › 0.90
nk>http://www.mozilla.org/npl/npl-1.0m.html</link> </item> </rdf:rdf> note that here, rss is being used to list sections of the web site. ...
title - Archive of obsolete content
vogato.png</url> </image> <item> <title>why can i not get any tang?!</title> <link>http://www.advogato.org/article/10101.html</link> <description>seriously. why can't i get any tang?</description> </item> </channel> </rss> attributes none sub-elements none parent elements the table below shows a list of rss elements that this element can be a child of. <tr> <th>name</td> <th>tag</td> <th>0.90</td> <th>n 0.91 r1</td> <th>n 0.91 r3</td> <th>u 0.91</td> <th>0.92</td> <th>0.93</td> <th>0.94</td> <th>1.0</td> <th>2.0</td> </tr> <tr> <td>rss channel element</td> <td><channel></td> <td>✔</td> <td>✔</td> <td>✔</td> <td>✔</td> <td>?</td> <td>?</td> <td>?</td> <td>?</td> <td>?</td...
.htaccess ( hypertext access ) - Archive of obsolete content
o different pages depending on the error they caused or by the webserver. errordocument 404 /notfound.html # redirects traffic to notfound.html in case of a 404 error errordocument 500 /serverr.html # redirects traffic to serverr.html in case of a 500 internal server error for further information see this external article: redirect your traffic for error handling. cache control : .htaccess allows a server to control caching by web browsers, helps load pages faster, and reduces the data transfer. mime types : see correct mime types for further information. ...
Security Controls - Archive of obsolete content
or mitigated. second, the system should offer only the required functionality to each authorized user, so that no one can use functions that are not necessary. this principle is known as least privilege. limiting functionality and resolving security weaknesses have a common goal: give attackers as few opportunities as possible to breach a system. there are three types of security controls, as follows: management controls: the security controls that focus on the management of risk and the management of information system security. operational controls: the security controls that are primarily implemented and executed by people (as opposed to systems). technical controls: the security controls that are primarily implemented and executed by the system through the system's hardware, softwar...
Digital Signatures - Archive of obsolete content
ginning of this document. but encryption and decryption, by themselves, do not address another problem: tampering. this section describes how public-key cryptography addresses the problem of tampering. tamper detection and related authentication techniques rely on a mathematical function called a one-way hash (also called a message digest). a one-way hash is a number of fixed length with the following characteristics: the value of the hash is unique for the hashed data. any change in the data, even deleting or altering a single character, results in a different value. the content of the hashed data cannot, for all practical purposes, be deduced from the hash-which is why it is called "one-way." similarly, in public key encryption, a key pair is generated for digital signing. the key p...
Encryption and Decryption - Archive of obsolete content
ion 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. decryption with the correct key is simple. decryption without the correct key is very difficult, and in some cases impossible for all practical purposes. the sections that follow introduce the use of keys for encryption and decryption. symmetric-key encryption public-key encryption key length and encryption strength symmetric-key encryption with symmetric-key encryption, the encryption key can be calculated from the decryption key and vice versa. with most symmetric algorithms, the same key is used for both encryption and decryption, as shown in figure 1. imple...
Threats - Archive of obsolete content
akes—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 card number, record a sensitive conversation, or intercept classified information. tampering. information in transit is changed or replaced and then sent on to the recipient. for example, someone could alter an order for goods or change a person's resume. impersonation.
The Basics of Web Services - Archive of obsolete content
the basics web services are not really anything that new, and actually, if you've ever used an rss or atom feed to pull news from a website, you have an idea of how a web service might work. web services exchange data from a server to a client, using an xml format to send requests, so both the server and the client can understand each other. (xml introduction). a better way to understand a web service is to compare it to a html form communication with a server side script (such as php or asp) to post and send data. ...
contents.rdf - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "contents.rdf": <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:chrome="http://www.mozilla.org/rdf/chrome#"> <!-- list all the skins being supplied by this theme --> <rdf:seq about="urn:mozilla:skin:root"> <rdf:li resource="urn:mozilla:skin:my_theme"/> </rdf:seq> <rdf:description about="urn:mozilla:skin:my_theme" chrome:displayname="my theme" chrome:accesskey="n" chrome:author="" chrome:authorurl="" chrome:description="" chrome:name="my_theme" chrome:image="preview.png"> <chrome:packages> <rdf:seq about="urn:mozilla:skin:my_theme:packages"> <rdf:li resource="urn:mozilla:skin:my_...
install.rdf - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "install.rdf": <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>{themes_uuid}</em:id> <em:version>themes_version</em:version> <!-- target application this extension can install into, with minimum and maximum supported versions. --> <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 --...
Making sure your theme works with RTL locales - Archive of obsolete content
n the back and forward arrows, you don't really need new versions of the images. instead, just use the opposite arrow when in rtl context. using start/end rules instead of left/right rules directions are mirrored in rtl mode, so left becomes right and right becomes left. as a result, you almost never want to use left/right rules for paddings, borders, and margins. ...
Developing cross-browser and cross-platform pages - Archive of obsolete content
opriate switches. another major problem with this approach is that the browser identity can be "spoofed" because, in many modern browsers, the navigator.appversion and navigator.useragent string properties are user configurable strings. for example, firefox 1.x users and users of any/all mozilla-based browsers can customize the "general.useragent.*" string properties to any value. opera 6+ allows users to set the browser identification string via a menu internet explorer uses the windows registry safari, konqueror and icab browsers can mask their browser identity under internet explorer or netscape labels a user or browser distributor can put what they want in the navigator.useragent string and this may trick your code into executing a "wrong" block of code. moreover, there are many ...
Using workers in extensions - Archive of obsolete content
fairly similar to the previous versions, with two notable exceptions: if the ticker symbol 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["@...
-moz-window-shadow - Archive of obsolete content
ult changed, with all windows having a shadow. this version introduced the -moz-window-shadow css property to provide a way to turn off unwanted shadows. initial valuedefaultapplies toall elements that create native windows, e.g. <window>, <panel>inheritednocomputed valueas specifiedanimation typediscrete syntax the -moz-window-shadow property is specified as one of the keyword values listed below. values default the window will have a shadow with the default window shadow style. menu the window will have the shadow style that's appropriate for menus. tooltip the window will have the shadow style that's appropriate for tooltips. sheet the window will have the shadow style that's appropriate for sheet windows. none the window won't have a shadow. formal syntax default | menu...
-ms-content-zoom-limit-max - Archive of obsolete content
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. ...
-ms-content-zoom-limit-min - Archive of obsolete content
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. ...
-ms-content-zoom-snap - Archive of obsolete content
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 ef...
-ms-content-zooming - Archive of obsolete content
-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. the top-level element can also be zoomed via double-tap when it is zoom-enabled. starting with windows 8.1, this property is also supported for touchpad interaction. this property requires windows 8 or later. ...
-ms-hyphenate-limit-lines - Archive of obsolete content
nes css property is a microsoft extension specifying the maximum number of consecutive lines in an element that may be ended with a hyphenated word. initial valueno-limitapplies toblock container elementsinheritedyescomputed valueas specifiedanimation typediscrete syntax values no-limit indicates that hyphenation is not limited based on the number of consecutive hyphenated lines. in the flow above the consecutive hyphenated lines limit would be an infinitely large positive number. <integer> indicates the maximum number of successive hyphenated lines. for instance, if 2, then no more than 2 successive lines may end with a hyphenated word. if 0 then no lines may end with a hyphenated word. (hyphenation is effectively disabled.) negative values are not allowed. formal synt...
-ms-hyphenate-limit-zone - Archive of obsolete content
the -ms-hyphenate-limit-zone css property is a microsoft extension specifying the width of the hyphenation zone. initial value0applies toblock container elementsinheritedyespercentagescalculated with respect to the width of the line boxcomputed valueas specifiedanimation typediscrete syntax values <percentage> an integer followed by a percent sign (%), which specifies the width of the hyphenation zone, calculated with respect to the line box. negative values are not allowed. <length> a floating-point number, followed by a relative units designator, that indicates the width of the hyphenation zone. for more information about supported length units, see css basic data types. negative values are not allowed. formal syntax <percentage> | <length> specifications ...
-ms-scroll-limit - Archive of obsolete content
values -ms-scroll-limit-x-min the value of the -ms-scroll-limit-x-min property. -ms-scroll-limit-y-min the value of the -ms-scroll-limit-y-min property. -ms-scroll-limit-x-max the value of the -ms-scroll-limit-x-max property. -ms-scroll-limit-y-max the value of the -ms-scroll-limit-y-max property. forma...
-ms-scroll-rails - Archive of obsolete content
the -ms-scroll-rails css property is a microsoft extension that specifies whether scrolling locks to the primary axis of motion. initial valuerailedapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete syntax values none the content moves exactly with the user's finger. this value allows for free-form panning. railed initial value. panning locks to the primary axis of motion. formal syntax none | railed specifications not part of any specification. remarks this property has no effect on non-scrollable elements. starting with windows 8.1, this property is also supported for touchpad interaction. this property requires windows 8 or later. ...
-ms-scroll-snap-x - Archive of obsolete content
type: none-ms-scroll-snap-points-x: snapinterval(0px, 100%)applies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas each of the properties of the shorthand:-ms-scroll-snap-type: as specified-ms-scroll-snap-points-x: as specifiedanimation typediscrete syntax values the -ms-scroll-snap-x shorthand property is specified as one or both of the following values, in order and separated by spaces. -ms-scroll-snap-type the value of the -ms-scroll-snap-type property. -ms-scroll-snap-points-x the value of the -ms-scroll-snap-points-x property. formal syntax <'-ms-scroll-snap-type'> <'-ms-scroll-snap-points-x'> examples the -ms-scroll-snap-x property is a shorthand property. the two selectors in the following example have the s...
-ms-scroll-snap-y - Archive of obsolete content
type: none-ms-scroll-snap-points-y: snapinterval(0px, 100%)applies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas each of the properties of the shorthand:-ms-scroll-snap-type: as specified-ms-scroll-snap-points-y: as specifiedanimation typediscrete syntax values the -ms-scroll-snap-y shorthand property is specified as one or both of the following values, in order and separated by spaces. -ms-scroll-snap-type the value of the -ms-scroll-snap-type property. -ms-scroll-snap-points-y the value of the -ms-scroll-snap-points-y property. formal syntax <'-ms-scroll-snap-type'> <'-ms-scroll-snap-points-y'> examples the -ms-scroll-snap-y property is a shorthand property. the two selectors in the following example have the s...
-ms-scrollbar-3dlight-color - Archive of obsolete content
code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/scrollbarcolor.htm <!doctype html> <html> <head> <title>scrollbar-3dlight-color</title> <style> .blue3dlight { -ms-scrollbar-3dlight-color: blue; scrollbar-3dlight-color:...
-ms-scrollbar-darkshadow-color - Archive of obsolete content
code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/scrollbarcolor.htm <!doctype html> <html> <head> <title>scrollbar-darkshadow-color</title> <style> .blueshadow { scrollbar-darkshadow-color: blue; } </style> </head> <...
-ms-scrollbar-face-color - Archive of obsolete content
e> [ / <alpha-value> ]? ) | hsla( <hue>, <percentage>, <percentage>, <alpha-value>? )where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples this example uses -ms-scrollbar-face-color and -ms-scrollbar-arrow-color to display a scroll bar with a blue scroll box and arrows, and a scroll bar with a green scroll box and arrows. ...
-ms-scrollbar-highlight-color - Archive of obsolete content
<hue>, <percentage>, <percentage>, <alpha-value>? )where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples this example uses -ms-scrollbar-highlight-color, -ms-scrollbar-face-color, and -ms-scrollbar-arrow-color to create two <div> objects with different scroll bar color schemes. ...
-ms-scrollbar-shadow-color - Archive of obsolete content
<!doctype html> <html> <head> <title>scrollbar-shadow-color</title> <style> .blueshadow { scrollbar-shadow-color: blue; } </style> </head> <body> <textarea class="blueshadow">the gutter elements in the scroll bar for this element will be blue.</textarea> ...
-ms-wrap-through - Archive of obsolete content
none specifications not part of any specification. remarks you can use the -ms-wrap-through property to control the effect of exclusions; for instance, to cause one content block to wrap around an exclusion 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-system-metric(windows-default-theme) - Archive of obsolete content
this will exclude windows classic themes as well as third-party themes. this selector is intended for use mainly by theme developers. 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. ...
:-moz-system-metric() - Archive of obsolete content
this will exclude windows classic themes as well as third-party themes. formal syntax syntax not found in db! ...
::-ms-reveal - Archive of obsolete content
-element is a microsoft extension that is used to display a password reveal button for use with a password field created by <input type="password">. the user presses the button to reveal the actual field value rather than asterisks. the password reveal button is usually displayed at the edge of the password field. the ::-ms-reveal pseudo-element is specific to internet explorer 10 and later. allowable properties only the following css properties can be used in a rule with ::-ms-reveal in its selector. other properties are ignored. background-clip background-color background-image background-origin background-repeat background-size border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-left-color border-left-st...
::-ms-ticks-after - Archive of obsolete content
tion of <input type="range">. these ticks are not shown by default. to show them, set the control's display property to block. it is possible to use the ::-ms-ticks-after, ::-ms-ticks-before, and ::-ms-track pseudo-elements together. to do so would create three sets of tick marks, but the best user experience is one set. to remove tick marks altogether, set the color property to transparent. allowable properties only the following css properties can be used in a rule with ::-ms-ticks-after in its selector. other properties are ignored. background-clip background-color background-image background-origin background-repeat background-size border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-left-color border-le...
::-ms-ticks-before - Archive of obsolete content
tion of <input type="range">. these ticks are not shown by default. to show them, set the control's display property to block. it is possible to use the ::-ms-ticks-after, ::-ms-ticks-before, and ::-ms-track pseudo-elements together. to do so would create three sets of tick marks, but the best user experience is one set. to remove tick marks altogether, set the color property to transparent. allowable properties only the following css properties can be used in a rule with ::-ms-ticks-before in its selector. other properties are ignored. background-clip background-color background-image background-origin background-repeat background-size border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-left-color border-l...
::-ms-tooltip - Archive of obsolete content
the ::-ms-tooltip css pseudo-element is a microsoft extension that represents the tooltip of a slider control. a slider control is one possible representation of <input type="range">. allowable properties only the following css properties can be used in a rule with ::-ms-tooltip in its selector. other properties are ignored. display visibility syntax ::-ms-tooltip ...
azimuth - Archive of obsolete content
Archive › Web › CSS › azimuth
combination with elevation, the azimuth css property enables different audio sources to be positioned spatially for aural presentation. this is important in that it provides a natural way to tell several voices apart, as each can be positioned to originate at a different location on the sound stage. stereo output produce a lateral sound stage, while binaural headphones and multi-speaker setups allow for a fully three-dimensional stage. initial valuecenterapplies toall elementsinheritedyescomputed valuenormalized angleanimation typediscrete syntax <angle> | [ [ left-side | far-left | left | center-left | center | center-right | right | far-right | right-side ] | behind ] | leftwards | rightwards values angle audible source position is described as an angle within the range -360deg to ...
display-inside - Archive of obsolete content
box generated by an element, dictating how its contents lay out inside the box. /* keyword values */ display-inside: auto; display-inside: block; display-inside: table; display-inside: flex; display-inside: grid; display-inside: ruby; /* global values */ display-inside: inherit; display-inside: initial; display-inside: unset; value not found in db! syntax one of the keyword values listed below. values auto if the element's computed <display-outside> value is inline-level, the element is an inline element, and lays out its contents using inline layout. if the element's computed <display-outside> value is an layout-specific internal type, this elements acts as normal for its given <display-outside> value. otherwise, this value computes to block. block the element lays out its cont...
display-outside - Archive of obsolete content
; display-outside: table-column-group; display-outside: table-column; display-outside: table-caption; display-outside: ruby-base; display-outside: ruby-text; display-outside: ruby-base-container; display-outside: ruby-text-container; /* global values */ display-outside: inherit; display-outside: initial; display-outside: unset; value not found in db! syntax one of the keyword values listed below. values block-level the element generates a block-level box, and participates in a block formatting context. other formatting contexts, such as flex formatting contexts, may also work with block-level elements. inline-level the element generates an inline-level box, and participates in an inline formatting context. run-in the element generates a run-in box. run-in elements act like inlin...
Using JavaScript Generators in Firefox - Archive of obsolete content
var generator; // simple event listener function to pass the received event to the generator. ...
Array.observe() - Archive of obsolete content
rder of occurrence. it's equivalent to object.observe() invoked with the accept type list ["add", "update", "delete", "splice"]. however, this api has been deprecated and removed from browsers. you can use the more general proxy object instead. syntax array.observe(arr, callback) parameters arr the array to be observed. callback the function called each time changes are made, with the following argument: changes an array of objects each representing a change. the properties of these change objects are: name: the name of the property which was changed. object: the changed array after the change was made. type: a string indicating the type of change taking place. one of "add", "update", "delete", or "splice". oldvalue: only for "update" and "delete" types. the valu...
Expression closures - Archive of obsolete content
sed to the function. a function can have up to 255 arguments. expression the expression which comprise the body of the function. description this addition is nothing more than a shorthand for writing simple functions, giving the language something similar to a typical lambda notation. javascript 1.7 and older: function(x) { return x * x; } javascript 1.8: function(x) x * x this syntax allows you to leave off the braces and 'return' statement - making them implicit. there is no added benefit to writing code in this manner, other than having it be syntactically shorter. examples a shorthand for binding event listeners: document.addeventlistener('click', function() false, true); using this notation with some of the array functions from javascript 1.6: elems.some(function(elem) e...
Date.getVarDate() - Archive of obsolete content
alue returns a vt_date value. remarks the getvardate() method is used when javascript code interacts with com objects, activex objects, or other objects that accept and return date values in vt_date format. these include objects in visual basic and visual basic scripting edition (vbscript). the actual format of the returned value depends on regional settings. requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards. not supported in windows 8.x store apps. applies to: date object see also date.getdate() date.parse() ...
Debug.debuggerEnabled - Archive of obsolete content
the debug.debuggerenabled property determines whether debugging is enabled for the script context. 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). not supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards. ...
Debug.msUpdateAsyncCallbackRelation - Archive of obsolete content
debug.ms_async_callback_status_cancel debug.ms_async_callback_status_error for more information, see debug constants. note: some debugging tools do not display the information sent to the debugger by this function. requirements supported in the internet explorer 11 standards document mode. also supported in store apps (windows 8.1 and windows phone 8.1). not supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards. not supported in windows 8. ...
Debug.write - Archive of obsolete content
note: to run this example, you must have a script debugger installed and the script must run in debug mode. internet explorer 8 includes the javascript debugger. if you are using an earlier version of internet explorer, see how to: enable and start script debugging from internet explorer. var counter = 42; debug.write("the value of counter is " + counter); requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). ...
Enumerator.item - Archive of obsolete content
not supported in windows 8.x store apps. applies to: enumerator object ...
Error.stackTraceLimit - Archive of obsolete content
tracelimit property to any positive value between 0 and infinity. if the stacktracelimit property is set to 0 at the time an error is thrown, no stack trace is shown. if the property is set to a negative value or a non-numeric value, the value is converted to 0. if the stacktracelimit is set to infinity, the entire stack is shown. otherwise, touint32 is used to convert the value. example the following example shows how to set and then get the stack trace limit. try { var err = new error("my error"); error.stacktracelimit = 7; throw err; } catch(e) { document.write("error stack trace limit: ") document.write(error.stacktracelimit); } requirements supported in internet explorer 10 and in windows 8.x store apps. applies to: error object ...
ScriptEngine() - Archive of obsolete content
the scriptengine function gets the name of the scripting language in use. syntax scriptengine() remarks the scriptengine function returns "jscript", which indicates that javascript is the current scripting engine. example the following example illustrates the use of the scriptengine function: if (window.scriptengine) { console.log(window.scriptengine()); } // output: jscript requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). ...
@cc_on - Archive of obsolete content
onditional 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 statement outside of a comment also activates conditional compilation. example the following example illustrates the use of the @cc_on statement. /*@cc_on @*/ /*@ document.write("javascript version: " + @_jscript_version + "."); document.write("<br />"); @if (@_win32) document.write("running on the 32-bit version of windows."); @elif (@_win16) document.write("running on the 16-bit version of windows."); @else document.write("running on a di...
@if - Archive of obsolete content
t 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 that do not support conditional compilation to ignore it. example the following example illustrates the use of the @if...@elif...@else...@end statement. /*@cc_on @*/ /*@ document.write("javascript version: " + @_jscript_version + "."); document.write("<br />"); @if (@_win32) document.write("running on a 32-bit version of windows."); @elif (@_win16) document.write("running on a 16-bit version of windows."); @else document.write(...
New in JavaScript 1.1 - Archive of obsolete content
the old netscape documentation references this as "features added after version 1". netscape navigator 3.0 was released on august 19, 1996. netscape navigator 3.0 was the second major version of the 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 in JavaScript 1.2 - Archive of obsolete content
the old netscape documentation can be found on archive.org. netscape navigator 4.0 was released on june 11, 1997. netscape navigator 4.0 was the third major version of the browser with javascript support. javascript versions netscape navigator 4.0 executes javascript language versions up to 1.2. note that netscape navigator 3.0 and earlier ignored scripts with the language attribute set to "javascript1.2" and higher. <script language="javascript1.1"> <!-- javascript for navigator 3.0. --> <script language="javascript1.2"> <!-- javascript for navigator 4.0. ...
New in JavaScript 1.4 - Archive of obsolete content
the old netscape documentation can be found on archive.org. ...
New in JavaScript 1.6 - Archive of obsolete content
this version was included in firefox 1.5 (gecko 1.8), which was released in november 2005. the corresponding ecma standard is ecma-262 edition 3 and ecmascript for xml (e4x) with some additional features. several new features were introduced: e4x, several new array methods, and array and string generics. new features in javascript 1.6 support for ecmascript for xml (e4x) for creating and processing xml content within javascript has been added. see for details. ...
New in JavaScript 1.8.1 - Archive of obsolete content
this version was included in firefox 3.5. javascript 1.8.1 is a modest update syntactically to javascript; the main change in this release is the addition of the tracemonkey just-in-time compiler, which improves performance. new features in javascript 1.8.1 object.getprototypeof() support for native json string.prototype.trim() string.prototype.trimleft() string.prototype.trimright() changed functionality in javascript 1.8.1 implicit setting of properties in object and array initializers no longer execute setters in javascript. this makes the behavior of setting the values of properties more predictable. ...
Object.getNotifier() - Archive of obsolete content
syntax object.getnotifier(obj) parameters obj the object to retrieve the notifier of. return value the notifier object associated with the object being passed to the function. description the notifier is used to trigger synthetic changes that will be observed by object.observe(). ...
Object.observe() - Archive of obsolete content
chronously observing the changes to an object. it provided a stream of changes in the order in which they occur. however, this api has been deprecated and removed from browsers. you can use the more general proxy object instead. syntax object.observe(obj, callback[, acceptlist]) parameters obj the object to be observed. callback the function called each time changes are made, with the following argument: changes an array of objects each representing a change. the properties of these change objects are: name: the name of the property which was changed. object: the changed object after the change was made. type: a string indicating the type of change taking place. one of "add", "update", or "delete". oldvalue: only for "update" and "delete" types. the value before ...
Object.prototype.unwatch() - Archive of obsolete content
return value undefined. description the javascript debugger has functionality similar to that provided by this method, as well as other debugging options. for information on the debugger, see venkman. by default, this method is inherited by every object descended from object. note: the reason for unwatch() to take the property name prop as its only parameter is due to the "single handler allowing" behavior of the watch() method. examples see watch(). specifications not part of any standard. ...
String.prototype.quote() - Archive of obsolete content
me. try to avoid using it. the non-standard quote() method returns a copy of the string, replacing various special characters in the string with their escape sequences and wrapping the result in double-quotes ("). syntax str.quote() return value a new string representing the original string wrapped in double-quotes, with any special characters escaped. examples using quote in the table below the quote() method replaces any special characters and wraps the strings in double-quotes. also note the third column where a wrapped eval() evaluates the escape sequences again. str str.quote() eval(str.quote()) hello world! "hello world!" hello world! hello world! "hello\n\tworld!" hello world! " \ — ' "\" \\ \u2014 '" "...
arguments.caller - Archive of obsolete content
he function that invoked the currently executing function. this property has been removed and no longer works. description this property is not available anymore, but you can still use function.caller. function whocalled() { if (whocalled.caller == null) console.log('i was called from the global scope.'); else console.log(whocalled.caller + ' called me!'); } examples the following code was used to check the value of arguments.caller in a function, but doesn't work anymore. function whocalled() { if (arguments.caller == null) console.log('i was called from the global scope.'); else console.log(arguments.caller + ' called me!'); } specifications not part of any standard. implemented in javascript 1.1 and removed in bug 7224 due to potentially vulnera...
for each...in - Archive of obsolete content
p, use a block statement ({ ... }) to group those statements. description some built-in properties are not iterated over. these include all built-in methods of objects, e.g. string's indexof method. however, all user-defined properties are iterated over. examples using for each...in warning: never use a loop like this on arrays. only use it on objects. see for...in for more details. the following snippet iterates over an object's properties, calculating their sum: var sum = 0; var obj = {prop1: 5, prop2: 13, prop3: 8}; for each (var item in obj) { sum += item; } console.log(sum); // logs "26", which is 5+13+8 specifications not part of any standard. ...
LiveConnect Reference - Archive of obsolete content
this section documents the java classes used for liveconnect, along with their constructors and methods. javascript-to-java these classes allow a java object to access javascript code. jsexception the public class jsexception extends runtimeexception, and is thrown when javascript returns an error. jsobject the public class jsobject extends object. javascript objects are wrapped in an instance of the class jsobject and passed to java, allowing java to manipulate javascript objects. java-to-javascript global objects java packages netscape sun javaarray javaclass javaobject javapackage ...
JavaPackage - Archive of obsolete content
ined in a javapackage are its properties, you cannot use a for...in statement to enumerate them as you can enumerate the properties of other objects. ...
MSX Emulator (jsMSX) - Archive of obsolete content
jsmsx is the first msx emulator 100% written in javascript. yes, you read it: javascript! it emulates the underlying z80 cpu, tms9918 video display processor (vdp), ppi, ram slots, and megaram. in its present form, it should be able to run any program or game developed for msx 1.0. since javascript currently is mostly an interpreted language in web browsers, it is at least an order of magnitude slower than other languages such as c and java. therefore, jsmsx requires a very fast computer to emulate msx at the normal 50-60 interrupts per second inside a web browser. why? the initial motivation was to find some interesting project to develop while exploring the possibilities of the <canvas> tag and javascript language in the most recent web browsers like firefox 2. as you may have realized, ma...
XForms API Reference - Archive of obsolete content
this page is the beginning of the xforms api reference. ...
Implementation Status - Archive of obsolete content
supported 4.9 feature string for the hasfeature method call supported 5. datatypes section title status notes bugs 5.1 xml schema built-in datatypes partial whitespace facet not supported. ...
RFE to the Custom Controls - Archive of obsolete content
xul, in many cases, is much better suited for application development than xhtml. therefore the control set may need to be more extensive to address the wider spectrum of requirements that a xul application will have on its controls. ...
RFE to the XForms API - Archive of obsolete content
Archive › Web › XForms › RFE › XForms API
. for example, every visual xforms element exposes the nsixformsdelegate interface. if you need some additional functionality that shouldn't be exposed from the xforms element directly, then you should think which interface of the xforms element is more appropriate to expose it. mozilla xforms doens't offer any service you can get via xpcom. as an example, the nsixformsaccessors interface which allows a user to get/set the value of an instance node and get the state of an instance node, is exposed by the nsixformsdelegate interface using the accessors property. xforms dom put here your requirements how to improve xforms dom api. reflect attributes to properties for the elements that can contain the incremental or selection attributes, it makes sense to expose analogous properties. xfo...
XForms Styling - Archive of obsolete content
just a starting draft. hopefully someone more proficient in mozilla xforms and css can clean this up repeats see the mozilla xforms specials page for some general points. switches can be styled as tabs. triggers use appearance="minimal" to be able to style buttons portability the mozilla xforms extension is one of the few xforms processors which allow for styling of the xforms elements directly, using mostly standard css. processors such as chiba create "old-style" html forms from xforms documents, and must be styled accordingly. however, most of the time the transition is straight-forward: view the source after processing of your xforms document, and map the old styles to the new elements. appearance attributes can also make a big difference. experimenting with these can ...
XForms Message Element - Archive of obsolete content
ibutes, inline text. attributes single-node binding linking src - url of a document whose contents will be retrieved by the message element and used to provide the message text for the message element. special level - defines a representation of message element type restrictions the message element can be bound to any simple content. representations it may be represented in the following ways: modal window - if level attribute value is modal modeless window - if level attribute value is modeless tooltip window - if level attribute value is ephemeral note: message element doesn't define a default presentation. therefore you should always specify a level attribute. example <xforms:trigger> <xforms:label>it's a button</xforms:label> <xforms:message level="modal" ev:ev...
XForms Submit Element - Archive of obsolete content
type restrictions the submit element can be bound to a node containing data of any type. actually, the submit element doesn't interact with the data 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. representations the xforms submit element can be represented by the following widgets for the specified appearance attribute values: button - default representation (xhtml/xul) link/clickable text - used when appearance = 'minimal' (xhtml only) button displaying a button is the default presentation (xhtml/xul). characteristics analogous widgets are <html:input type="submit"/> and <xul:button/> link/clickable text xforms authors can use this representation if t...
XForms Switch Module - Archive of obsolete content
the module defines for this switch, case and toggle elements. switch element the element (see the spec) is used in conjunction with case and toggle elements. the switch element contains case elements which in turn contain markup. only the contents of a single case may be displayed at one time. the toggle element is an action that when triggered will make a case selected and visible and thereby hiding all other case elements contained by the same switch. ...
Displaying a graphic with audio samples - Archive of obsolete content
the following example shows how to take samples from an audio stream and display them behind an image (in this case, the mozilla logo), giving the impression that the image is built from the samples. <!doctype html> <html> <head> <title>javascript spectrum example</title> </head> <body> <audio id="audio-element" src="revolve.ogg" controls="true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <img id="mozlogo" style="display:none" src="mozilla2.png"></img> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, framebufferlength, fft; function loadedmetadata() { chan...
Issues Arising From Arbitrary-Element hover - Archive of obsolete content
xpect. one is easily fixed by validation, but the other is a little more subtle. first, there is the problem of authors who open a named anchor but do not close it. for example: <a name="pagetop"> <h2>my page</h2> without a </a>, this name will effectively enclose the rest of the document. this generally means that the rest of the document will take hover styles. consider the effects of the following rule: a:hover {color: red;} in a document with an unclosed named anchor, any text that follows the anchor's open tag will be colored red (unless another css rule intervenes). this brings up the second common problem, which is that named anchors can accept hover styles. although authors may intend the selector a:hover to apply only to hyperlinks, it will also apply to named anchors, since th...
RDF in Fifty Words or Less - Archive of obsolete content
o relate a bookmark to another bookmark, or keep it in multiple "folders" at once. the rdf graph provides a perfect data model upon which to build a "universal" bookmarking service as described above: the graph can contain pointers to arbitrary resources and can group them in just about any way that you can imagine. but wait, there's more... second, rdf is a serialization syntax. this syntax allows the graph-like model to be communicated between "agents". okay, what the heck doesthat mean? fundamentally, it means that parts of the rdf data model can be communicated across network boundaries, and the contents of the graph can dynamically change as information arrives from a remote service. let's go back to our bookmark example. say that one of my bookmark "folders" is really a pointer to ...
Web Standards - Archive of obsolete content
sites developed along these lines will continue to function correctly as traditional desktop browsers evolve, and as new internet devices come to market. ...
XQuery - Archive of obsolete content
orted 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 (including well-formed xhtml) documents stored locally. the extension now includes and interfaces with the open-source version of saxonica's saxon b (though this extension currently only performs the xqueries). other popular native xml databases might also be supported...
XUL Parser in Python - Archive of obsolete content
for example, you could easily adapt this to: return the id values of all the elements take elements on the command line and only spell them out build new chrome subdirectories (i.e. new "packages") on the fly using search and replace. as i adapt the script in these ways and try to further generalize the actual code as i get time, i will make it available here. in the explanation section below, i try to say a little something about how this script works. it's really just a wrapper around python's xmllib xml parser, but i had to sort of fool around with it. python's support for xml (and potential with xul) is extensive, and so it's more a matter of choosing an approach and hooking things up than anything else. source code the source code for the xul parser is available. it only runs ...
bootstrap.js - Extensions
the bootstrap.js script should contain several specific functions, which are called by the browser to manage the extension. the script gets executed in a privileged sandbox, which is cached until the extension is shut down. for more information, see bootstrapped extensions. the example below contains the required methods in vsdoc format. function startup(data, reason) { /// bootstrap data structure @see /docs/extensions/bootstrapped_extensions#bootstrap_data /// string id /// string version /// nsifile installpath /// nsiuri resourceuri /// /// reason types: /// app_startup /// addon_enable /// addon_install /// addon_upgrade /// addon_downgrade } function shutdown(data, reason) { /// bootstrap data structure @se...
Introduction to game development for the Web - Game development
e high-performance, hardware-accelerated 3d (and 2d) graphics from web content. this is a web-supported implementation of opengl es 2.0. webrtc the webrtc (real-time communications) api gives 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. xmlhttpr...
Publishing games - Game development
promotion and monetization of your game on the web, rather than each version being locked into a single store controlled by one company. you can benefit from the web being truly multiplatform. 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. game distribution so you've followed a tutorial or two and created an html5 game — that's great! game distribution provides all you need to know about the ways you can distribute your newly created game into the wild — including hosting it yourself online, submitting it to open marketplaces, and submitting it to closed ones like google play or the ios app store. game promotion developing and finishing the game is not enough.
2D collision detection - Game development
ng axis theorem this is a collision algorithm that can detect a collision between any two *convex* polygons. it's more complicated to implement than the above methods but is more powerful. the complexity of an algorithm like this means we will need to consider performance optimization, covered in the next section. implementing sat is out of scope for this page so see the recommended tutorials below: separating axis theorem (sat) explanation collision detection and response collision detection using the separating axis theorem sat (separating axis theorem) separating axis theorem collision performance while some of these algorithms for collision detection are simple enough to calculate, it can be a waste of cycles to test *every* entity with every other entity. usually games will s...
WebVR — Virtual Reality for the Web - Game development
tc. for example: function setcustomfov(up,right,down,left) { var testfov = new vrfieldofview(up,right,down,left); ghmd.setfieldofview(testfov,testfov,0.01,10000.0); } the gpositionsensor variable holds the positionsensorvrdevice — using this you can get the current position or orientation state (for example to update the scene view on every frame), or reset the sensor. ...
Async scripts for asm.js - Game development
to see the difference, toggle javascript.options.parallel_parsing in about:config. ...
Desktop mouse and keyboard controls - Game development
previous overview: control mechanisms next now when we have our mobile controls in place and the game is playable on touch-enabled devices, it would be good to add mouse and keyboard support, so the game can be playable also on desktop. that way we can broaden the list of supported platforms. we'll look at this below. it's also easier to test control-independent features like gameplay on desktop if you develop it there, so you don't have to push the files to a mobile device every time you make a change in the source code. note: the captain rogers: battle at andromeda is built with phaser and managing the controls is phaser-based, but it could also be done in pure javascript. the good thing about using phaser is that it offers helper variables and functions for easier and faster de...
Mobile touch controls - Game development
as")[0]; el.addeventlistener("touchstart", handlestart); el.addeventlistener("touchmove", handlemove); el.addeventlistener("touchend", handleend); el.addeventlistener("touchcancel", handlecancel); this way, touching the game's <canvas> on the mobile screen would emit events, and thus we could manipulate the game in any way we want (for example, moving the space ship around). the events are as follows: touchstart is fired when the user puts a finger on the screen. touchmove is fired when they move the finger on the screen while touching it touchend is fired when the user stops touching the screen touchcancel is fired when a touch is cancelled, for example when the user moves their finger outside of the screen. note: the touch events reference article provides more examples and inform...
Techniques for game development - Game development
dio and video communication, webrtc lets you set up peer-to-peer data channels to exchange text or binary data actively between your players. this article explains what this can do for you, and shows how to use libraries that make this easy. efficient animation for web games this article covers techniques and advice for creating efficient animation for web games, with a slant towards supporting lower end devices such as mobile phones. we touch on css transitions and css animations, and javascript loops involving window.requestanimationframe. audio for web games audio is an important part of any game — it adds feedback and atmosphere. web-based audio is maturing fast, but there are still many browser differences to negotiate. this article provides a detailed guide to implementing audio f...
asm.js - Game development
asm.js is a specification defining a subset of javascript that is highly optimizable. this article looks at exactly what is permitted in the asm.js subset, what improvements it confers, where and how you can make use of it, and further resources and examples. what is asm.js, exactly? it is a very small, strict subset of javascript that only allows things like `while`, `if`, numbers, top-level named functions, and other simple constructs. it does not allow objects, strings, closures, and basically anything that requires heap allocation. asm.js code resembles c in many ways, but it's still completely valid javascript that will run in all current engines. it pushes js engines to optimize this kind of code, and gives compilers like emscripten a clear definition of what kind of code to ...
2D breakout game using Phaser - Game development
nt, we would suggest that you first work through this series' counterpart, 2d breakout game using pure javascript. after that, you can pick any framework you like and use it for your projects; we have chosen phaser as it is a good solid framework, with a good support and community available, and a good set of plugins. frameworks speed up development time and help take care of the boring parts, allowing you to concentrate on the fun stuff. however, frameworks are not always perfect, so if something unexpected happens or you want to write some functionality that the framework does not provide, you will need some pure javascript knowledge. note: this series of articles can be used as material for hands-on game development workshops. you can also make use of the gamedev phaser content kit base...
Tutorials - Game development
2d breakout game using pure javascript in this step-by-step tutorial you'll implement a simple breakout clone using pure javascript. along the way you will learn the basics of using the <canvas> element to implement fundamental game mechanics like rendering and moving images, collision detection, control machanisms, and winning and losing states. 2d breakout game using phaser in this step-by-step tutorial you'll implement the same breakout clone as the previous tutorial series, except that this time you'll do it using thephaser html5 game framework. ...
Character sets supported by Gecko - Gecko Redirect 1
...
Ajax - MDN Web Docs Glossary: Definitions of Web-related terms
ajax, which initially stood for asynchronous javascript and xml, is a programming practice of building complex, dynamic webpages using a technology known as xmlhttprequest. ajax allows you to update parts of the dom of an html page instead without the need for a full page refresh. ajax also lets you work asynchronously, meaning your code continues to run while the targeted part of your web page is trying to reload (compared to synchronously, which blocks your code from running until that part of your page is done reloading). with interactive websites and modern web standards, ajax is gradually being replaced by functions within javascript frameworks and the official fetch api standard. ...
Accessibility tree (AOM) - MDN Web Docs Glossary: Definitions of Web-related terms
...
Alpha (alpha channel) - MDN Web Docs Glossary: Definitions of Web-related terms
olor channels describe how much red, green, and blue are used to make up the final color. to represent a color through which the background can be seen to some extent, a fourth channel is added to the color: the alpha channel. the alpha channel specifies how opaque the color is. for example, the color #8921f2 (also described as rgb(137, 33, 242) or hsl(270, 89%, 54)) is a nice shade of purple. below you see a small box of that color in the top-left corner and a box of the same color but with an alpha channel set at 0.5 (50% opacity). the two boxes are drawn on top of a paragraph of text. as you can see, the color without an alpha channel completely blocks the background text, while the box with the alpha channel leaves it visible through the purple background color. learn more general k...
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
ript 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 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. s...
Attribute - MDN Web Docs Glossary: Definitions of Web-related terms
you may see attributes without the equals sign or a value. that is a shorthand for providing the empty string in html, or the attribute’s name in xml. ...
Block (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
for example, <p> is by default a block-level element, whereas <a> is an inline element — you can put several links next to one another in your html source and they will sit on the same line as one another in the rendered output. ...
Block - MDN Web Docs Glossary: Definitions of Web-related terms
the term block can have several meanings depending on the context. it may refer to: block (css) a block on a webpage is an html element that appears on a new line, i.e. underneath the preceding element in a horizontal writing mode, and above the following element (commonly known as a block-level element). for example, <p> is by default a block-level element, whereas <a> is an inline element — you can put several links next to one another in your html source and they will sit on the same line as one another in the rendered output. block (scripting) in javascript, a block is a collection of related statements enclosed in braces ("{}"). for example, you can put a block of statements after an if (condition) block, indicating that the interpreter should run the code i...
Boolean - MDN Web Docs Glossary: Definitions of Web-related terms
in computer science, a boolean is a logical data type that can have only the values true or false. for example, in javascript, boolean conditionals are often used to decide which sections of code to execute (such as in if statements) or repeat (such as in for loops). below is some javascript pseudocode (it's not truly executable code) demonstrating this concept. /* javascript if statement */ if (boolean conditional) { // code to execute if the conditional is true } if (boolean conditional) { console.log("boolean conditional resolved to true"); } else { console.log("boolean conditional resolved to false"); } /* javascript for loop */ for (control variable; boolean conditional; counter) { // code to execute repeatedly if the conditional is true } for (var i=0; i < 4; i++)...
Breadcrumb - MDN Web Docs Glossary: Definitions of Web-related terms
a breadcrumb, or breadcrumb trail, is a navigational aid that is typically placed between a site's header and the main content, displaying either a hierarchy of the current page in relation to the the site's structure, from top level to current page, or a list of the links the user followed to get to the current page, in the order visited. a location breadcrumb for this document might look something like this: mdn > glossary > breadcrumb breadcrumb trails enable users to be aware of their location within a website. this type of navigation, if done correctly, helps users know where they are in a site and how they got there. they can also help a user get back to where they were before and can reduce the number of clicks needed to get to a higher-level page. ...
CDN - MDN Web Docs Glossary: Definitions of Web-related terms
ervers can fulfill data requests based on which servers are closest to the respective end-users. cdns make for fast service less affected by high traffic. cdns are used widely for delivering stylesheets and javascript files (static assets) of libraries like bootstrap, jquery etc. using cdn for those library files is preferable for a number of reasons: serving libraries' static assets over cdn lowers the request burden on an organization's own servers. most cdns have servers all over the globe, so cdn servers may be geographically nearer to your users than your own servers. geographical distance affects latency proportionally. cdns are already configured with proper cache settings. using a cdn saves further configuration for static assets on your own servers. ...
CMS - MDN Web Docs Glossary: Definitions of Web-related terms
a cms (content management system) is software that allows users to publish, organize, change, or remove various kinds of content, not only text but also embedded images, video, audio, and interactive code. learn more general knowledge content management system on wikipedia ...
CORS-safelisted request header - MDN Web Docs Glossary: Definitions of Web-related terms
a cors-safelisted request header is one of the following http headers: accept, accept-language, content-language, content-type. when containing only these headers (and values that meet the additional requirements laid out below), a requests doesn't need to send a preflight request in the context of cors. you can safelist more headers using the access-control-allow-headers header and also list the above headers there to circumvent the following additional restrictions: additional restrictions cors-safelisted headers must also fulfill the following requirements in order to be a cors-safelisted request header: for accept-language and content-language: can only have values consisting of 0-9, a-z, a-z, space or *,-.;=. for accept and content-type: can't contain a cors-unsafe...
CORS-safelisted response header - MDN Web Docs Glossary: Definitions of Web-related terms
a cors-safelisted response header is an http header which has been safelisted so that it will not be filtered when responses are processed by cors, since they're considered safe (as the headers listed in access-control-expose-headers). ...
CRLF - MDN Web Docs Glossary: Definitions of Web-related terms
l characters or bytecode that can be used to mark a line break in a text file. cr = carriage return (\r, 0x0d in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line. lf = line feed (\n, 0x0a in hexadecimal, 10 in decimal) — moves the cursor down to the next line without returning to the beginning of the line. a cr immediately followed by a lf (crlf, \r\n, or 0x0d0a) moves the cursor down to the next line and then to the beginning of the line. learn moreedit general knowledge newline on wikipedia carriage return on wikipedia ...
CSS - MDN Web Docs Glossary: Definitions of Web-related terms
ly. a style declaration contains the properties and their values, which determine how a webpage looks. 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. a css rule is a set of properties associated with a selector. here is an example that makes every html paragraph yellow against a black background: /* the selector "p" indicates that all paragraphs in the document will be affected by that rule */ p { /* the "color" property defines the text color, in this case yellow. */ color: yellow; /* the "background-color" property defines the background color, in this case black. */ background-color: black } "cascading" refers to the rules that govern how selector...
CSS Object Model (CSSOM) - MDN Web Docs Glossary: Definitions of Web-related terms
d other relationship. the cssom is very similar to the document object model (dom). both of them are part of the critical rendering path which is a series of steps that must happen to properly render a website. the cssom, together with the dom, to build the render tree, which is in turn used by the browser to layout and paint the web page. cssom api the css object model is also a set of apis allowing the manipulation of css from javascript. it is much like the dom, but for the css rather than the html. it allows users to read and modify the css style dynamically. see also populating the page: how browsers work ...
Selector (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
a css selector is the part of a css rule that describes what elements in a document the rule will match. the matching elements will have the rule's specified style applied to them. consider this css: p { color: green; } div.warning { width: 100%; border: 2px solid yellow; color: white; background-color: darkred; padding: 0.8em 0.8em 0.6em; } #customized { font: 16px lucida grande, arial, helvetica, sans-serif; } the selectors here are "p" (which applies the color green to the text inside any <p> element), "div.warning" (which makes any <div> element with the class "warning" look like a warning box), and "#customized", which sets the base font of the element with the id "customized" to 16-pixel tall lucida grande or one of a few fallback fonts. we can then apply t...
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
hen starts carrying out the function. any functions that are called by that function are added to the call stack further up, and run where their calls are reached. when the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing. if the stack takes up more space than it had assigned to it, it results in a "stack overflow" error. example function greeting() { // [1] some codes here sayhi(); // [2] some codes here } function sayhi() { return "hi!"; } // invoke the `greeting` function greeting(); // [3] some codes here the code above would be executed like this: ignore all functions, until it reaches the greeting() function invocation. add the greeting() function to the call stack list. c...
Canonical order - MDN Web Docs Glossary: Definitions of Web-related terms
the description of the formal syntax used for css values on mdn ...
Cipher - MDN Web Docs Glossary: Definitions of Web-related terms
yptographically secure except for the one-time pad. modern ciphers are designed to withstand attacks discovered by a cryptanalyst. there is no guarantee that all attack methods have been discovered, but each algorithm is judged against known classes of attacks. ciphers operate two ways, either as block ciphers on successive blocks, or buffers, of data, or as stream ciphers on a continuous data flow (often of sound or video). they also are classified according to how their keys are handled: symmetric key algorithms use the same key to encode and decode a message. the key also must be sent securely if the message is to stay confidential. asymmetric key algorithms use a different key for encryption and decryption. ...
Client hints - MDN Web Docs Glossary: Definitions of Web-related terms
client hints enable automated delivery of optimized assets like the automatic negotiation of image dpr resolution. use of client hints isn't automatic: rather, servers must announce that they support client hints. servers announce support for client hints using the accept-ch (accept client hints) header or an equivalent html meta element with the http-equiv attribute. ...
Compile - MDN Web Docs Glossary: Definitions of Web-related terms
rmonkey javascript engine has a jit built-in that will compile javascript in a website to machine code while you're viewing it so it runs faster. projects like webassembly work on making this even better. learn more general knowledge compiler on wikipedia the gnu compiler collection (gcc) learning resources base cs introduction on compilers a big list of learning material on stackoverflow ...
Computer Programming - MDN Web Docs Glossary: Definitions of Web-related terms
am 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. learn more general knowledge computer programming on wikipedia list of programming languages: wikipedia ...
Continuous Media - MDN Web Docs Glossary: Definitions of Web-related terms
web content displayed on a screen is continuous media, as is spoken content. ...
Cross-site scripting - MDN Web Docs Glossary: Definitions of Web-related terms
this code is executed by the victims and lets the attackers bypass access controls and impersonate users. according to the open web application security project, xss was the seventh most common web app vulnerability in 2017. these attacks succeed if the web app does not employ enough validation or encoding. the user's browser cannot detect the malicious script is untrustworthy, and so gives it access to any cookies, session tokens, or other sensitive site-specific information, or lets the malicious script rewrite the html content. ...
DOM (Document Object Model) - MDN Web Docs Glossary: Definitions of Web-related terms
the dom (document object model) is an api that represents and interacts with any html or xml document. the dom is a document model loaded in the browser and representing the document as a node tree, where each node represents part of the document (e.g. an element, text string, or comment). the dom is one of the most-used apis on the web because it allows code running in a browser to access and interact with every node in the document. nodes can be created, moved and changed. event listeners can be added to nodes and triggered on occurrence of a given event. dom was not originally specified—it came about when browsers began implementing javascript. this legacy dom is sometimes called dom 0. today, the whatwg maintains the dom living standard. ...
DTLS (Datagram Transport Layer Security) - MDN Web Docs Glossary: Definitions of Web-related terms
ansport layer security (dtls) is a protocol used to secure datagram-based communications. it's based on the stream-focused transport layer security (tls), providing a similar level of security. as a datagram protocol, dtls doesn't guarantee the order of message delivery, or even that messages will be delivered at all. however, dtls gains the benefits of datagram protocols, too; in particular, the lower overhead and reduced latency. these features are especially useful for one of the most common areas in which dtls comes into play: webrtc. all of the webrtc related protocols are required to encrypt their communications using dtls; this includes sctp, srtp, and stun. learn more general knowledge datagram transport layer security on wikipedia specifications rfc 6347: datagram transpor...
Deserialization - MDN Web Docs Glossary: Definitions of Web-related terms
that has been transferred over a network, or stored in a data store) is translated into a readable object or other data structure. in javascript, for example, you can deserialize a json string to an object by calling the function json.parse(). ...
Developer Tools - MDN Web Docs Glossary: Definitions of Web-related terms
developer tools (or "development tools" or short "devtools") are programs that allow a developer to create, test and debug software. current browsers provide integrated developer tools, which allow to inspect a website. they let users inspect and debug the page's html, css, and javascript, allow to inspect the network traffic it causes, make it possible to measure it's performance, and much more. learn more general knowledge web development tools on wikipedia technical reference firefox developer tools on mdn firebug (former developer tool for firefox) chrome devtools on chrome.com safari web inspector on apple.com edge dev tools on microsoft.com ...
Doctype - MDN Web Docs Glossary: Definitions of Web-related terms
in html, the doctype is the required "<!doctype html>" preamble found at the top of all documents. its sole purpose is to prevent a browser from switching into so-called “quirks mode” when rendering a document; that is, the "<!doctype html>" doctype ensures that the browser makes a best-effort attempt at following the relevant specifications, rather than using a different rendering mode that is incompatible with some specifications. learn more general knowledge definition of the doctype in the html specification quirks mode and standards mode technical reference document.doctype, a javascript method that returns the doctype ...
Domain - MDN Web Docs Glossary: Definitions of Web-related terms
by name unambigously using the dns system of the internet. for example, in "developer.mozilla.org": "org" is called a top-level domain. they are registered as an internet standard by the iana . here, "org" means "organization" which is defined in a top-level domain registry. "mozilla" is the domain. if you like to own a domain you have to register it with one of the many registrars who are allowed to do so with a top-level domain registry. "developer" is a "sub-domain", something you as the owner of a domain may define yourself. many owners choose to have a subdomain "www" to point to their world_wide_web resource, but that's not required (and has even fallen somewhat out of favor). learn more domain name on wikipedia ...
Domain sharding - MDN Web Docs Glossary: Definitions of Web-related terms
cost of extra dns lookups for each domain and the overhead of establishing each tcp connection. the initial response from an http request is generally an html file listing other resources such as javascript, css, images and other media files that need to be downloaded. as browsers limit the number of active connections per domain, serving all the required resources from a single domain could be slow as assets need to be downloaded sequentially. with domain sharding, the required downloads are served from more than one domain, enabling the browser to simultaneously download needed resources. multiple domains, however, is an anti-pattern, as dns lookups slow initial load times. http2 supports unlimited concurrent requests making domain sharding an obsolete requirement when http/2 is enabled. ...
Empty element - MDN Web Docs Glossary: Definitions of Web-related terms
nested elements or text nodes). the html, svg, and mathml specifications define very precisely what each element can contain. ...
Endianness - MDN Web Docs Glossary: Definitions of Web-related terms
index or address. every byte can store an 8-bit number (i.e. between 0x00 and 0xff), so you must reserve more than one byte to store a larger number. by far the most common ordering of multiple bytes in one number is the little-endian, which is used on all intel processors. little-endian means storing bytes in order of least-to-most-significant (where the least significant byte takes the first or lowest address), comparable to a common european way of writing dates (e.g., 31 december 2050). naturally, big-endian is the opposite order, comparable to an iso date (2050-12-31). big-endian is also often called "network byte order", because internet standards usually require data to be stored big-endian, starting at the standard unix socket level and going all the way up to standardized web binary...
Entity - MDN Web Docs Glossary: Definitions of Web-related terms
ities. for example, the entity for the copyright symbol (©) is &copy;. for less memorable characters, such as &#8212; or &#x2014;, you can use a reference chart or decoder tool. reserved characters some special characters are reserved for use in html, meaning that your browser will parse them as html code. for example, if you use the less-than (<) sign, the browser interprets any text that follows as a tag. to display these characters as text, replace them with their corresponding character entities, as shown in the following table. character entity note & &amp; interpreted as the beginning of an entity or character reference. < &lt; interpreted as the beginning of a tag > &gt; interpreted as the ending of a tag " ...
Entity header - MDN Web Docs Glossary: Definitions of Web-related terms
an entity header is an http header that can be used in an http request or response, and describes the content of the body of themessage. headers like content-length, content-language, content-encoding are entities headers. even if they are neither request, nor response headers, entity headers are often included in such terms. ...
FTP - MDN Web Docs Glossary: Definitions of Web-related terms
ftp (file transfer protocol) was the standard protocol for many years for transferring files from one host to another over the internet. increasingly, though, teams and hosting accounts don't allow ftp and instead rely on a version control system like git. you will still find it used on older hosting accounts, but it is safe to say that ftp is no longer considered best practice. learn more general knowledge beginner's guide to uploading files via ftp ftp on wikipedia ...
Fallback alignment - MDN Web Docs Glossary: Definitions of Web-related terms
in css box alignment, a fallback alignment is specified in order to deal with cases where the requested alignment cannot be fullfilled. for example, if you specify justify-content: space-between there must be more than one alignment subject. if there is not, the fallback alignment is used. this is specified per alignment method, as detailed below. first baseline start last baseline safe end baseline start space-between flex-start (start) space-around center space-evenly center stretch flex-start (start) learn more css box alignment ...
Falsy - MDN Web Docs Glossary: Definitions of Web-related terms
falsey) value is a value that is considered false when encountered in a boolean context. javascript uses type conversion to coerce any value to a boolean in contexts that require it, such as conditionals and loops. there are 8 falsy values: false the keyword false 0 the number zero -0 the number negative zero 0n bigint, when used as a boolean, follows the same rule as a number. 0n is falsy. "" empty string value null null - the absence of any value undefined undefined - the primitive value nan nan - not a number objects are falsy if and only if they have the [[ishtmldda]] internal slot. this slot only exists in document.all and cannot be set using javascript. examples example...
Fetch metadata request header - MDN Web Docs Glossary: Definitions of Web-related terms
er that provides additional information about the context the request originated from. ...
First input delay - MDN Web Docs Glossary: Definitions of Web-related terms
ser’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 the user experience. reducing site initialization time and eliminating long tasks can help eliminate first input delays. see also requestidlecallback lazy loading ...
Flex - MDN Web Docs Glossary: Definitions of Web-related terms
ticipate in flex layout, and all of the properties defined in the css flexible box layout module may be applied. the flex property is a shorthand for the flexbox properties flex-grow, flex-shrink and flex-basis. in addition <flex> can refer to a flexible length in css grid layout. ...
Flex Container - MDN Web Docs Glossary: Definitions of Web-related terms
level flex container, and inline-flex an inline level flex container. ...
Flexbox - MDN Web Docs Glossary: Definitions of Web-related terms
n a flex layout can grow and shrink. space can be assigned to the items themselves, or distributed between or around the items. flexbox also enables alignment of items on the main or cross axis, thus providing a high level of control over the size and alignment of a group of items. ...
Forbidden header name - MDN Web Docs Glossary: Definitions of Web-related terms
tp request header name (in contrast with a forbidden response header name). modifying such headers is forbidden because the user agent retains full control over them. names starting with `sec-` are reserved for creating new headers safe from apis using fetch that grant developers control over headers, such as xmlhttprequest. ...
Fork - MDN Web Docs Glossary: Definitions of Web-related terms
forks are often seen in free and open source software development. this is now a more popular term thanks to contribution model using git (and/or the github platform). ...
Gzip compression - MDN Web Docs Glossary: Definitions of Web-related terms
gzip is a file format used for file compression and decompression. it is based on the deflate algorithm that allows files to be made smaller in size which allows for faster network transfers. gzip is commonly supported by web servers and modern browsers, meaning that servers can automatically compress files with gzip before sending them, and browsers can uncompress files upon receiving them. learn more how to enable compression and gzip for page speed. gzip on wikipedia ...
Gonk - MDN Web Docs Glossary: Definitions of Web-related terms
the kernel and several of the userspace libraries are common open-source projects: linux, libusb, bluez, and so forth. some other parts of the hal are shared with aosp: gps, camera, and others. you could call gonk a very simple linux distribution. gonk is a porting target of gecko (just as gecko has been ported to os x, windows, and android). since firefox os has full control over gonk, we can expose interfaces to gecko that aren't accessible on other operating systems, for example the full telephony stack and display frame buffer. ...
Graceful degradation - MDN Web Docs Glossary: Definitions of Web-related terms
ers essential content and functionality in older browsers. polyfills can be used to build in missing features with javascript, but acceptable alternatives to features like styling and layout should be provided where possible, for example by using the css cascade, or html fallback behaviour. some good examples can be found in handling common html and css problems. it is a useful technique that allows web developers to focus on developing the best possible websites, given that those websites are accessed by multiple unknown user-agents. progressive enhancement is related but different — often seen as going in the opposite direction to graceful degredation. in reality both approaches are valid and can often complement one another. ...
Grid - MDN Web Docs Glossary: Definitions of Web-related terms
described as an explicit grid. if you place content outside of this explicit grid, or if you are relying on auto-placement and the grid algorithm needs to create additional row or column tracks to hold grid items, then extra tracks will be created in the implicit grid. the implicit grid is the grid created automatically due to content being added outside of the tracks defined. in the example below i have created an explicit grid of three columns and two rows. the third row on the grid is an implicit grid row track, formed due to their being more than the six items which fill the explicit tracks. * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-radius...
Grid Areas - MDN Web Docs Glossary: Definitions of Web-related terms
a grid area is one or more grid cells that make up a rectangular area on the grid. grid areas are created when you place an item using line-based placement or when defining areas using named grid areas. grid areas must be rectangular in nature; it is not possible to create, for example, a t- or l-shaped grid area. in the example below i have a grid container with two grid items. i have named these with the grid-area property and then laid them out on the grid using grid-template-areas. this creates two grid areas, one covering four grid cells, the other two. * {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: ...
Grid Axis - MDN Web Docs Glossary: Definitions of Web-related terms
in any grid we have two axes. the block or column axis, and the inline or row axis. it is along these axes that items can be aligned and justified using the properties defined in the box alignment specification. in css the block or column axis is the axis used when laying out blocks of text. if you have two paragraphs and are working in a right to left, top to bottom language they lay out one below the other, on the block axis. the inline or row axis runs across the block axis and is the direction along which regular text flows. these are our rows in css grid layout. the physical direction of these axes can change according to the writing mode of the document. learn more further reading css grid layout guide: basic concepts of grid layout css grid layout guide: box alignment in ...
Grid Tracks - MDN Web Docs Glossary: Definitions of Web-related terms
a grid track is the space between two grid lines. they are defined in the explicit grid by using the grid-template-columns and grid-template-rows properties or the shorthand grid or grid-template properties. tracks are also created in the implicit grid by positioning a grid item outside of the tracks created in the explicit grid. the image below shows the first row track on a grid. track sizing in the explicit grid when defining grid tracks using grid-template-columns and grid-template-rows you may use any length unit, and also the flex unit, fr which indicates a portion of the available space in the grid container. the example below demonstrates a grid with three column tracks, one of 200 pixels, the second of 1fr, the third of 3fr. once the 200 pixels has been subtracted from t...
Gutters - MDN Web Docs Glossary: Definitions of Web-related terms
gutters or alleys are spacing between content tracks. these can be created in css grid layout using the grid-column-gap, grid-row-gap, or grid-gap properties. in the example below we have a three-column and two-row track grid, with 20-pixel gaps between column tracks and 20px-gaps between row tracks. * {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: #fff8f8; padding: 1em; color: #d9480f; } .wrapper { display: grid; grid-template-columns: repeat(3,1.2fr); grid-auto-rows: 45%; grid-column-gap: 20px; grid-row-gap: 20px; } <div class="wrapper"> <div>one</div> <div>two</div> <div>thre...
HTML - MDN Web Docs Glossary: Definitions of Web-related terms
the ietf began formally specifying html in 1993, and after several drafts released version 2.0 in 1995. in 1994 berners-lee founded the w3c to develop the web. in 1996, the w3c took over the html work and published the html 3.2 recommendation a year later. ...
Houdini - MDN Web Docs Glossary: Definitions of Web-related terms
houdini gives developers access to the css object model (cssom), enabling developers to write code the browser can parse as css. the benefit of houdini is that developers can create css features without waiting for web standards specifications to define them and without waiting for every browser to fully implement the features. while many of the features houdini enables can be created with javascript, interacting directly with the cssom before javascript is enabled provides for faster parse times. ...
Hypertext - MDN Web Docs Glossary: Definitions of Web-related terms
the term was coined by ted nelson around 1965. ...
ICE - MDN Web Docs Glossary: Definitions of Web-related terms
by webrtc (among other technologies) for connecting two peers, regardless of network topology (usually for audio and video chat). this protocol lets two peers find and establish a connection with one another even though they may both be using network address translator (nat) to share a global ip address with other devices on their respective local networks. ...
IDL - MDN Web Docs Glossary: Definitions of Web-related terms
pass another type, it is automatically converted to a number as specified by the standard javascript rules for type conversion. idl attributes can reflect other types such as unsigned long, urls, booleans, etc. unfortunately, there are no clear rules and the way idl attributes behave in conjunction with their corresponding content attributes depends on the attribute. most of the time, it will follow the rules laid out in the specification, but sometimes it doesn't. html specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes behave oddly (select.size, for example) and you should read the specifications to understand how exactly they behave. learn more general knowledge idl on wikipedia html attribute reference te...
IMAP - MDN Web Docs Glossary: Definitions of Web-related terms
clients accessing a mailbox can receive information about state changes made from other clients. imap also provides a mode for clients to stay connected and receive information on demand. mark crispin initially developed imap in 1986 as interim mail access protocol. ...
IPv6 - MDN Web Docs Glossary: Definitions of Web-related terms
ipv6 is the current version of the communication protocol underlying the internet. slowly ipv6 is replacing ipv4, among other reasons because ipv6 allows for many different ip addresses. learn more general knowledge ipv6 on wikipedia ...
Java - MDN Web Docs Glossary: Definitions of Web-related terms
ed, highly portable programming language. 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". learn more general knowledge java on wikipedia ...
JavaScript - MDN Web Docs Glossary: Definitions of Web-related terms
ince then, the standardized javascript is called ecmascript and specified under ecma-262, whose latest (tenth, es2019) edition is available as of june 2019. recently, javascript's popularity has expanded even further through the successful node.js platform—the most popular cross-platform javascript runtime environment outside the browser. node.js - built using chrome's v8 javascript engine - allows developers to use javascript as a scripting language to automate things on a computer and build fully functional http and web sockets servers. learn more general knowledge javascript on wikipedia learning javascript the javascript guide on mdn the "javascripting" workshop on nodeschool the javascript course on codecademy.com john resig's learning advanced javascript technical refe...
Latency - MDN Web Docs Glossary: Definitions of Web-related terms
latency is the network time it takes for a requested resource to reach its destination. low latency is good, meaning there is little or no delay. high latency is bad, meaning it takes a long time for the requested resource to reach its destination. latency can be a factor in any kind of data flow, but is most commonly discussed in terms of network latency (the time it takes for a packet of data to travel from source to destination) and media codec latency (the time it takes for the source data to be encoded or decoded and reach the consumer of the resulting data). learn more understanding latency ...
Localization - MDN Web Docs Glossary: Definitions of Web-related terms
localization (l10n) is the process of adapting a software user interface to a specific culture. the following are common factors to consider: language unit of measure (e.g., kilometers in europe, miles in u.s.) text direction (e.g., european languages are left-to-right, arabic right-to-left) capitalization in latin script (e.g., english uses capitals for weekdays, spanish uses lowercase) adaptation of idioms (e.g., "raining cats and dogs" makes no sense when translated literally) use of register (e.g., in japanese respectful speech differs exceptionally from casual speech) number format (e.g., 10 000,00 in germany vs. 10,000.00 in the u.s.) date format currency cultural references paper size color psychology compliance with local laws local holidays personal names ...
Long task - MDN Web Docs Glossary: Definitions of Web-related terms
a long task is a task that takes more than 50ms to complete. it is an uninterrupted period where the main ui thread is busy for 50 ms or longer. common examples include long running event handlers, expensive reflows and other re-renders, and work the browser does between different turns of the event loop that exceeds 50 ms. see also long task api ...
Lossless compression - MDN Web Docs Glossary: Definitions of Web-related terms
lossless compression methods are reversible. ...
Main thread - MDN Web Docs Glossary: Definitions of Web-related terms
this means that long-running javascript functions can block the thread, leading to an unresponsive page and a bad user experience. ...
Mutable - MDN Web Docs Glossary: Definitions of Web-related terms
bjects whose state cannot be changed once the object is created. strings and numbers are immutable. lets understand this with an example: var immutablestring = "hello"; // in the above code, a new object with string value is created. immutablestring = immutablestring + "world"; // we are now appending "world" to the existing value. on appending the "immutablestring" with a string value, following events occur: existing value of "immutablestring" is retrieved "world" is appended to the existing value of "immutablestring" the resultant value is then allocated to a new block of memory "immutablestring" object now points to the newly created memory space previously created memory space is now available for garbage collection. learn more general knowledge immutable object on ...
Node.js - MDN Web Docs Glossary: Definitions of Web-related terms
node.js is a cross-platform javascript runtime environment that allows developers to build server-side and network applications with javascript. learn more general knowledge node.js on wikipedia node.js website technical information api reference documentation tutorials ...
Normative - MDN Web Docs Glossary: Definitions of Web-related terms
normative is a word commonly used in software specifications to denote sections that are standardized and must be followed as a rule. specifications might also contain sections that are marked as non-normative or informative, which means those are provided there for the purpose of helping the reader understand the specifications better or to showcase an example or best practice, which need not be followed as a rule. learn more description of normative and informative content in whatwg wiki ...
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). learn more general knowledge object-oriented programming on wikipedia introduction to object-oriented javascript ...
POP3 - MDN Web Docs Glossary: Definitions of Web-related terms
nearly all email servers and clients currently support pop3. ...
Packet - MDN Web Docs Glossary: Definitions of Web-related terms
error-correcting code which automatically corrects the errors at the transmitter, the calculation is performed before the packet is sent. when received at the destination, the checksum is recalculated, and compared with the one in the packet. priority this field indicates which packet should have higher priority over the others. the high priority queue is emptied more quickly than lower priority queues when the network is congested. addresses when routing network packets it requires two network addresses the source address of the sending host, and the destination address of the receiving host. user data - payload payload is the data that is carried on behalf of an application. it is usually of variable length, up to a maximum that is set by the network prot...
Port - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the default port for the http protocol is 80 and the default port for the https protocol is 443, so a http server waits for requests on those ports. ...
Prefetch - MDN Web Docs Glossary: Definitions of Web-related terms
prefetching is when content is downloaded in the background, this is based on the assumption that the content will likely be requested, enabling the content to load instantly if and when the user requests it. the content is downloaded and cached for anticipated future use without the user making an explicit request for it. dns prefetching domain lookups can be slow, especially with network latency on mobile phones. they are most relevant when 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...
Progressive Enhancement - MDN Web Docs Glossary: Definitions of Web-related terms
he 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 thing and is often seen as going in the opposite direction to progressive enhancement. in reality both approaches are valid and can often complement one another. learn more general knowledge progressive enhance...
Prototype-based programming - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge prototype-based programming on wikipedia ...
Pseudo-class - MDN Web Docs Glossary: Definitions of Web-related terms
learn more technical reference pseudo-class documentation ...
Public-key cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
rated it. when used for encryption, the public key is used to encrypt and the private key is used to decrypt. this gives public-key encryption systems an advantage over symmetric encryption systems in that the encryption key can be made public. anyone could encrypt a message to the owner of the private key, but only the owner of the private key could decrypt it. however, they are typically much slower than symmetric algorithms and the size of message they can encrypt is proportional to the size of the key, so they do not scale well for long messages. as a result, it's common for an encryption system to use a symmetric algorithm to encrypt the message, then a public-key system to encrypt the symmetric key. this arrangement can confer the benefits of both systems. commonly used public-key cr...
QUIC - MDN Web Docs Glossary: Definitions of Web-related terms
quick udp internet connection, or quic, is an experimental multiplexed transport protocol implemented on udp. it was developed by google as a way to experiment with ways to improve tcp and web application delivery. as tcp is built into the kernel of many operating systems being able to experiment with changes, test them and implement modifications is an extremely slow process. the creation of quic allows developers to conduct experiments and try new things faster. quic was designed to support the semantics of http/2. it provides multiplexing, flow control, security and congestion control. key features of quic include: reduction in connection establishment time. improved congestion control. multiplexing without head-of-line blocking. forward error correction. connection mig...
Recursion - MDN Web Docs Glossary: Definitions of Web-related terms
the act of a function calling itself, recursion is used to solve problems that contain smaller sub-problems. a recursive function can receive two inputs: a base case (ends recursion) or a recursive case (resumes recursion). examples recursive function calls itself until condition met the following python code defines a function that takes a number, prints it, and then calls itself again with the number's value -1. it keeps going until the number is equal to 0, in which case it stops. def recurse(x): if x > 0: print(x) recurse(x - 1) recurse(10) the output will look like this: 10 9 8 7 6 5 4 3 2 1 0 learn more general knowledge recursion (computer science) on wikipedia more details about recursion in javascript ...
Request header - MDN Web Docs Glossary: Definitions of Web-related terms
not all headers appearing in a request are request headers. for example, the content-length appearing in a post request is actually an entity header referring to the size of the body of the request message. however, these entity headers are often called request headers in such a context. ...
SEO - MDN Web Docs Glossary: Definitions of Web-related terms
seo (search engine optimization) is the process of making a website more visible in search results, also termed improving search rankings. search engines crawl the web, following links from page to page, and index the content found. when you search, the search engine displays the indexed content. crawlers follow rules. if you follow those rules closely when doing seo for a website, you give the site the best chances of showing up among the first results, increasing traffic and possibly revenue (for ecommerce and ads). search engines give some guidelines for seo, but big search engines keep result ranking as a trade secret. seo combines official search engine guidelines, empirical knowledge, and theoretical knowledge from science papers or patents. seo methods fall into three broad ...
SIMD - MDN Web Docs Glossary: Definitions of Web-related terms
simd (pronounced "sim-dee") is short for single instruction/multiple data which is one classification of computer architectures. simd allows one same operation to be performed on multiple data points resulting in data level parallelism and thus performance gains — for example, for 3d graphics and video processing, physics simulations or cryptography, and other domains. see also sisd for a sequential architecture with no parallelism in either the instructions or the data sets. ...
SISD - MDN Web Docs Glossary: Definitions of Web-related terms
sisd is short for single instruction/single data which is one classification of computer architectures. in sisd architecture, a single processor executes a single instruction and operates on a single data point in memory. see also simd for a parallel architecture that allows one same operation to be performed on multiple data points. learn more general knowledge sisd on wikipedia ...
SPA (Single-page application) - MDN Web Docs Glossary: Definitions of Web-related terms
an spa (single-page application) is a web app implemention that loads only a single web document, and then updates the body content of that single document via javascript apis such as xmlhttprequest and fetch when different content is to be shown. this therefore allows users to use websites without loading whole new pages from the server, which can result in performance gains and a more dynamic experience, with some tradeoff disadvantages such as seo, more effort required to maintain state, implement navigation, and do meaningful performance monitoring. learn more general knowledge some of the most popular spa frameworks include: react angular vue.js ...
SRI - MDN Web Docs Glossary: Definitions of Web-related terms
subresource integrity (sri) is a security feature that enables browsers to verify that files they fetch (for example, from a cdn) are delivered without unexpected manipulation. it works by allowing you to provide a cryptographic hash that a fetched file must match. learn more subresource integrity content-security-policy: require-sri-for ...
SVG - MDN Web Docs Glossary: Definitions of Web-related terms
scalable vector graphics (svg) is a 2d vector image format based on an xml syntax. the w3c began work on svg in the late 1990s, but svg only became popular when internet explorer 9 came out with svg support. all major browsers now support svg. based on an xml syntax, svg can be styled with css and made interactive using javascript. html5 now allows direct embedding of svg tags in an html document. as a vector image format, svg graphics can scale infinitely, making them invaluable in responsive design, since you can create interface elements and graphics that scale to any screen size. svg also provides a useful set of tools, such as clipping, masking, filters, and animations. learn more general knowledge svg on wikipedia learning svg w3.org's svg primer technical informa...
SVN - MDN Web Docs Glossary: Definitions of Web-related terms
although svn can also handle binary files, we do not recommend that you use it for such files. ...
Scroll container - MDN Web Docs Glossary: Definitions of Web-related terms
a scroll container is created by applying overflow: scroll to a container, or overflow: auto when there is enough content to cause overflow. the scroll container allows the user to scroll through parts of the overflow region that would otherwise be clipped and hidden from view. the visible part of the scroll container is referred to as the scrollport. ...
Scrollport - MDN Web Docs Glossary: Definitions of Web-related terms
the scrollport is the visual viewport of a scroll container in a document. a scroll container is created by applying overflow: scroll to a container, or overflow: auto when there is enough content to cause overflow. the scrollport coincides with the padding box of that container and represents the content that can be seen as the box is scrolled. ...
Search engine - MDN Web Docs Glossary: Definitions of Web-related terms
a web site owner can exclude areas of the site from being accessed by a search engine's web crawler (or spider), by defining "robot exclusion" information in a file named robots.txt. ...
Server Timing - MDN Web Docs Glossary: Definitions of Web-related terms
see also https://www.w3.org/tr/server-timing/ resource timing ...
Session Hijacking - MDN Web Docs Glossary: Definitions of Web-related terms
two machines in mid session. session hijacking occurs because no account lockout for invalid session ids weak session-id generation algorithm insecure handling indefinite session expiration time short session ids transmission in plain text session hijacking process sniff, that is perform a man-in-the-middle (mitm) attack, place yourself between victim and server. monitor packets flowing between server and user. break the victim machine's connection. take control of the session. inject new packets to the server using the victim's session id. protection against session hijacking create a secure communication channel with ssh (secure shell) pass authentication cookies over https connection implement logout functionality so the user can end the session generate the ses...
Site map - MDN Web Docs Glossary: Definitions of Web-related terms
a site map or sitemap is a list of pages of a web site. structured listings of a site's page help with search engine optimization, providing a link for web crawlers such as search engines to follow. site maps also help users with site navigation by providing an overview of a site's content in a single glance. ...
Slug - MDN Web Docs Glossary: Definitions of Web-related terms
a slug is the unique identifying part of a web address, typically at the end of the url. in the context of mdn, it is the portion of the url following "<locale>/docs/". it may also just be the final component when a new document is created under a parent document; for example, this page's slug is glossary/slug . ...
Snap positions - MDN Web Docs Glossary: Definitions of Web-related terms
a scroll container may set snap positions — points that the scrollport will stop moving at after a scrolling operation is completed. this allows a scrolling experience that gives the effect of paging through content rather than needing to drag content into view. defining snap positions on the scroll container was introduced in the css scroll snap specification. ...
Speed index - MDN Web Docs Glossary: Definitions of Web-related terms
speed index (si) is a page load performance metric that shows you how quickly the contents of a page are visibly populated. it is the average time at which visible parts of the page are displayed. expressed in milliseconds, and dependent on the size of the viewport, the lower the score, the better. the calculation calculates what percent of the page is visually complete at every 100ms interval until the page is visually complete. the overall score, the above the fold metric, is a sum of the individual 10 times per second intervals of the percent of the screen that is not-visually complete. ...
State machine - MDN Web Docs Glossary: Definitions of Web-related terms
nsition 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. 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...
Static typing - MDN Web Docs Glossary: Definitions of Web-related terms
a statically-typed language is a language (such as java, c, or c++) where variable types are known at compile time. in most of these languages, types must be expressly indicated by the programmer; in other cases (such as ocaml), type inference allows the programmer to not indicate their variable types. learn more general knowledge type system on wikipedia ...
Stylesheet - MDN Web Docs Glossary: Definitions of Web-related terms
of css rules used to control the layout and design of a webpage or document. internal stylesheets are placed inside a <style> element inside the <head> of a web document, and external stylesheets are placed inside a separate .css file, which is applied to a document by referencing the file inside a <link> element in the document's head. external stylesheets are generally preferred because they allow you to control the styling of multiple pages from a single place, rather than having to repeat the css across each page. learn more general knowledge css first steps stylesheets on wikipedia ...
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
bol registry is mostly built by javascript's compiler infrastructure, and the global symbol registry's content is not available to javascript's run-time infrastructure, except through these reflective methods. ...
TLD - MDN Web Docs Glossary: Definitions of Web-related terms
ld 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-level domains: country-code top-level domains (cctld) two-character domains established for countries or territories. example: .us for united states. internationalized country code top-level domains (idn cctld) cctlds in non-latin character sets (e.g., arabic or chinese). generic top-level domains (gtld) top-level domains with three or more characters. unsponsored top-le...
TURN - MDN Web Docs Glossary: Definitions of Web-related terms
turn (traversal using relays around nat) is a protocol enabling a computer to receive and send data from behind a network address translator (nat) or firewall. turn is used by webrtc to allow any two devices on the internet to enter a peer-to-peer connection. learn more general knowledge turn on wikipedia webrtc protocols technical reference specification specification update for ipv6 ...
Tag - MDN Web Docs Glossary: Definitions of Web-related terms
in html, a tag is used for creating an element. the name of an html element is the name used in angle brackets such as <p> for paragraph. note that the end tag's name is preceded by a slash character, </p>, and that in empty elements, the end tag is neither required nor allowed. if attributes are not mentioned, default values are used in each case. learn more general knowledge html element on wikipedia html elements syntax on whatwg technical reference introduction to html ...
Time to interactive - MDN Web Docs Glossary: Definitions of Web-related terms
tti, proposed by the web incubator community group in 2018, is intended to provide a metric that describes when a page or application contains useful content and the main thread is idle and free to respond to user interactions, including having event handlers registered. ...
VoIP - MDN Web Docs Glossary: Definitions of Web-related terms
voip (voice over internet protocol) is a technology used to transmit voice messages over ip (internet protocol) networks. common voip packages include skype, msn messenger, yahoo and many more. everything transferrred through voip is digital. it is also known as ip telephony, or broadband telephony. the main reason for using voip technology is because of cost. voip allows you to make a call directly from a computer, a special voip phone, or a traditional phone connected to a special adapter. a high speed internet connection is required for voip. usually, telephone calls over the internet do not incur further charges beyond what the user is paying for internet access, much in the same way that the user doesn't pay for sending individual emails over the internet. learn more general k...
WebDAV - MDN Web Docs Glossary: Definitions of Web-related terms
webdav (web distributed authoring and versioning) is an http extension that lets web developers update their content remotely from a client. webdav is rarely used alone, but two extensions are very common: caldav (remote-access calendar) and carddav (remote-access address book). webdav allows clients to add, delete, and retrieve webpage metadata (e.g. author or creation date) link pages of any media type to related pages create sets of documents and retrieve hierarchical list copy and move webpages lock a document from being edited by more than one person at a time learn more general knowledge webdav on wikipedia technical reference rfc 2518 rfc 3253 rfc 3744 ...
WebSockets - MDN Web Docs Glossary: Definitions of Web-related terms
websocket is a protocol that allows for a persistent tcp connection between server and client so they can exchange data at any time. any client or server application can use websocket, but principally web browsers and web servers. through websocket, servers can pass data to a client without prior client request, allowing for dynamic content updates. learn more general knowledge websocket on wikipedia technical reference websocket reference on mdn learn about it writing websocket client applications writing websocket servers ...
Web performance - MDN Web Docs Glossary: Definitions of Web-related terms
learn more learn about web performance perceived performance ...
Array - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, arrays start at index zero and can be manipulated with various methods. ...
Brotli - MDN Web Docs Glossary: Definitions of Web-related terms
-purpose lossless compression algorithm. it compresses data using a combination of a modern variant of the lz77 algorithm, huffman coding, and second-order context modeling, providing a compression ratio comparable to the best currently available general-purpose compression methods. brotli provides better compression ratios than gzip and deflate speeds are comparable, but brotli compressing is a slower process than gzip compression, so gzip may be a better option for the compression of non-cachable content. brotli is compatible with most modern browsers, but you may want to consider a fallback. learn more brotli.org brotli github repository brotli on wikipedia brotli on caniuse ...
caret - MDN Web Docs Glossary: Definitions of Web-related terms
he caret using a thin vertical line or a character-sized box that flashes, but this can vary. this point in the text is called the insertion point. the word "caret" differentiates the text insertion point from the mouse cursor. on the web, a caret is used to represent the insertion point in <input> and <textarea> elements, as well as any elements whose contenteditable attribute is set, thereby allowing the contents of the element to be edited by the user. learn more general knowledge caret navigation on wikipedia css related to the caret you can set the color of the caret for a given element's editable content by setting the element's css caret-color property to the appropriate <color> value. html elements that may present a caret these elements provide text entry fields or boxes a...
Character encoding - MDN Web Docs Glossary: Definitions of Web-related terms
an encoding defines a mapping between bytes and text. a sequence of bytes allows for different textual interpretations. by specifying a particular encoding (such as utf-8), we specify how the sequence of bytes is to be interpreted. for example, in html we normally declare a character encoding of utf-8, using the following line: <meta charset="utf-8"> this ensures that you can use characters from just about any human language in your html document, and they will display reliably. learn more general knowledge character encoding on w3c character encoding on wikipedia ...
HTTPS - MDN Web Docs Glossary: Definitions of Web-related terms
https (hypertext transfer protocol secure) is an encrypted version of the http protocol. it uses ssl or tls to encrypt all communication between a client and a server. this secure connection allows clients to safely exchange sensitive data with a server, such as when performing banking activities or online shopping. ...
jQuery - MDN Web Docs Glossary: Definitions of Web-related terms
anipulation, ajax calls, and event handling. jquery uses a format, $(selector).action() to assign an element(s) to an event. to explain it in detail, $(selector) will call jquery to select selector element(s), and assign it to an event api called .action(). ...
JPEG - MDN Web Docs Glossary: Definitions of Web-related terms
mpression 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 ...
Percent-encoding - MDN Web Docs Glossary: Definitions of Web-related terms
special characters needing encoding are: ':', '/', '?', '#', '[', ']', '@', '!', '$', '&', "'", '(', ')', '*', '+', ',', ';', '=', as well as '%' itself. other characters don't need to be encoded, though they could. ...
Routers - MDN Web Docs Glossary: Definitions of Web-related terms
for spa in application layer, router is a library that decides what web page is presented by a given url. this middleware module is used for all url functions, as these are given a path to a file that is rendered to open the next page. ...
Speculative parsing - MDN Web Docs Glossary: Definitions of Web-related terms
ad 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 override the base uri of your page, put the element in the non-scripted part of the document. don't add it via document.write() or document.createelement. avoiding losing tree builder output speculative tree building fails when d...
Test your skills: The Cascade - Learn web development
the aim of this task is to help you check your understanding of some of the values and units that we looked at in the lesson on the cascade and inheritance. note: you can try out solutions in the interactive 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. task one in this task, you need to use one of the special values we looked at in the controlling inheritance section to write a declaration in a new rule that will reset the background color back to white, without using an actual color value. in the example below see if you can match the image above. for assessment o...
Test your skills: Media Queries and Responsive Design - Learn web development
er 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 want to ask for help: put...
CSS first steps - Learn web development
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 (most of) the code examples in an online coding program such as jsbin or glitch. guides this module contains the following articles, which will take you through all the basic theory of css, and provide opportunities for you to test out some skills. what is css? css (cascading style sheets) allows you to create great-looking web pages, but how does it work under the hood? this article explains what css is, with a simple syntax example, and also covers some key terms about the language. getting started with css...
What do common web layouts contain? - Learn web development
n you start learning about css. why would you think it's a three-column layout? because the image on the top-right is l-shaped, because b1 looks like a column supporting the shifted main content, and because the "m" and "i" of the mica logo create a vertical line of force. this is a good example of a classic layout supporting some design creativity. simple layouts are easier to implement, but allow yourself room to express your creativity in this area. a much trickier layout the opera de paris. basically a two-column layout, but you'll notice many tweaks here and there that visually break up the layout. especially, the header overlaps the image of the main content. the way the curve of the header's menu ties in with the curve at the bottom of the image, the header and main cont...
How does the Internet work? - Learn web development
p address 173.194.121.32. so using the domain name is the easiest way for us to reach a computer over the internet. internet and the web as you might notice, when we browse the web with a web browser, we usually use the domain name to reach a website. does that mean the internet and the web are the same thing? it's not that simple. as we saw, the internet is a technical infrastructure which allows billions of computers to be connected all together. among those computers, some computers (called web servers) can send messages intelligible to web browsers. the internet is an infrastructure, whereas the web is a service built on top of the infrastructure. it is worth noting there are several other services built on top of the internet, such as email and irc. next steps how the web works ...
What is the difference between webpage, website, web server, and search engine? - Learn web development
. all web pages available on the web are reachable through a unique address. to access a page, just type its address in your browser address bar: web site a website is a collection of linked web pages (plus their associated resources) that share a unique domain name. each web page of a given website provides explicit links—most of the time in the form of clickable portion of text—that allow the user to move from one page of the website to another. to access a website, type its domain name in your browser address bar, and the browser will display the website's main web page, or homepage (casually referred as "the home"): the ideas of a web page and a website are especially easy to confuse for a website that contains only one web page. such a website is sometimes called a single-p...
What is a Domain Name? - Learn web development
don't require web services to meet any particular criteria, but some tlds enforce stricter policies so it is clearer what their purpose is. for example: local tlds such as .us, .fr, or .se can require the service to be provided in a given language or hosted in a certain country — they are supposed to indicate a resource in a particular language or country. tlds containing .gov are only allowed to be used by government departments. the .edu tld is only for use by educational and academic institutions. tlds can contain special as well as latin characters. a tld's maximum length is 63 characters, although most are around 2–3. the full list of tlds is maintained by icann. label (or component) the labels are what follow the tld. a label is a case-insensitive character sequence...
Common questions - Learn web development
hniques to help you design websites for any kind of user — quick accessibility wins, and other such things. ...
Example - Learn web development
this the example for a basic payment form for the article how to structure an html form. ...
Test your skills: Form structure - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
Test your skills: Styling basics - Learn web development
pful to put your code in 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. styling basics 1 our basic form styling assessment is fairly free-form, and you have a lot of flexibility over what you end up doing here. but your css should aim to fulfill the following requirements: add some kind of lightweight "reset" to make fonts, padding, margin, and sizing more consistent to begin with. on top of that, add in some nice, consistent styling for the inputs and button. use some kind of layout technique to make the inputs and labels line up neatly. download the starting point for this task to work in your own editor or in an online editor. assessme...
Example - Learn web development
; box-sizing: border-box; /* to harmonize the look & feel of text field border */ border: 1px solid #999; } input:focus, textarea:focus { /* to give a little highligh on active elements */ border-color: #000; } textarea { /* to properly align multiline text field with their label */ vertical-align: top; /* to give enough room to type some text */ height: 5em; /* to allow users to resize any textarea vertically it works only on chrome, firefox and safari */ resize: vertical; } .button { /* to position the buttons to the same position of the text fields */ padding-left: 90px; /* same size as the label elements */ } button { /* this extra magin represent the same space as the space between the labels and their text fields */ margin-left: .5em; ...
Installing basic software - Learn web development
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 free editor, that offers live previews and code hints. installing modern web browsers for now, we'll install a couple of desktop web browsers to test our code in. choose your operating system below and click the relevant links to download installers for your favorite browsers: linux: firefox, chrome, opera, brave. windows: firefox, chrome, opera, internet explorer, microsoft edge, brave (windows 10 comes with edge by default; if you have windows 7 or above, you can install internet explorer 11; otherwise, you should install an alternative browser). macos: firefox, chrome, opera, safari...
What will your website look like? - Learn web development
age as..., and choose a safe place to save your image. alternatively, copy the image's web address from your browser's address bar for later use. note that most images on the web, including in google images, are copyrighted. to reduce your likelihood of violating copyright, you can use google's license filter. click on the tools button, then on the resulting usage rights option that appears below. you should choose an option such as labeled for reuse. font to choose a font: go to google fonts and scroll down the list until you find one you like. you can also use the controls on the right to further filter the results. click the "plus" (add to) icon next to the font you want. click the "* family selected" button in the panel at the bottom of the page ("*" depends on how many fonts...
HTML Cheatsheet - Learn web development
d a word or phrase within the text mark text as important <strong>i'm important</strong> i'm important highlight some text <mark>notice me</mark> notice me draw a line through irrelevant text <s>i'm irrelevant</s> i'm irrelevant underline a non-textual annotation this is <u>mispelled</u> this is mispelled text displayed lower than normal text h<sub>2</sub>o h2o small text used to represent the <small>small print </small>of a document used to represent the small print of a document used for an address <address>main street 67</address> main street 67 used for a textual cite <cite>lorem ipsum</cite> lorem ipsum text displayed higher than normal text x<sup>2<...
Use HTML to solve common problems - Learn web development
Learn › HTML › Howto
basic structure the most basic application of html is document structure. if you're new to html you should start with this. how to create a basic html document how to divide a webpage into logical sections how to set up a proper structure of headings and paragraphs basic text-level semantics html specializes in providing semantic information for a document, so html answers many questions you might have about how to get your message across best in your document. ...
HTML Tables - Learn web development
Learn › HTML › Tables
l. get started prerequisites before starting this module, you should already have covered the basics of html — see introduction to html. 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 this module contains the following articles: html table basics this article gets you started with html tables, covering the very basics such as rows and cells, headings, making cells span multiple columns and rows, and how to group together all the cells in a column for styling purposes. html table advanced features and accessibility this module looks at some more advanced features of html tables — such as captions/summ...
Structuring the web with HTML - Learn web development
you should definitely start with the first one. introduction to html this module sets the stage, getting you used to important concepts and syntax, looking at applying html to text, how to create hyperlinks, and how to use html to structure a webpage. multimedia and embedding this module explores how to use html to include multimedi...
Server-side website programming first steps - Learn web development
elect 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 the server side welcome to the mdn beginner's server-side programming course! in this first article, we look at server-side programming from a h...
React resources - Learn web development
se. you can read more about component stylesheets in the create-react-app docs. react devtools we used console.log() to check on the state and props of our application in this tutorial, and you'll also have seen some of the useful warnings and error message that react gives you both in the cli and your browser's javascript console. but there's more we can do here. the react devtools utility allows you to inspect the internals of your react application directly in the browser. it adds a new panel to your browser's developer tools, and with it you can inspect the state and props of various components, and even edit state and props to make immediate changes to your application. this screenshot shows our finished application as it appears in react devtools: on the left, we see all of the...
ChromeWorkers and the Chrome worker loader
lable not only to the application itself, but also to add-ons. this documentation covers chrome workers and the chrome worker module loader. note: if you're contributing content to this section, create subpages using the "new sub-page" option 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(). ...
Information for users
is document is intended to help testers and designers understand and plan what still needs to be added to our ui for full usable accessibility. please give us feedback on the discussion list! firefox accessibility skins and themes at the excellent access firefox website, you will find many valuable resources, including a list of firefox themes that have been specially designed for those with low vision: themes with high color constrast themes with big icons themes with extra large and bright icons themes with extra large and extra bold text join the mozilla accessibility community live chat both 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 ch...
Mozilla Plugin Accessibility
n of problems and the planned solutions: new! see the plugin keyboard navigation proposal to see how the largest problems can be solved. problem planned solution owner targeted completion 1. all browser keys unavailable when plugin has focus focused plugins currently have no choice but to consume all keyboard events. the new plugin api will allow plugins to bubble unused keypresses to the browser. this will allow keyboard users to still access menus, close the current page, scroll, move back and forward in history, etc. if the plugin needs those keystrokes, the can consume them and not pass them on. see the plugin keyboard navigation proposal for the implementation plan. the same solution will be used for bug 140566 (full page plugins) an...
ZoomText
d to install mailnews or address book if curious about the other apps. you will also need to install zoomtext 8.11.3. happy testing! you may wish to read through the current issues on this page before reporting bugs. send me email so that i'm aware that you're testing and let me know what bugs you're finding. my email address is aaronleventhal@moonset.net. issues for ai squared, from high to low priority docreader and appreader don't respect the structure of the document -- no support for columns. zoomtext text to speech doesn't always echo what it should -- need more details from testers. mozilla issues cannot tab into frames and iframes. cannot customize the sidebar with the keyboard only. comboboxes report incorrect bounds, causing zoomtext tracking to move to the wrong a...
Frequently Asked Questions for Lightweight themes
k will always be your artwork. after creating a lightweight theme, can i edit the design? yes. if at any point you need to edit or delete your theme design after it has been submitted to the gallery, you can access it from the submissions dashboard. from there, you can view your current designs. by clicking on each, you can make changes to each design's settings. what's the maximum file size allowable for my lightweight theme? the theme you upload may not exceed 300 kb for the header or the footer image. couldn't find the answer you're looking for? consider visiting the firefox support website or the themes forum for more help. ...
Themes
learn how to create and share themes! browser themes browser theme concepts get an introduction to creating themes for the latest versions of firefox using the amo theme generator use the theme generator to create and submit a new theme to amo lightweight themes lightweight themes have been deprecated and are no longer accepted by amo. only browser themes will be accepted going forward. ...
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 nt 5.1; ...
Choosing the right memory allocator
use these if you link against xpcom or xpcom glue; this includes extensions with binary components. ...
Creating JavaScript callbacks in components
tation of the callback interface. note, that since the javascript function is a single method, this magic only works for callback interfaces with a single method, like nsidomeventlistener. the javascript function is passed the same arguments as defined by the callback method. so we could convert the example above to accept javascript functions in place of the stringparserobserver by making the following changes: [scriptable, function, uuid(...)] interface stringparserobserver : nsisupports { void onword(string word); }; [scriptable, uuid(...)] interface stringparser { void parse(string data); void addobserver(stringparserobserver observer); }; note the only change was adding function to the interface attributes of the callback interface. now we can create a callback javascript functi...
Creating a Login Manager storage module
interface in a specific category. some work has already been done to integrate the login manager with the mac os x keychain (bug 106400) and gnome keyring manager (bug 309807). you should start with the existing code if you want to implement that in your extension. to see some debugging output in the console set signon.debug to true using about:config. sample javascript implementation the following code snippet is a javascript component that implements a dummy nsiloginmanagerstorage interface. see how_to_build_an_xpcom_component_in_javascript for more details about javascript components. const cc = components.classes; const ci = components.interfaces; components.utils.import("resource://gre/modules/xpcomutils.jsm"); function sampleloginmanagerstorage() {} sampleloginmanagerstorage.pro...
Debugging OpenGL
for various reasons, debugging opengl related code can be tricky. this article provides suggestions for how to improve your efficiency while debugging opengl code in gecko. opengl debug mode when running a debug build, you can enable the opengl debug mode by defining the environment variable moz_gl_debug. if you start up firefox with this variable defined, the following behavior changes occur: each time you issue an opengl call, a check is performed to ensure that the gl context is current, using a thread-local static variable to keep track of this. if the context isn't current, the call aborts. every time an opengl call completes, glfinish() gets run automatically. this flushes out each call, essentially turning opengl into a synchronous api. this makes debugging crashes caused by a...
Debugging Safari
to enable the very useful debug menu in safari use the following: defaults write com.apple.safari includeinternaldebugmenu 1 it is often useful to switch into single process mode by turning off "use multi-process windows" ...
Debugging update problems
. you can do this using the live http headers addon to determine the url of the update request. 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. useful preferences enabling the following preferences in about:config can help troubleshoot problems with updates: app.update.log - for application updates; extensions.logging.enabled - for add-on updates. related resources extension versioning, update and compatibility. ...
Debugging a hang on OS X (Archived)
warning: the content of this article may be out of date. this article contains historical information about older versions of os x. see how to report a hung firefox instead. if you find a hang in an application, it is very useful for the developer to know where in the code this hang happens, especially if he or she can't reproduce it. below are steps you can use to attach so-called "samples" to bug reports. creating the sample on mac os x 10.5 (xcode < 4.2) when the application is still hung, open up spin control.app (it’s in your <tt>/developer/applications/performance tools/</tt> folder; if it is missing, install the latest computer hardware understanding development (chud) tools from apple). by default, sampling of any hanging application will begin automatically. af...
Adding APIs to the navigator object
you can read about creating and registering xpcom components in javascript. ...
OS TARGET
os_target is typically the output of the 'uname -s' command on the target platform. the following list is not complete as any platform could have its own os_target. winnt linux darwin android sunos freebsd openbsd netbsd os2 beos irix64 aix hp-ux dragonfly skyos riscos nto osf1 ...
pymake
e/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 typing just pymake into the shell and press enter. this should come back with "no makefile found." if it does, your pymake alias is connected and you ar...
Working with Mozilla source code
getting a pre-configured mozilla build system virtual machine this is the easiest way to get started: use a virtualbox virtual machine which is already configured with a complete build environment for you to use. just boot the vm and build! viewing and searching mozilla source code online learn how to use searchfox, mozilla's online search and browsing tool for accessing the source code. this isn't a good way to download the code, but is a great way to search it. ...
Index
t" protocol firefox, guide, mozilla, protocols there is a lot of useful information about firefox hidden away behind the about: url protocol. the most useful is the url about:config, which displays preferences and settings that can be inspected and changed. 141 index firefox, index, mozilla found 168 pages: 142 linux compatibility matrix the following table lists the available library versions for the mozilla.org-distributed firefox builds dependencies, and/or to build firefox. 143 multiple firefox profiles beginner, firefox, guide, intro, profiles, qa a profile in firefox is the collection of settings, customizations, add-ons, and other personalizations that a user has made or installed into their copy of firefox. you ...
Limitations of chrome scripts
ous access to content objects. however, there are various limitations on the kinds of things you can do with a cpow. note that from firefox 47 onwards, unsafe cpow usage is no longer permitted in browser code. if browser code tries an unsafe cpow operation, the browser will throw an exception and you'll see an "unsafe cpow usage forbidden” error in the browser console. add-on code is still allowed to use cpows "unsafely". however, if an add-on passes a cpow into a platform api, and that platform api then attempts an unsafe operation on it, this will throw an exception. so as a general rule, add-ons should avoid passing cpows into non-addon code. nsicontentpolicy without the shim in multiprocess firefox, if you register the nsicontentpolicy in the chrome process then it will never see...
Message manager overview
s message manager (cpmm). there's also an additional child-in-process message manager (cipmm) in the parent process. for each child process message manager, there's a parent process message manager (ppmm) in the parent process. there's also a single global parent process message manager (gppmm) in the parent process, that provides access to all the parent process message managers. the diagram below shows the setup that would result from having two child processes: with the gppmm, you can broadcast messages to the cipmm and all cpmms. with a ppmm, you can send a message to its corresponding cpmm. with a cpmm, you can send messages to the parent process: these messages are received first by the corresponding ppmm, then by the gppmm. from firefox 38 onwards, you can also use a parent proce...
Message manager
these guides explain how to use message managers in multiprocess firefox. note that none of this requires multiprocess firefox: everything described here will work with single-process firefox, so the same code will work on both variants. ...
Errors
this page lists the errors that can be raised due to firefox's anti-tracking functionality, governed by the storage access policy. ...
Firefox
x user interface where web sites are listed for the user to choose a destination to visit or a site to manage in some way. one example is the new tab page, which includes a "top sites" section showing sites you visit that firefox thinks you're likely to want to visit again, as well as potentially some sites that have been pinned to always appear in that space. linux compatibility matrixthe following table lists the available library versions for the mozilla.org-distributed firefox builds dependencies, and/or to build firefox.multiple firefox profilesa profile in firefox is the collection of settings, customizations, add-ons, and other personalizations that a user has made or installed into their copy of firefox. you can find details about profiles on mozilla's end-user support site.perfor...
Firefox Operational Information Database: SQLite
(install the sqlite mangager add-on, click tools -> sqlite manager. ...
HTMLIFrameElement.clearMatch()
nvoking this method results in a mozbrowserfindchange event firing, which carries details about the search results. note: use of the browser api requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. see using the browser api for more details. syntax instanceofhtmliframeelement.clearmatch(); returns void. parameters none. examples the following function is taken from our browser api demo, and (amongst other things) clears the search results when the search bar is hidden, if an existing search is active. see implementing the search bar for more explanation. searchtoggle.addeventlistener('touchend',function() { if(search.getattribute('class') === 'search') { search.setattribute('class', 'search shifted'); } else if(search.geta...
HTMLIFrameElement.download()
ified url, storing it at /sdcard/download. syntax var instanceofdomrequest = instanceofhtmliframeelement.download(url, options); returns a domrequest for handling the download request. its request.onsuccess handler handles the success case, and its request.onerror handler handles the failure case. parameters url the url of the file to be downloaded. options optional an options object allowing optional settings to be specified for the download. the available options are: filename: the filename to save the downloaded file as. if this is not specified, the filename used will be the original filename, as specified in the url. referrer: specifies a referrer for the downloaded file. if this is not specified there will be no referrer. examples var browser = document.querysele...
HTMLIFrameElement.executeScript()
note: use of the browser api requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. see using the browser api for more details. syntax var mydomrequest = instanceofhtmliframeelement.executescript(script, options); return value a domrequest object that returns an onsuccess handler if the script is successfully executed against the loaded content, or an onerror handler if not. parameters script the script to be executed. ...
HTMLIFrameElement.findAll()
nt to do. see using the browser api for more details. syntax instanceofhtmliframeelement.findall(searchstring, casesensitivity); returns void. parameters searchstring the string you want to search for in the browser <iframe>'s text. casesensitivity a string to declare whether you want the search to be case sensitive (case-sensitive) or insensitive (case-insensitive.) example the following function is taken from our browser api demo, and executes a search when a search form is submitted. see implementing the search bar for more explanation. searchform.addeventlistener('submit', function(e) { e.preventdefault(); browser.findall(searchbar.value, 'case-sensitive'); searchactive = true; prev.disabled = false; next.disabled = false; searchbar.blur(); }); specification ...
HTMLIFrameElement.findNext()
ileged app, and browser and/or embed-apps permissions, depending on what you want to do. see using the browser api for more details. syntax instanceofhtmliframeelement.findnext(direction); return value void. parameters direction a string indicating the direction in which you want to cycle through the available search results. available values are forward and backward. examples the following functions are taken from our browser api demo, and cycle through the available search results. see implementing the search bar for more explanation. prev.addeventlistener('touchend',function() { browser.findnext('backward'); }); next.addeventlistener('touchend',function() { browser.findnext('forward'); }); specification not part of any specification. ...
mozbrowseractivitydone
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: success a boolean that indicates whether the activity has completed successfully (true) or not (false). examples var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseractivitydone", function(event) { if(event.details.success) { console.log('activity completed successfully'); } else { console.log('activity not completed successfully'...
mozbrowserasyncscroll
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: top the scroll top position in css pixels of the document within the browser <iframe>. left the scroll left position in css pixels of the document within the browser <iframe>. width the width in css pixels of the visible part of the document within the browser <iframe>. height the height in css pixels of the visible part of the document within the browser <iframe>. scrol...
mozbrowsererror
et the browser iframe 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. details read only object a custom object. detail the detail property returns an anonymous javascript object with the following properties: type a domstring representing the type of error that occurred. possible values are: fatal(crash) unknownprotocolfound filenotfound dnsnotfound connectionfailure netinterrupt nettimeout cspblocked phishingblocked malwareblocked unwantedblocked offline malformeduri redirectloop unknownsockettype netreset notcached isprinting deniedportacces...
mozbrowserfindchange
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: active a boolean indicating whether a search is currently active (true), or not (false.) searchstring a domstring representing the string that is currently being searched for. searchlimit a number indicating the maximum number of searches that can be returned. numberofmatches a number indicating the number of matches returned by the search. activematchordinal a number i...
mozbrowsericonchange
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: href a domstring representing the path to the new icon. sizes a domstring listing the sizes the new icon is available in, e.g. "16x16" or "16x16 32x32". the any keyword can also be used, to represent "any size." rel a domstring representing the rel attribute value from the <link> element used to link to the icon. example var browser = document.queryselector("iframe"); ...
mozbrowserloadend
et the browser iframe 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. details read only object a custom object. detail the detail property returns an anonymous javascript object with the following properties: backgroundcolor a domstring representing the main background color of the browser <iframe> content, expressed as an rgb value. can be used to make the theme of the surrounding ui complement the theme of the currently loaded content, for example. example in this example the mozbrowserloadstart and mozbrowserloadend events are used to change the icon shown on the stop/reload b...
mozbrowserlocationchange
et the browser iframe 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. details read only object a custom object. detail the detail property returns an anonymous javascript object with the following properties: url a domstring representing the url of the new location. cangoback a boolean that defines whether it's possible to go back in the navigation history (true) or not (false). cangoforward a boolean that defines whether it's possible to go forward in the navigation history (true) or not (false). example this example updates the url bar so that it will always display the cor...
mozbrowsermanifestchange
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: href the url of the new app manifest. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsermanifestchange", function(event) { console.log("new manifest url: " + event.details.href); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbr...
mozbrowseropensearch
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: title a domstring representing the title of the search engine. href a domstring representing url of the search engine. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseropensearch", function( event ) { console.log("new search engine encountered: " + event.details.title); }); related events mozbrowserasyncscroll mozbrowsercl...
mozbrowseropentab
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: url a domstring representing the url of the new document loaded. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseropentab", function( event ) { console.log("a new document has opened containing the content at " + event.details.url + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbro...
mozbrowseropenwindow
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: url a domstring representing the url of the document loaded within the frameelement property. name a domstring representing the name of the new browser window. features a domstring containing features represented by a list of names and values separated by commas. for a complete list of possible features, see window.open(). frameelement an object representing the new brows...
mozbrowserresize
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: width a number representing the new width of the <iframe> viewport, in device pixels. height a number representing the new height of the <iframe> viewport, in device pixels. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserresize", function( event ) { console.log("the new window size is " + event.details.width + " x " + event.d...
mozbrowserscroll
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: top a number representing the new vertical scroll position of the <iframe> viewport — in css pixels — from the top of the viewport. left a number representing the new horizontal scroll position of the <iframe> viewport — in css pixels — from the left of the viewport. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserscroll...
mozbrowserscrollareachanged
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: width a number representing the new scroll area width of the <iframe> viewport, in css pixels. height a number representing the new scroll area height of the <iframe> viewport, in css pixels. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserscrollareachanged", function( event ) { console.log("the new scroll area is " + event.de...
mozbrowserscrollviewchange
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: state a domstring representing the current state of scrolling in the viewport — available values are started and stopped. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserscrollviewchange", function( event ) { console.log("scrolling has " + event.details.state + "."); }); related events mozbrowserasyncscroll mozbrowserclos...
mozbrowsersecuritychange
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: state a domstring representing the current state of ssl security. possible values are: broken: indicates an unknown security state. this may mean that the request is being loaded as part of a page in which some content was received over an insecure channel. secure: indicates that the data corresponding to the request was received over a secure channel. insecure: indicat...
mozbrowserselectionstatechanged
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: rect an object that represents the bounding rectangle of the selection. its properties are: width: the width of the selection, in css pixels. height: the height of the selection, in css pixels. top: the y coordinate of the top of the bounding box, in css pixels. bottom: the y coordinate of the bottom of the bounding box, in css pixels. left: the x coordinate of the ...
mozbrowsershowmodalprompt
arget the browser iframe 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. details read only object a custom object. details the details property is an anonymous javascript object with the following properties: prompttype a domstring defining the type of the prompt. it can be alert, confirm, or prompt. title a domstring representing the title of the prompt. message a domstring representing the value passed to the window.alert(), window.confirm(), or window.prompt() methods within the browser <iframe>'s content. returnvalue a domstring representing the return value for the window...
mozbrowserusernameandpasswordrequired
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following members: host a domstring representing the host requesting the http authentification. realm a domstring representing the value of the realm http header. isproxy a boolean indicating whether the server dealing with the authentication is a proxy server (true) or not (false). authenticate() a function that is called to enable the authentication to go ahead. it needs to take two paramete...
mozbrowservisibilitychange
the browser iframe 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. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: visible a boolean that indicates whether the browser iframe is visible (true) or not (false). example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowservisibilitychange", function( event ) { if(event.details.visible) { console.log("the browser is visible."); } else { console.log("the browser is hidden."); } }); related events...
HTMLIFrameElement.sendMouseEvent()
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the sendmouseevent() method of the htmliframeelement interface allows you to fake a mouse event and send it to the browser <iframe>'s content. syntax instanceofhtmliframeelement.sendmouseevent(type, x, y, button, clickcount, modifiers); returns void. parameters type a string representing the event type. possible values are mousedown, mouseup, mousemove, mouseover, mouseout, or contextmenu. x a number representing the x position of the cursor relat...
HTMLIFrameElement.sendTouchEvent()
note: this method is available for touch-enabled devices only. syntax instanceofhtmliframeelement.sendtouchevent(type, x, y, rx, ry, rotationangles, forces, count, modifiers); returns void. parameters type a string representing the event type. possible values are touchstart, touchend, touchmove, or touchcancel. ...
HTMLIFrameElement.setVisible()
<iframe> has nothing to do with its actual visibility (which is handled through css). the visible state is used to define the level of resources required by the browser <iframe>. if the visible state is set to true, it means that the browser <iframe> should have high priority over the resources needed to render and handle its content. on the contrary, if its visible state is set to false, it has low priority over the resources it needs. as an example, if the content of a browser <iframe> uses the window.requestanimationframe method and if the visible state is set to true, window.requestanimationframe will be called as often as necessary. however, if the visible state is set to false, window.requestanimationframe will be called only when there are free resources to do it. syntax instanceof...
ChromeWorker
rker that can use js-ctypes to perform calls to native code, you can do so by using chromeworker instead of the standard worker object. it works exactly like a standard worker, except that it has access to js-ctypes via a global ctypes object available in the global scope of the worker. examples of chromeworker's using js-ctypes are availabe on github and are linked to from the see also section below. to use a postmessage with callback version of chromeworker that features promises, see promiseworker. addons must use absolute urls to load their workers, and those urls have to be using a chrome:// or resource:// protocol (file:// is not accepted). addons that wish to use file:// urls must first register a resource replacement path, using code like this: var fileuri = services.io.newfileuri(f...
-moz-window-dragging
applies to all elements that create native windows, e.g. <window>, <panel> inherited no media visual computed value as specified animation type discrete canonical order the unique non-ambiguous order defined by the formal grammar syntax the -moz-window-dragging property is specified as one of the keyword values listed below. values drag the window is draggable. no-drag the window is not draggable formal syntax drag | no-drag example toolbarpaletteitem { -moz-window-dragging: no-drag; } specifications this property is not part of any specification. ...
CSS <display-xul> component
see this firefox site compati...
MozBeforePaint
rame() method. once you've called this, the mozbeforepaint event will be fired one time, when it's time for animations to be updated for the window's next animation frame. the timestamp property of this event will be set to the time when the animation frame is sampled; this is relevant when trying to synchronize mozrequestanimationframe animations with smil animations or css transitions. this allows multiple animations to remain in sync with one another within the context of a given window. frame rate control mozbeforepaint won't fire more than a fixed number of times per second, e.g. 50 or 60. this is intentional, because modern operating systems and hardware won't let the browser display more frames than that anyway. limiting the frame rate avoids wasting work, thereby saving cpu usage ...
MozScrolledAreaChanged
this event, introduced in gecko 1.9.2, is fired whenever either or both of these values change. ...
Embedding Mozilla
that means you can embed a web browser inside a third-party application, open channels and streams through the network backend, walk through the dom and so on. you can even construct whole new applications using chrome. documentation gecko embedding basics an introduction to embedding the gecko rendering engine. embedding tips some frequently asked questions about embedding. mozilla embedding apis overview introduction to the mozilla embedding apis. ...
HTML parser threading
some tree ops have been moved to the staging queue, the nsirunnable held in mexecutorflusher is dispatched to the main thread. (the same runnable is used repeatedly in order to avoid cross-thread refcounting issues.) memory management when crossing the thread boundary the tree ops hold various heap-allocated objects that end up crossing the thread boundary. these objects are memory managed as follows: attribute holders (nshtml5htmlattributes objects) are allocated using new by the tokenizer. the tree builder either transfers an attribute holder to a tree op whose destructor explicitly deletes the attribute holder or if the tree builder ends up ignoring an attribute holder, the tree builder deletes the attribute holder explicitly. attribute values, public identifiers (in doctype) and system i...
Gecko versions and application versions
note that after gecko 2.0, both firefox and thunderbird versions are from then on the same as the gecko version number, at gecko 5.0. ...
How to get a process dump with Windows Task Manager
nightly build or released version of firefox from mozilla. you can find the latest trunk nightly builds under http://ftp.mozilla.org/pub/mozilla.o.../latest-trunk/. creating the dump file ensure that firefox is not already running. run firefox, reproduce the hang start firefox and perform whatever steps are necessary to cause firefox to hang. once the browser hangs, continue with the steps below. after the hang open windows task manager (ctrl+shift+esc). find firefox.exe among the list of processes. right-click firefox.exe and select "create dump file". task manager should indicate where the dump file was written to. see also how to get a stacktrace for a bug report [en-us] how to create a user-mode process dump file in windows vista and in windows 7 (msdn) ...
How to get a stacktrace for a bug report
ments you need a binary build of firefox from mozilla.org. seamonkey and thunderbird also support crash reporting. mozilla's crash 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 fir...
IPDL Type Serialization
all types used in ipdl must be serializable. this is accomplished through type specialization of a c++ traits class. types are serialized and deserialized from an ipc::message type declared in ipc_message.h. each type specializes ipc::paramtraits as follows: namespace ipc { template <> struct paramtraits<mytype> { typedef mytype paramtype; static void write(message* amsg, const paramtype& aparam) { // implement serialization here } static bool read(const message* amsg, void** aiter, paramtype* aresult) { // implement deserialization here. return false if deserialization failed } }; } // namespace ipc the standard ipdl types (integers, floats, and xpcom strings) already have serializers. other types need to have serializers written for them explicitly. in ma...
IPC Protocol Definition Language (IPDL)
all messages for multi-process plugins and tabs in firefox are declared in the ipdl language. ...
Addon
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, per profile, user, syst...
AddonListener
stalled( in addon addon, ) parameters addon the addon that has been uninstalled onoperationcancelled() called when a pending operation for an add-on is cancelled. void onoperationcancelled( in addon addon, ) parameters addon the addon that has had a pending operation cancelled onpropertychanged() called when one or more properties of addon has changed. only applies to the following properties: applybackgroundupdates void onpropertychanged( in addon addon, in string properties[] ) parameters addon the addon that has had its properties changed properties an array of the names of properties that changed. ...
AddonManager
gh callbacks passed to the method. the callbacks will be called just once but that may be before or after the method returns. one of the forces of the addonmanager is that it deals with any kind (type) of add-on in a generic manner. to do so many methods of the addonmanager take the add-on types as parameters. the existing add-on types are defined in xpiprovider.jsm and are, at this time, the following: extension, theme, locale, multipackage, dictionary and experiment. to import the addonmanager object in the add-on sdk, use: const { addonmanager } = require("resource://gre/modules/addonmanager.jsm"); to import it in a normal bootstrapped extension or similar, use: cu.import("resource://gre/modules/addonmanager.jsm"); method overview promise? getinstallforurl(in string url, i...
AddonScreenshot
attributes attribute type description url string the url of the screenshot. thumbnailurl optional string the url of a thumbnail version of the screenshot. caption optional string the caption of the screenshot. width optional string the width of the screenshot. height optional string the height of the screenshot. thumbnailwidth optional string the thumbnailwidth of the screenshot. ...
AddonType
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 viewtype integer the type of ui to use to display this type ...
Code Samples
simply replace yourextensionid with your add-on's id. ...
UpdateListener
either onupdateavailable() or onnoupdateavailable(), depending on whether a newer version of the addon was found. ...
Assert.jsm
ue 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 with ==. undefined equal( actual, expected, message ); parameters actual test subject to be evaluated as equivalent to expected expected test reference to evaluate against actual message short explanation of the expected result notequal() the non-equality assertion tests for whether two objects are not equal with !=. undefined notequal( actual, expected...
AsyncShutdown.jsm
unction info) boolean removeblocker(function|promise condition) methods addblocker () register a blocker for the completion of a phase. void addblocker( in string name, in function|promise|* condition, optional in function info ) arguments name the human-readable name 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 ...
API-provided widgets
only useful for views (and required there): the id of the that should be shown when clicking the widget. tooltiptext string to use for the tooltip of the widget label string to use for the label of the widget removable whether the widget is removable (optional, default: true). nb: if you specify false here, you must provide a defaultarea, too. overflows whether widget can overflow when in an overflowable toolbar (optional, default: true) defaultarea default area to add the widget to (optional, default: none; required if non-removable) shortcutid id of an element that has a shortcut for this widget (optional, default: null). this is only used to display the shortcut as part of the tooltip for builtin widgets (which hav...
Dict.jsm
appen. constructor dict() creates and returns a new dictionary object. dict dict(); dict dict( object initalkeysandvalues ); parameters initialkeysandvalues optional a object containing key/value pairs with which to initialize the dictionary. return value a newly created dictionary object implementing the methods described in this article. methods copy() returns a shallow copy of the dictionary; that is, a copy of the dictionary including the items immediately included within the dictionary; however, any objects referenced by those top-level objects are not copied. dict copy(); parameters none. return value a new dictionary object containing the same top-level items as the original dictionary on which the copy() method was called. del() deletes a key/value...
DownloadList
adownload the download object to remove. promise resolves to undefined when the download has been removed. addview() adds a view that will be notified of changes to downloads. the newly added view will receive ondownloadadded notifications for all the downloads that are already in the list. promise addview( object aview ); parameters aview the view object to add. the following methods may be defined: ondownloadadded: optional this function is called with a single download argument, after the download is added to the end of the list. ondownloadchanged: optional this function is called with a single download argument, after the properties of the download change. ondownloadremoved: optional this function is called with a single download argument,...
JavaScript OS
platform and add-ons) to interact with the host operating system. at the time of this writing, some of the features of this module are available only to chrome workers. os.constants os-related constants, including errors, file opening modes, system configuration, etc. os.file access to the native file system. ...
OS.File.Error
ces of os.file.error are used by os.file to notify of file-related errors. using os.file.error example: finding out whether the problem is due to a file that does not exist try { let file = os.file.open("myfile.txt"); // ... } catch (ex) { if (ex instanceof os.file.error && ex.becausenosuchfile) { // the file does not exist } } global object os.file.error methods overview the following functions are utility functions that may be used to construct instances of os.file.error, setting the platform-specific error number. error closed() error exists() 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 ...
Deferred
ve no effect the second time, as the associated promise is already resolved to the pending promise value as its resolution. void resolve( avalue ); parameters avalue optional if this value is not a promise, including undefined, it becomes the fulfillment value of the associated promise. if this value is a promise, then the associated promise will be resolved to the passed promise, and follow the state as the provided promise (including any future transitions). reject() rejects the associated promise with the specified reason. if the promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. note: this function is exactly same as promise constructor's reject argument, and can be called with any value of this. void reject( ar...
WebChannel.jsm
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 the channel itself with t...
Localization notes
localizers usually work on the localizable files without the context of the source files including the localized strings; it is important to add comments to the localizable files themselves, too. these comments are generally referred to as localization notes. there is an established format for those, which is described in this document. it's important to follow the format as closely as possible. there are a number of automated tools that parse these comments for easier access and use by localizers. dtd files <!-- localization note (entity name): comment --> properties files # localization note (key): comment file-wide comments should use the same format, be at the top of the file (after the license header, though) and just drop the (entity name/key) reference. ...
Localizing with Mozilla Translator
checking "keep original" flags for strings not needing translation, instead of just leaving the translation empty struggling to get empty lists when running "untranslated strings" and "view fuzzy" if you are up to date in localization regularly running qa checks and trying to minimize them. 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 | `-- brand.properties |-- browser | |-- aboutdialog.dtd . . |-- browser-region | `-- region.properties...
Web Localizability
the documentation is divided into 4 parts: how to create localizable content. how to choose the right localization format. how to create localizable web applications. how to set up the infrastructure for localization. why localizability is important there are many reasons why you should start thinking about making your web app localizable as soon as possible. you will make localizer's life easier, for which they will be grateful. ...
Writing localizable code
. 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 likely be a good key name, and it will help tools to pick up that the change you do is different f...
Mozilla Framework Based on Templates (MFBT)
ce. (the <stdint.h> standard header is not available on all platforms and so cannot be used directly. this 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 contr...
MathML3Testsuite
the sections are marked with passed, failed, not-tested or some parts pass, giving the status of trunk builds with the appropriate fonts installed. when the markup is intentionally errorous, the correct behavior is not defined by the recommendation and hence the tests are considered passed if there is no fatal error (crash, etc). this exception also holds for obsolete features (such as macro, mode etc) or for other undefined behaviors (attribute href for example). note that in general, comparing with the "sample rendering" is not enough to conclude on the success/failure of the test. so please do not edit these pages if you are not able to explain gecko's rendering. ...
MathML Torture Test
temathfont() { var mathfont = document.getelementbyid("mathfont").value; if (mathfont == "default") { document.body.removeattribute("class"); } else { document.body.setattribute("class", mathfont); } } function load() { document.getelementbyid("mathfont"). addeventlistener("change", updatemathfont, false) } window.addeventlistener("load", load, false); the following test contains sample tex formulas from knuth's tex book and equivalent mathml representations. it compares the rendering by the xetex engine using the default latin modern math font against the mathml rendering by your browser using the default math font, or an alternative opentype math fonts. to get the best rendering, be sure to have appropriate mathematical fonts installed on your system an...
Mozilla MathML Status
pport. references to mathml 3 are given. the sections are marked with their current status: supported, in progress, and not currently supported. sections related to semantics/content mathml or irrelevant features are left blank or not listed at all. if only the main features of an element are implemented then its section is marked as supported but details of unsupported attributes are specified below. the top-level math element see § 2.2. attribute notes display implemented. maxwidth, overflow not implemented. see bug 534962. altimg, altimg-width, altimg-height, altimg-valign, alttext accepted, but do not have any effect on the rendering. mathml is always enabled since bug 660762. cdgroup accepted, but does not have any effect on th...
Updates
march 22, 2011 firefox 4.0 has been released! this new version comes with several bug fixes and new features for mathml. some improvements are particularly worth noting: a new html parser, which lets you use mathml inside non-xhtml documents. complete support for stix fonts 1.0. better rendering of mathematical symbols, especially stretchy operators. october 21, 2010 mathml 3.0 is now a w3c recommendation! june 11, 2010 stix fonts version 1.0 are now compatible with trunk. may 28, 2010 stix fonts version 1.0 released. ...
Various MathML Tests
is means to those who care to read. testing mathml <merror>, <mtext>: this is a text in mtext this is a text in merror testing <maction>: click to toggle between expressions, and watch the status line onmouseover/onmouseout: statusline#first expression first expression statusline#second expression second expression statusline#and so on... and so on.. click the expression below to see several definitions of pi: π = 3.14159265358... π = 2i ⁢ log 1-i 1+i π = 2 . 2 2 . 2 2 + 2 . 2 2 + 2 + 2 ... π 4 = 1 2 + 12 2 + 32 2 + 52 2 + 72 2+... thomson scattering theory d 2 p d Ω s   d ω s = r e 2 ∫ v < s i > d 3 r ∫ | e ^ . Π ↔ . e ^ | 2 ...
MathML Demo: <mmultiscripts> - attach prescripts and tensor indices to a base
a mathml mmultiscripts object allows you to build tensor-like objects. for example m c d a b . the scripts come in pairs, with <mprescripts/> used to indicate prescripts and <none/> used to hold an empty position as in f b a . there are some variations possible: <mmultiscripts> a a b c d , nested <msubsup>s a a b c d , or &invisiblecomma; a a ⁣ c b ⁣ d . displays a mathml mmultiscripts objects allows you to build tensor-like objects. for example m c d a b the scripts come in pairs, with <mprescripts/> used to indicate prescripts and <none/> used to hold an empty position as in f b a there are some variations possible: <mmultiscripts> a a b c d nested <msubsup>s a a b c d or &invisiblecomma; ...
Mozilla projects on GitHub
first thing to know. to do more—to contribute to the code, or to fork it and start your own project based on mozilla-related code—you need a github account. to learn more about setting up a github account, visit the github website. most mozilla project code is located in repositories within the mozilla github organization. this is a great place to start looking for any projects not listed below. projects this listing covers the larger-scale and more important mozilla projects on github. it does not include everything since it's hard to keep track of all the smaller projects. look to github for the most complete list of mozilla projects on github. project name description pdf.js a portable document format (pdf) reader written entirely in javascript. ...
Namespace
below, find links to articles about c++ classes mozilla uses within various namespaces, primarily the mozilla namespace. mozillamozilla::condvarmozilla::monitormozilla::monitorautoentermozilla::mutexmozilla::mutexautolockmozilla::mutexautounlock ...
Are We Slim Yet
im yet project (commonly known as awsy) for several years tracked memory usage across builds on the (now defunct) website areweslimyet.com. it used the same infrastructure as about:memory to measure memory usage on a predefined snapshot of alexa top 100 pages known as tp5. since firefox transitioned to using multiple processes by default, we moved awsy into the taskcluster infrastructure. this allowed us to run measurements on all branches and platforms. the results are posted to perfherder where we can track regressions automatically. as new processes are added to firefox we want to make sure their memory usage is also tracked by awsy. to this end we request that memory reporting be integrated into any new process before it is enabled on nightly. ...
Build Metrics
"build metrics" is a catch-all term for performance measures that are generated by the firefox build system and tracked by perfherder. num_constructors number of static constructors found by the compiler in the firefox c++ codebase. lower is better. static constructors are undesirable because their initialization imposes an unavoidable time penalty every time firefox is started. installer size size in bytes of the firefox installer. lower is better here, especially on space-restricted platforms like android. build times amount of time it takes to build firefox in automation on a specific platform / configuration. lower is better. compiler warnings number of compiler warnings detected during a build. lower is better. due to the way the build system works, compiler warnings are...
GC and CC logs
...
Intel Power Gadget
worth reading at this point if you haven't already. it may make parts of this document easier to understand. the main strengths of this tool are (a) it works on windows, unlike most other power-related tools, and (b) it shows this data in graph form, which is occasionally useful. on mac and linux, tools/power/rapl is probably a better tool to use. understanding the power gadget output the following screenshot (from the mac version) demonstrates the available measurements. the three panes display the following information: power: shows power estimates for the package and the cores ("ia"). these are reasonably useful for power profiling purposes, but mozilla's rapl utility provides these along with gpu and ram estimates, and in a command-line format that is often easier to use. freq...
Investigating CSS Performance
http://people.mozilla.org/~jmuizelaar/css-perf.patch this patch instruments a bunch of key places and should give an estimate of the order of magnitude of the different parents. two counts are collected which allow for an estimation of the amount of work being done during restyle: resolvestyleforcount this is incremented everytime that we do style resolution on an element contentenumfunccount this is incremented roughly for every rule that we test against time during restyle can be spent in a bunch of places. for example, hasstatedependentstyle will compute a hint that determines how many elements we'll restyle. if we get a erestyle_subtree we will restyle more elements. this was developed while investigating bug 1110625 ...
Profiling with the Gecko Profiler and Local Symbols on Windows
d 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 you're on windows and you've built firefox yourself. for any official release of firefox (nightly, beta, etc), you do not need to use these steps. make sure you don't have ac_add_options --disable-crashreporter in your firefox .mozconfig file. if you're building a beta or release channel version, and you want proper c++ callstacks in your pr...
dtrace
s a powerful mac os x kernel instrumentation system that can be used to profile wakeups. this article provides a light introduction to it. 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. invocation dtrace must be invoked as the super-user. a good starting command for profiling wakeups is the following. sudo dtrace -n 'mach_kernel::wakeup { @[ustack()] = count(); }' -p $firefox_pid > $output_file let's break that down further. the -n option combined with the mach_kernel::wakeup selects a probe point. mach_kernel is the module name and wakeup is the probe name. you can see a complete list of probes by running sudo dtrace -l. the code between the braces is run when the probe point is ...
Phishing: a short definition
controlled website. the login portal might resemble the trusted website's login page very closely, and convince users to enter their credentials, letting others hijack their account. past and current countermeasures various technical, and social approaches, exist to combat phishing attacks. none of these are sufficient by themselves, so we see a mix of these deployed by various services. the following is a non-exhaustive list of the most common approaches. shifting blame to users some quick-to-implement, and cost-effective solutions, hold users accountable for their actions instead of restricting what’s technically possible. earlier responses by affected banks, and payment providers, was to attempt educating users to not click links in emails, along with requesting to verify email legit...
Preferences system
this document describes toolkit's preferences system. using this system it is possible to create preferences windows that display and operate appropriately on various platforms (windows, macos x and gnome). the system is implemented through a few xul elements and attributes. ...
Productization guide
irefox 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 » ...
Crash reporting
st need to find the crash id that the server has assigned your crash. type about:crashes into your location bar to get a page listing both submitted and unsubmitted crash reports. for more information, see how to get a stacktrace for a bug report. reports and queries crash-stats has built-in reports of "topcrashes" for each release grouped by signature. there is also a custom query tool which allows users to limit searches on more precise information. finally, a set of mozilla employees have access to directly query the underlying data in either sql summary or using mapreduce on the storage cluster. if you are interested in obtaining this advanced access, contact gabriele svelto. see also understanding crash reports a guide to searching crash reports crash-stats crash pings (telemet...
L20n
from the entire expressive power of the natural language. l20n keeps simple things simple, and at the same time makes complex things possible. through l20n, mozilla is creating a new generation of technology that places more power in localizers' hands. l20n lets localizers reach higher levels of free linguistic expression by sharpening the divide between localization 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: "f...
MailNews
esting the mailnews component of thunderbird. see mailnews automated testing for a description of the other testing mechanisms. leak and bloat tests this page describes how to perform tests that measure memory leaks and bloat for mailnews and its sub-components. mailnews automated testing automated testing is an increasingly significant and important part of mailnews development. it allows reviewers to quickly pick up regressions in patches and helps developers to think about different cases. see pages tagged mailnews for additional mailnews-specific information. ...
McCoy
applications periodically look for and install updates to their add-ons. it's important that the update information retrieved has not been tampered with since being written by the add-on author. ...
NSPR build instructions
ndows. nspr debug build uses the release c run-time library by default. to generate a debug build that uses the debug c run-time library, specify the --enable-debug-rtl configure option. makefile targets all (default) clean realclean distclean install release running the test programs the tests were built above, in the pr/tests directory. on mac os x, they can be executed with the following: /bin/sh: $ cd pr/tests $ dyld_library_path=../../dist/lib ./accept pass $ $ # to run all the nspr tests... $ $ dyld_library_path=../../dist/lib ../../../nspr/pr/tests/runtests.sh ../.. ...
NSPR release procedure
ectory /share/builds/components. this design comes from the netscape days. the repackage.sh script repackages the jar files into the form most commonly used on that platform. so on unix it repackages the jar files into gzipped tar files, and on windows it repackages the jar files into zip files. edit the repackage.sh script to customize it for your environment. after you have run repackage.sh, follow the instructions in to upload the files to ftp.mozilla.org's staging server, so that they eventually show up on ftp.mozilla.org. the host ftp.mozilla.org can be accessed via the ftp, http, and https protocols. we recommend using https://ftp.mozilla.org/. note: for nss, the script equivalent to nspr's repackage.sh is /u/robobld/bin/sbsinit/nss/push/buildbindist.sh in the "svbuild" source tree. ...
Nonblocking IO In NSPR
sk i/o never blocks. fundamentally, this constraint is due to the fact that nonblocking i/o and <tt>select()</tt> are only available to sockets on some platforms (e.g., winsock). in nspr, a new socket returned by <tt>pr_newtcpsocket()</tt> or <tt>pr_newudpsocket()</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 ...
Optimizing Applications For NSPR
face. nspr's file i/o is done using windows 3.1's synchronous file i/o api. the nspr file i/o apis may cause a thread switch even though the i/o is fully synchronous. do not depend on file i/o being synchronous. command line applications using the libc printf() and related apis behave funny on windows 3.1. read the fine print in the windows sdk for the grizzly details. watch out for printn overflow on win16. make sure all possible values of your printn variables are within 2^16. win-95 the win-95 version of nspr should really be labeled win-32. the same library will work on either win-nt or win-95. win-95 nspr uses native threads as nspr threads. generally speaking, the native threads (on nt or '95) are quite functional. however, having lots of them (100s or even 1000s) is unrealistic.
Programs Using NSPR
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
match. in the first protocol, the job of passing the inheritable shared memory is done via helper-functions with pr_createprocess. in the second protocol, the parent process is responsible for creating the child process; the parent and child are mutually responsible for passing a filemap string. nspr provides helper functions for extracting data from the prfilemap object. ... see the examples below. both sides should adhere strictly to the protocol for proper operation. the pseudo-code below shows the use of a file-mapped shared memory by a parent and child processes. in the examples, the server creates the file-mapped shared memory, the client attaches to it. first protocol server: fm = pr_openanonfilemap(dirname, size, filemapprot); addr = pr_memmap(fm); attr = pr_newprocessattr(); pr...
I/O Types
ket options functions type used with memory-mapped i/o offset interpretation for seek functions directory type prdir file descriptor types nspr represents i/o objects, such as open files and sockets, by file descriptors of type prfiledesc. this section introduces prfiledesc and related types. prfiledesc priomethods prfileprivate prdescidentity note that the nspr documentation follows the unix convention of using the termfiles to refer to many kinds of i/o objects. to refer specifically to the files in a file system (that is, disk files), this documentation uses the termnormal files. prfiledesc has an object-oriented flavor. an i/o function on a prfiledesc structure is carried out by invoking the corresponding "method" in the i/o methods table (a structure of type priomethod...
Logging
compile the program with debug defined. before running the compiled program, set the environment variable nspr_log_modules to userstuff:5 static void userlogstuff( void ) { prlogmoduleinfo *mylm; printn i; pr_static_assert(5 > 4); /* nspr 4.6.6 or newer */ mylm = pr_newlogmodule( "userstuff" ); ...
NSPR Types
plemented in an application but called from a shared library. ...
PLHashEntry
const void *key; void *value; the key field is a pointer to an opaque key. the value field is a pointer to an opaque value. if the key of an entry is an integral value that can fit into a void * pointer, you can just cast the key itself to void * and store it in the key field. ...
PL_HashString
a general-purpose hash function for character strings. syntax #include <plhash.h> plhashnumber pl_hashstring(const void *key); parameter the function has the following parameter: key a pointer to a character string. returns the hash number for the specified key. description pl_hashstring can be used as the key hash function for a hash table if the key is a character string. ...
PL_HashTableAdd
key a pointer to the key for the entry to be added. value a pointer to the value for the entry to be added. returns a pointer to the new entry. description add a new entry with the specified key and value to the hash table. ...
PL_HashTableDestroy
description pl_hashtabledestroy frees all the entries in the table and the table itself. ...
PL_HashTableEnumerateEntries
f function to be applied to each entry. arg argument for function f. ...
PL_HashTableLookup
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. ...
PL_HashTableRemove
key a pointer to the key for the entry to be removed. description if there is no entry in the table with the specified key, pl_hashtableremove returns pr_false. ...
PL_NewHashTable
keyhash hash function. keycompare function used to compare keys of entries. valuecompare function used to compare keys of entries. ...
PRFileDesc
a file descriptor used to represent any open file, such as a normal file, an end point of a pipe, or a socket (end point of network communication). syntax #include <prio.h> struct prfiledesc { priomethods *methods; prfileprivate *secret; prfiledesc *lower, *higher; void (*dtor)(prfiledesc *fd); prdescidentity identity; }; typedef struct prfiledesc prfiledesc; parameters methods the i/o methods table. see priomethods. secret layer-dependent implementation data. see prfileprivate. lower pointer to lower layer. higher pointer to higher layer. dtor a destructor function for the layer. identity identity of this particular layer. see prdescidentity. description the fields of this structure are significant only if you are implementing a layer on top of nspr, such as...
PRFileInfo
see prfiletype. size size, in bytes, of file's contents. ...
PRFileInfo64
see prfiletype. size 64-bit size, in bytes, of file's contents. ...
PRFileType
type for enumerators used in the type field of the prfileinfo and prfileinfo64 structures. syntax #include <prio.h> typedef enum prfiletype{ pr_file_file = 1, pr_file_directory = 2, pr_file_other = 3 } prfiletype; enumerators the enumeration has the following enumerators: pr_file_file the information in the structure describes a file. pr_file_directory the information in the structure describes a directory. pr_file_other the information in the structure describes some other kind of file system object. ...
PRIOMethods
d in priomethods implements the pr_write function. for type definition details, see prio.h. the i/o methods table provides procedural access to the functions of the file descriptor. it is the responsibility of a layer implementor to provide suitable functions at every entry point (that is, for every function in the i/o methods table). if a layer provides no functionality, it should call the next lower (higher) function of the same name (for example, the "close" method would return fd->lower->method->close(fd->lower)). not all functions in the methods table are implemented for all types of files. for example, the seek method is implemented for normal files but not for sockets. in cases where this partial implementation occurs, the function returns an error indication with an error code of pr...
PRMcastRequest
structure used to specify values for the pr_sockopt_addmember and pr_sockopt_dropmember socket options that define a request to join or leave a multicast group. syntax #include <prio.h> struct prmcastrequest { prnetaddr mcaddr; prnetaddr ifaddr; }; typedef struct prmcastrequest prmcastrequest; fields the structure has the following fields: mcaddr ip multicast address of group. ifaddr local ip address of interface. description the mcaddr and ifaddr fields are of the type prnetaddr, but their port fields are ignored. only the ip address (inet.ip) fields are used. ...
PR_Initialize
the type for the root function used by pr_initialize is specified as follows: syntax typedef printn (pr_callback *prprimordialfn)(printn argc, char **argv); see also pr_initialize ...
PRProtoEnt
protocol entry 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. ...
PRSeekWhence
specifies how to interpret the offset parameter in setting the file pointer associated with the fd parameter for the pr_seek and pr_seek64 functions. syntax #include <prio.h> typedef prseekwhence { pr_seek_set = 0, pr_seek_cur = 1, pr_seek_end = 2 } prseekwhence; enumerators the enumeration has the following enumerators: pr_seek_set sets the file pointer to the value of the offset parameter. pr_seek_cur sets the file pointer to its current location plus the value of the offset parameter. pr_seek_end sets the file pointer to the size of the file plus the value of the offset parameter. ...
PRThreadType
hread.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 used with caution. ...
PR_Accept
accepts a connection on a specified socket. syntax #include <prio.h> prfiledesc* pr_accept( prfiledesc *fd, prnetaddr *addr, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing the rendezvous socket on which the caller is willing to accept new connections. addr a pointer to a structure of type prnetaddr. on output, this structure contains the address of the connecting entity. timeout a value of type printervaltime specifying the time limit for completion of the accept operation. returns the function returns one of the following values: upon successful acceptance of a connection, a pointer to a new prfiledesc structure representing the newly accepted connection. if unsuccessful, null. furthe...
PR_Access
determines the accessibility of a file. syntax #include <prio.h> prstatus pr_access( const char *name, praccesshow how); parameters the function has the following parameters: name the pathname of the file whose accessibility is to be determined. 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_AtomicAdd
val a value to be added. ...
PR_AtomicDecrement
returns the function returns the decremented value (i.e., the result). ...
PR_AtomicIncrement
returns the function returns the incremented value (i.e., the result). ...
PR_AtomicSet
newval the new value to assign to the val parameter. returns the function returns the prior value of the referenced variable. ...
PR_AttachThread
priority the priority to assign to the thread being attached. stack the stack for the thread being attached. ...
PR_Available
determines the number of bytes (expressed as a 32-bit integer) that are available for reading beyond the current read-write pointer in a specified file or socket. 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_available does not work with pipes on win...
PR_Available64
determines the number of bytes (expressed as a 32-bit integer) that are available for reading beyond the current read-write pointer in a specified file or socket. 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_available does not work with pipes on...
PR_CEnterMonitor
enters the lock associated with a cached monitor. syntax #include <prcmon.h> prmonitor* pr_centermonitor(void *address); parameter the function has the following parameter: address a reference to the data that is to be protected by the monitor. this reference must remain valid as long as there are monitoring operations being performed. returns the function returns one of the following values: if successful, the function returns a pointer to the prmonitor associated with the value specified in the address parameter. if unsuccessful (the monitor cache needs to be expanded and the system is out of memory), the function returns null. description pr_centermonitor uses the value specified in the address parameter to find a monitor in the monitor cache, then enters the lock asso...
PR_CNotify
the calling thread must be in the monitor defined by the value of the address. returns pr_success indicates that the calling thread is the holder of the mutex for the monitor referred to by the address parameter. pr_failure indicates that the monitor has not been entered by the calling thread. ...
PR_CNotifyAll
the calling thread must be in the monitor at the time pr_cnotifyall is called. returns pr_success indicates that the referenced monitor was located and the calling thread was in the monitor. ...
PR_CWait
wait for a notification that a monitor's state has changed. syntax #include <prcmon.h> prstatus pr_cwait( void *address, printervaltime timeout); parameters the function has the following parameters: address the address of the protected object--the same address previously passed to pr_centermonitor. timeout the amount of time (in printervaltime units) that the thread is willing to wait for an explicit notification before being rescheduled. if you specify pr_interval_no_timeout, the function returns if and only if the object is notified. returns the function returns one of the following values: pr_success indicates either that the monitored object has been notified or that the interval specified in the timeout parameter has been exceeded. pr_failure indicates either t...
PR_CallOnce
tem initialization occurs only once. syntax prstatus pr_callonce( prcalloncetype *once, prcalloncefn func); parameters pr_callonce has these parameters: once a pointer to an object of type prcalloncetype. initially (before any threading issues exist), the object must be initialized to all zeros. from that time on, the client should consider the object read-only (or even opaque) and allow the runtime to manipulate its content appropriately. func a pointer to the function the calling client has designed to perform the subsystem initialization. the function will be called once, at most, for each subsystem to be initialized. it should return a prstatus indicating the result of the initialization process. while the first thread executes this function, other threads attempting the s...
PR_CancelJob
causes a previously queued job to be canceled. syntax #include <prtpool.h> nspr_api(prstatus) pr_canceljob(prjob *job); parameter the function has the following parameter: job a pointer to a prjob structure returned by a pr_queuejob function representing the job to be cancelled. returns prstatus ...
PR_Cleanup
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. ...
PR_CloseDir
returns if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. description when a prdir object is no longer needed, it must be closed and freed with a call to pr_closedir call. ...
PR_CloseSemaphore
closes a specified semaphore. syntax #include <pripcsem.h> nspr_api(prstatus) pr_closesemaphore(prsem *sem); parameter the function has the following parameter: sem a pointer to a prsem structure returned from a call to pr_opensemaphore. returns prstatus ...
PR_Connect
initiates a connection on a specified socket. syntax #include <prio.h> prstatus pr_connect( prfiledesc *fd, const prnetaddr *addr, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. addr a pointer to the address of the peer to which the socket is to be connected. timeout a value of type printervaltime specifying the time limit for completion of the connect operation. returns the function returns one of the following values: upon successful completion of connection setup, pr_success. if unsuccessful, pr_failure. further information can be obtained by calling pr_geterror. description pr_connect is usually invoked on a tcp socket, but it may also be invoked on a udp socket. both ...
PR_ConnectContinue
out_flags the out_flags field of the poll descriptor returned by pr_poll(). returns if the nonblocking connect has successfully completed, pr_connectcontinue returns pr_success. if pr_connectcontinue() returns pr_failure, call pr_geterror(): - pr_in_progress_error: the nonblocking connect is still in progress and has not completed yet. ...
PR ConvertIPv4AddrToIPv6
converts an ipv4 address into an (ipv4-mapped) ipv6 address. syntax #include <prnetdb.h> void pr_convertipv4addrtoipv6( pruint32 v4addr, pripv6addr *v6addr ); parameters the function has the following parameters: v4addr the ipv4 address to convert into an ipv4-mapped ipv6 address. this must be specified in network byte order. v6addr a pointer to a buffer, allocated by the caller, that is filled in with the ipv6 address on return. ...
PR_CreateIOLayerStub
methods a pointer to the priomethods structure specifying the functions for the new layer. returns a new file descriptor for the specified layer. description a new layer may be allocated by calling pr_createiolayerstub. the file descriptor returned contains the pointer to the i/o methods table provided. ...
PR_CreatePipe
on return, this parameter contains the file descriptor for the read end of the pipe. writepipe a pointer to a prfiledesc pointer. on return, this parameter contains the file descriptor for the write end of the pipe. ...
PR_CreateThreadPool
create a new hash table. syntax #include <prtpool.h> nspr_api(prthreadpool *) pr_createthreadpool( print32 initial_threads, print32 max_threads, pruint32 stacksize ); parameters the function has the following parameters: initial_threads the number of threads to be created within this thread pool. max_threads the limit on the number of threads that will be created to server the thread pool. stacksize size of the stack allocated to each thread in the thread. returns pointer to a prthreadpool structure or null on error. description ...
PR_DeleteSemaphore
removes a semaphore specified by name from the system. syntax #include <pripcsem.h> nspr_api(prstatus) pr_deletesemaphore(const char *name); parameter the function has the following parameter: name the name of a semaphore that was previously created via a call to pr_opensemaphore. returns prstatus ...
PR_DestroyMonitor
destroys a monitor object. syntax #include <prmon.h> void pr_destroymonitor(prmonitor *mon); parameter the function has the following parameter: mon a reference to an existing structure of type prmonitor. description the caller is responsible for guaranteeing that the monitor is no longer in use before calling pr_destroymonitor. there must be no thread (including the calling thread) in the monitor or waiting on the monitor. ...
PR_DestroyPollableEvent
close the file descriptor associated with a pollable event and release related resources. syntax nspr_api(prstatus) pr_destroypollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. ...
PR_EXTERN
ns or variables that are to be exported from a shared library. syntax #include <prtypes.h> pr_extern(type)prototype description pr_extern is used to define externally visible routines and globals. for syntax details for each platform, see prtypes.h. the macro includes the proper specifications to declare the target extern and set up other required linkages. warning: some platforms do not allow the use of the underscore character (_) as the first character of an exported symbol. ...
PR_EnterMonitor
description when the calling thread returns, it will have acquired the monitor's lock. attempts to acquire the lock for a monitor that is held by some other thread will result in the caller blocking. the operation is neither timed nor interruptible. ...
PR EnumerateAddrInfo
to begin an enumeration, this argument is set to null. ...
PR_ExitMonitor
decrements the entry count associated with a specified monitor and, if the entry count reaches zero, releases the monitor's lock. syntax #include <prmon.h> prstatus pr_exitmonitor(prmonitor *mon); parameter the function has the following parameter: mon a reference to an existing structure of type prmonitor. the monitor object referenced must be one for which the calling thread currently holds the lock. returns the function returns one of the following values: if successful, pr_success. if unsuccessful (the calling thread has not entered the monitor), pr_failure. description if the decremented entry count is zero, pr_exitmonitor releases the monitor's lock. threads that were blocked trying to enter the monitor will be rescheduled. ...
PR_ExportFileMapAsString
creates a string identifying a prfilemap. syntax #include <prshma.h> nspr_api( prstatus ) pr_exportfilemapasstring( prfilemap *fm, prsize bufsize, char *buf ); define pr_filemap_string_bufsize 128 parameters the function has the following parameters: fm a pointer to the prfilemap to be represented as a string. bufsize sizeof(buf) buf a pointer to abuffer of length pr_filemap_string_bufsize. returns prstatus description creates an identifier, as a string, from a prfilemap object previously created with pr_openanonfilemap. ...
PR FreeAddrInfo
destroys the praddrinfo structure returned by pr_getaddrinfobyname. syntax #include <prnetdb.h> void pr_enumerateaddrinfo(praddrinfo *addrinfo); parameters the function has the following parameters: addrinfo a pointer to a praddrinfo structure returned by a successful call to pr_getaddrinfobyname. returns the function doesn't return anything. ...
PR GetAddrInfoByName
looks up a host by name. equivalent to getaddrinfo(host, null, ...) of rfc 3493. syntax #include <prnetdb.h> praddrinfo *pr getaddrinfobyname( const char *hostname, pruint16 af, printn flags); parameters the function has the following parameters: hostname the character string defining the host name of interest. 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 store...
PR GetCanonNameFromAddrInfo
extracts the canonical name of the hostname passed to pr_getaddrinfobyname. syntax #include <prnetdb.h> const char *pr_getcanonnamefromaddrinfo(const praddrinfo *addrinfo); parameters the function has the following parameters: addrinfo a pointer to a praddrinfo structure returned by a successful call to pr_getaddrinfobyname. returns the function returns a const pointer to the canonical hostname stored in the given praddrinfo structure. this pointer is invalidated once the praddrinfo structure is destroyed by a call to pr_freeaddrinfo. ...
PR_GetConnectStatus
returns the function returns one of these values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. ...
PR_GetDescType
describes what type of file is referenced by a specified file descriptor. syntax #include <prio.h> prdesctype pr_getdesctype(prfiledesc *file); parameter the function has the following parameter: file a pointer to a prfiledesc object whose descriptor type is to be returned. returns the function returns a prdesctype enumeration constant that describes the type of file. description the prdesctype enumeration is defined as follows: typedef enum prdesctype { pr_desc_file = 1, pr_desc_socket_tcp = 2, pr_desc_socket_udp = 3, pr_desc_layered = 4 } prdesctype; the enumeration has the following enumerators: pr_desc_file the prfiledesc object represents a normal file. pr_desc_socket_tcp the prfiledesc object represents a tcp socket. pr_desc_socket_udp the prf...
PR_GetFileInfo
gets information about a file with a specified pathname. file size is expressed as a 32-bit integer. syntax #include <prio.h> prstatus pr_getfileinfo( const char *fn, prfileinfo *info); parameters the function has the following parameters: fn the pathname of the file to get information about. info a pointer to a file information object (see prfileinfo). on output, pr_getfileinfo writes information about the given file to the file information object. returns one of the following values: if the file information is successfully obtained, pr_success. if the file information is not successfully obtained, pr_failure. description pr_getfileinfo stores information about the file with the specified pathname in the prfileinfo structure pointed to by info. the file size is ret...
PR_GetFileInfo64
gets information about a file with a specified pathname. file size is expressed as a 64-bit integer. syntax #include <prio.h> prstatus pr_getfileinfo64( const char *fn, prfileinfo64 *info); parameters the function has the following parameters: fn the pathname of the file to get information about. info a pointer to a 64-bit file information object (see prfileinfo64). on output, pr_getfileinfo64 writes information about the given file to the file information object. returns one of the following values: if the file information is successfully obtained, pr_success. if the file information is not successfully obtained, pr_failure. description pr_getfileinfo64 stores information about the file with the specified pathname in the prfileinfo64 structure pointed to by info. t...
PR_GetInheritedFileMap
imports a prfilemap previously exported by my parent process via pr_createprocess. syntax #include <prshma.h> nspr_api( prfilemap *) pr_getinheritedfilemap( const char *shmname ); parameter the function has the following parameter: shmname the name provided to pr_processattrsetinheritablefilemap. returns pointer to prfilemap or null on error. description pr_getinheritedfilemap retrieves a prfilemap object exported from its parent process via pr_createprocess. note: this function is not implemented. ...
PR_GetLayersIdentity
gets the unique identity for the layer of the specified file descriptor. syntax #include <prio.h> prdescidentity pr_getlayersidentity(prfiledesc* fd); parameter the function has the following parameter: fd a pointer to a file descriptor. returns if successful, the function returns the prdescidentity for the layer of the specified file descriptor. ...
PR_GetOpenFileInfo
gets an open file's information. file size is expressed as a 32-bit integer. syntax #include <prio.h> prstatus pr_getopenfileinfo( prfiledesc *fd, prfileinfo *info); parameters the function has the following parameters: fd a pointer to a prfiledesc object for an open file. info a pointer to a prfileinfo object. on output, information about the given file is written into the file information object. returns the function returns one of the following values: if file information is successfully obtained, pr_success. if file information is not successfully obtained, pr_failure. description pr_getopenfileinfo obtains the file type (normal file, directory, or other), file size (as a 32-bit integer), and the file creation and modification times of the open file represented ...
PR_GetOpenFileInfo64
gets an open file's information. file size is expressed as a 64-bit integer. syntax #include <prio.h> prstatus pr_getopenfileinfo64( prfiledesc *fd, prfileinfo *info); parameters the function has the following parameters: fd a pointer to a prfiledesc object for an open file. info a pointer to a prfileinfo64 object. on output, information about the given file is written into the file information object. returns the function returns one of the following values: if file information is successfully obtained, pr_success. if file information is not successfully obtained, pr_failure. description pr_getopenfileinfo64 is the 64-bit version of pr_getopenfileinfo. it obtains the file type (normal file, directory, or other), file size (as a 64-bit integer), and the creation and...
PR_GetPeerName
gets the network address of the connected peer. syntax #include <prio.h> prstatus pr_getpeername( prfiledesc *fd, prnetaddr *addr); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. addr on return, the address of the peer connected to the socket. returns if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be obtained by calling pr_geterror. ...
PR_GetProtoByName
looks up a protocol entry based on the protocol's name. syntax #include <prnetdb.h> prstatus pr_getprotobyname( const char* protocolname, char* buffer, print32 bufsize, prprotoent* result); parameters the function has the following parameters: protocolname a pointer to the character string of the protocol's name. buffer a pointer to a scratch buffer for the runtime to return result. this buffer is allocated by the caller. bufsize number of bytes in the buffer parameter. the buffer must be at least pr_netdb_buf_size bytes. result on input, a pointer to a prprotoent structure. on output, this structure is filled in by the runtime if the function returns pr_success. returns the function returns one of the following values: if successful, pr_success. if unsuccessfu...
PR_GetProtoByNumber
looks up a protocol entry based on protocol's number. syntax #include <prnetdb.h> prstatus pr_getprotobynumber( print32 protocolnumber, char* buffer, print32 bufsize, prprotoent* result); parameters the function has the following parameters: protocolnumber the number assigned to the protocol. buffer a pointer to a scratch buffer for the runtime to return result. this buffer is allocated by the caller. bufsize number of bytes in the buffer parameter. the buffer must be at least pr_netdb_buf_size bytes. result on input, a pointer to a prnetaddr structure. on output, this structure is filled in by the runtime if the function returns pr_success. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. you can...
PR_GetSockName
gets network address for a specified socket. syntax #include <prio.h> prstatus pr_getsockname( prfiledesc *fd, prnetaddr *addr); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing the socket. addr on return, the address of the socket. returns if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be obtained by calling pr_geterror. ...
PR_GetSocketOption
data a pointer to a structure of type prsocketoptiondata. on input, the option field of this structure must be set to indicate which socket option to retrieve for the socket represented by the fd parameter. ...
PR_GetThreadPriority
returns the priority of a specified thread. syntax #include <prthread.h> prthreadpriority pr_getthreadpriority(prthread *thread); parameter pr_getthreadpriority has the following parameter: thread a valid identifier for the thread whose priority you want to know. ...
PR_GetThreadPrivate
returns null if the data has not been set. description pr_getthreadprivate may be called at any time during a thread's execution. ...
PR_GetUniqueIdentity
asks the runtime to allocate a unique identity for a layer identified by the layer's name. syntax #include <prio.h> prdescidentity pr_getuniqueidentity(const char *layer_name); parameter the function has the following parameter: layer_name the string associated with the creation of a layer's identity. returns the function returns one of the following values: if successful, the prdescidentity for the layer associated with the string specified in the layer named layer_name. if the function cannot allocate enough dynamic memory, it fails and returns the value pr_invalid_io_layer with the error code pr_out_of_memory_error. description a string may be associated with a layer when the layer is created. pr_getuniqueidentity allocates a unique layer identity and associates it wit...
PR_IMPLEMENT
used to define implementations of symbols that are to be exported from a shared library. syntax #include <prtypes.h> pr_implement(type)implementation description pr_implement is used to define implementations of externally visible routines and globals. for syntax details for each platform, see prtypes.h. warning: some platforms do not allow the use of the underscore character (_) as the first character of an exported symbol. ...
PR_ImportFileMapFromString
creates a prfilemap from an identifying string. syntax #include <prshma.h> nspr_api( prfilemap * ) pr_importfilemapfromstring( const char *fmstring ); parameter the function has the following parameter: fmstring a pointer to string created by pr_exportfilemapasstring. returns prfilemap pointer or null on error. description pr_importfilemapfromstring creates a prfilemap object from a string previously created by pr_exportfilemapasstring. ...
PR_Initialized
checks whether the runtime has been initialized. syntax #include <prinit.h> prbool pr_initialized(void); returns the function returns one of the following values: if pr_init has already been called, pr_true. if pr_init has not already been called, pr_false. ...
PR_IntervalToMicroseconds
...
PR_IntervalToMilliseconds
...
PR_IntervalToSeconds
...
PR_JoinJob
blocks the current thread until a job has completed. syntax #include <prtpool.h> nspr_api(prstatus) pr_joinjob(prjob *job); parameter the function has the following parameter: job a pointer to a prjob structure returned by a pr_queuejob function representing the job to be cancelled. returns prstatus ...
PR_JoinThreadPool
waits for all threads in a thread pool to complete, then releases resources allocated to the thread pool. syntax #include <prtpool.h> nspr_api(prstatus) pr_jointhreadpool( prthreadpool *tpool ); parameter the function has the following parameter: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool. returns prstatus ...
PR_MemMap
offset the starting offset of the section of file to be mapped. the offset must be aligned to whole pages. len length of the section of the file to be mapped. returns the starting address of the memory region to which the section of file is mapped. returns null on error. ...
PR_MicrosecondsToInterval
converts standard clock microseconds to platform-dependent intervals. syntax #include <prinrval.h> printervaltime pr_microsecondstointerval(pruint32 milli); parameter the function has the following parameter: micro the number of microseconds to convert to interval form. returns platform-dependent equivalent of the value passed in the micro parameter. ...
PR_MillisecondsToInterval
converts standard clock milliseconds to platform-dependent intervals. syntax #include <prinrval.h> printervaltime pr_millisecondstointerval(pruint32 milli); parameter the function has the following parameter: milli the number of milliseconds to convert to interval form. returns platform-dependent equivalent of the value passed in the milli parameter. ...
PR_MkDir
creates a directory with a specified name and access mode. syntax #include <prio.h> prstatus pr_mkdir( const char *name, printn mode); parameters the function has the following parameters: name the name of the directory to be created. all the path components up to but not including the leaf component must already exist. mode the access permission bits of the file mode of the new directory if the file is created when pr_create_file is on. caveat: the mode parameter is currently applicable only on unix platforms. it may be applicable to other platforms in the future. possible values include the following: 00400. read by owner. 00200. write by owner. 00100. search by owner. 00040. read by group. 00020. write by group. 00010. search by group. 00004. read by othe...
PR_NEXT_LINK
returns the next element in a list. syntax #include <prclist.h> prclist *pr_next_link (prclist *elemp); parameter elemp a pointer to the element. returns a pointer to a list element. description pr_next_link returns a pointer to the element following the specified element. it can be used to traverse a list. the following element is not removed from the list. ...
PR_NewCondVar
creates a new condition variable. syntax #include <prcvar.h> prcondvar* pr_newcondvar(prlock *lock); parameter pr_newcondvar has one parameter: lock the identity of the mutex that protects the monitored data, including this condition variable. returns the function returns one of the following values: if successful, a pointer to the new condition variable object. if unsuccessful (for example, if system resources are unavailable), null. ...
PR_NewLock
creates a new lock. syntax #include <prlock.h> prlock* pr_newlock(void); returns the function returns one of the following values: if successful, a pointer to the new lock object. if unsuccessful (for example, the lock cannot be created because of resource constraints), null. description pr_newlock creates a new opaque lock. ...
PR_NewMonitor
creates a new monitor object. the caller is responsible for the object and is expected to destroy it when appropriate. syntax #include <prmon.h> prmonitor* pr_newmonitor(void); returns the function returns one of the following values: if successful, a pointer to a prmonitor object. if unsuccessful (for example, if some operating system resource is unavailable), null. description a newly created monitor has an entry count of zero. ...
PR_NewThreadPrivateIndex
returns a new index for a per-thread private data table and optionally associates a destructor with the data that will be assigned to the index. syntax #include <prthread.h> prstatus pr_newthreadprivateindex( pruintn *newindex, prthreadprivatedtor destructor); parameters pr_newthreadprivateindex has the following parameters: newindex on output, an index that is valid for all threads in the process. you use this index with pr_setthreadprivate and pr_getthreadprivate. destructor specifies a destructor function prthreadprivatedtor for the private data associated with the index. this function can be specified as null. returns the function returns one of the following values: if successful, pr_success. if the total number of indices exceeds 128, pr_failure. description ...
PR_NotifyAllCondVar
if unsuccessful (for example, if the caller has not locked the lock associated with the condition variable), pr_failure. description the calling thread must hold the lock that protects the condition, as well as the invariants that are tightly bound to the condition. ...
PR_NotifyCondVar
if unsuccessful (for example, if the caller has not locked the lock associated with the condition variable), pr_failure. ...
PR_OpenAnonFileMap
size the size of the shared memory. prot how the shared memory is mapped. returns pointer to prfilemap or null on error. ...
PR_OpenDir
returns if the directory is successfully opened, a prdir object is dynamically allocated and the function returns a pointer to it. if the directory cannot be opened, the function returns null. ...
PR_OpenSemaphore
flags how to create or open the semaphore. ...
PR_OpenSharedMemory
size the size of the shared memory segment. flags options for creating the shared memory. mode same as passed to pr_open. returns pointer to opaque structure prsharedmemory, or null if an error occurs. retrieve the reason for the failure by calling pr_geterror and pr_getoserror. description pr_opensharedmemory creates a new...
PR_PopIOLayer
removes a layer from the stack. syntax #include <prio.h> prfiledesc *pr_popiolayer( prfiledesc *stack, prdescidentity id); parameters the function has the following parameters: stack a pointer to a prfiledesc object representing the stack from which the specified layer is to be removed. id identity of the layer to be removed from the stack. returns the function returns one of the following values: if the layer is successfully removed from the stack, a pointer to the removed layer. if the layer is not found in the stack or cannot be popped (for example, the bottommost layer), the function returns null with the error code pr_invalid_argument_error. description pr_popiolayer pops the specified layer from the stack. if the object to be removed is found, pr_popiolayer re...
PR_PostSemaphore
increments the value of a specified semaphore. syntax #include <pripcsem.h> nspr_api(prstatus) pr_postsemaphore(prsem *sem); parameter the function has the following parameter: sem a pointer to a prsem structure returned from a call to pr_opensemaphore. returns prstatus ...
PR_ProcessAttrSetInheritableFileMap
fm pointer to a prfilemap structure to be passed to the child process. shmname pointer to the name for the prfilemap; used by child. ...
PR_PushIOLayer
adds a layer onto the stack. syntax #include <prio.h> prstatus pr_pushiolayer( prfiledesc *stack, prdescidentity id, prfiledesc *layer); parameters the function has the following parameters: stack a pointer to a prfiledesc object representing the stack. id a prdescidentity object for the layer on the stack above which the new layer is to be added. layer a pointer to a prfiledesc object representing the new layer to be added to the stack. returns the function returns one of the following values: if the layer is successfully pushed onto the stack, pr_success. if the layer is not successfully pushed onto the stack, pr_failure. use pr_geterror to get additional information regarding the reason for the failure. description a file descriptor for a layer (possibly allo...
PR_QueueJob
fn the function to be executed when the job is executed. ...
PR_QueueJob_Accept
iod a pointer to a prjobiodesc structure. ...
PR_QueueJob_Connect
iod a pointer to a prjobiodesc structure. ...
PR_QueueJob_Read
iod a pointer to a prjobiodesc structure. ...
PR_QueueJob_Timer
iod a pointer to a prjobiodesc structure. timeout a value, expressed as a printervaltime, to wait before queuing the job. ...
PR_QueueJob_Write
iod a pointer to a prjobiodesc structure. ...
PR_Recv
receives bytes from a connected socket. syntax #include <prio.h> print32 pr_recv( prfiledesc *fd, void *buf, print32 amount, printn flags, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. buf a pointer to a buffer to hold the data received. amount the size of buf (in bytes). flags must be zero or pr_msg_peek. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. returns the function returns one of the following values: a positive number indicates the number of bytes actually received. the value 0 means the network connection is closed. the value -1 indicates a failure. the reason for the failure can be obtained by cal...
PR_RmDir
returns if successful, pr_success. if unsuccessful, pr_failure. the actual reason can be retrieved via pr_geterror. description pr_rmdir removes the directory specified by the pathname name. the directory must be empty. ...
PR_SecondsToInterval
converts standard clock seconds to platform-dependent intervals. syntax #include <prinrval.h> printervaltime pr_secondstointerval(pruint32 seconds); parameter the function has the following parameter: seconds the number of seconds to convert to interval form. returns platform-dependent equivalent of the value passed in the seconds parameter. ...
PR_Send
sends bytes from a connected socket. syntax #include <prio.h> print32 pr_send( prfiledesc *fd, const void *buf, print32 amount, printn flags, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. buf a pointer to a buffer containing the data to be sent. amount the size of buf (in bytes). flags this obsolete parameter must always be zero. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. returns the function returns one of the following values: a positive number indicates the number of bytes successfully sent. if the parameter fd is a blocking socket, this number must always equal amount. the value -1 indicates a failure...
PR_SendTo
sends bytes a socket to a specified destination. syntax #include <prio.h> print32 pr_sendto( prfiledesc *fd, const void *buf, print32 amount, printn flags, const prnetaddr *addr, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. buf a pointer to a buffer containing the data to be sent. amount the size of buf (in bytes). flags this obsolete parameter must always be zero. addr a pointer to the address of the destination. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. returns the function returns one of the following values: a positive number indicates the number of bytes successfully sent. the value -1 indicate...
PR_SetPollableEvent
set a pollable event. syntax nspr_api(prstatus) pr_setpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. ...
PR_SetSocketOption
data a pointer to a structure of type prsocketoptiondata specifying the options to set. returns if successful, pr_success. if unsuccessful, pr_failure. ...
PR_SetThreadPriority
priority the priority you want to set. description modifying the priority of a thread other than the calling thread is risky. ...
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_Sleep
returns calling pr_sleep with a parameter equivalent to pr_interval_no_timeout is an error and results in a pr_failure error. description pr_sleep simply waits on a condition for the amount of time specified. if you set ticks to pr_interval_no_wait, the thread yields. ...
PR_Sync
synchronizes any buffered data for a file descriptor to its backing device (disk). syntax #include <prio.h> prstatus pr_sync(prfiledesc *fd); parameter the function has the following parameter: fd pointer to a prfiledesc object representing a file. returns the function returns one of the following values: on successful completion, pr_success. if the function fails, pr_failure. description pr_sync writes all the in-memory buffered data of the specified file to the disk. ...
PR_TicksPerSecond
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_UnloadLibrary
unloads a library loaded with pr_loadlibrary. syntax #include <prlink.h> prstatus pr_unloadlibrary(prlibrary *lib); parameters the function has this parameter: lib a reference previously returned from pr_loadlibrary. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. use pr_geterror to find the reason for the failure. description this function undoes the effect of a pr_loadlibrary. after calling this function, future references to the library using its identity as returned by pr_loadlibrary will be invalid. ...
PR_Unlock
releases a specified lock object. releasing an unlocked lock results in an error. attempting to release a lock that was locked by a different thread causes undefined behavior. syntax #include <prlock.h> prstatus pr_unlock(prlock *lock); parameter pr_unlock has one parameter: lock a pointer to a lock object to be released. returns the function returns one of the following values: if successful, pr_success. if unsuccessful (for example, if the caller does not own the lock), pr_failure. see also pr_lock ...
PR_VersionCheck
compares the version of nspr assumed by the caller (the imported version) with the version being offered by the runtime (the exported version). syntax #include <prinit.h> prbool pr_versioncheck(const char *importedversion); parameter pr_versioncheck has one parameter: importedversion the version of the shared library being imported. returns the function returns one of the following values: if the version of the shared library is compatible with that expected by the caller, pr_true. if the versions are not compatible, pr_false. description pr_versioncheck tests whether the version of the library being imported (importedversion) is compatible with the running version of the shared library. this is a string comparison of sorts, though the details of the comparison will vary ...
PR_WaitCondVar
waits on a condition. syntax #include <prcvar.h> prstatus pr_waitcondvar( prcondvar *cvar, printervaltime timeout); parameters pr_waitcondvar has the following parameters: cvar the condition variable on which to wait. timeout the value pr_interval_no_timeout requires that a condition be notified (or the thread interrupted) before it will resume from the wait. the value pr_interval_no_wait causes the thread to release the lock, possibly causing a rescheduling within the runtime, then immediately attempt to reacquire the lock and resume. 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_interru...
PR_WaitForPollableEvent
blocks the calling thread until the pollable event is set, and then atomically unsetting the event before returning. syntax nspr_api(prstatus) pr_waitforpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. ...
PR_WaitSemaphore
returns prstatus description pr_waitsemaphore tests the value of the semaphore. if the value of the semaphore is > 0, the value of the semaphore is decremented and the function returns. ...
PR_htonl
performs 32-bit conversion from host byte order to network byte order. syntax #include <prnetdb.h> pruint32 pr_htonl(pruint32 conversion); parameter the function has the following parameter: conversion the 32-bit unsigned integer, in host byte order, to be converted. returns the value of the conversion parameter in network byte order. ...
PR_htons
performs 16-bit conversion from host byte order to network byte order. syntax #include <prnetdb.h> pruint16 pr_htons(pruint16 conversion); parameter the function has the following parameter: conversion the 16-bit unsigned integer, in host byte order, to be converted. returns the value of the conversion parameter in network byte order. ...
PR_ntohl
performs 32-bit conversion from network byte order to host byte order. syntax #include <prnetdb.h> pruint32 pr_ntohl(pruint32 conversion); parameter the function has the following parameter: conversion the 32-bit unsigned integer, in network byte order, to be converted. returns the value of the conversion parameter in host byte order. ...
PR_ntohs
performs 16-bit conversion from network byte order to host byte order. syntax #include <prnetdb.h> pruint16 pr_ntohs(pruint16 conversion); parameter the function has the following parameter: conversion the 16-bit unsigned integer, in network byte order, to be converted. returns the value of the conversion parameter in host byte order. ...
PR_strtod
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. ...
NSPR
getting nspr nspr is available in various source and binary packages, depending on your platform: windows: build the source package, using the nspr build instructions. mac: install the macports nspr package, or the homebrew nspr package. ubuntu: install the libnspr4-dev package via apt-get. debian: install the libnspr4-dev package via apt-get. ...
Function_Name
ate that matches the der-encoded certificate. a match is found when the issuer and serial number of the der-encoded certificate are found on a certificate in the certificate database. returns full description of the return value, for example: a pointer to a certcertificate representing the certificate in the database that matched the dercert, or null if none was found. the certificate is a shallow copy, use cert_destroycertificate to decrement the reference count on the certificate instance. see also copy of the mxr link, with the following text occurrences of function_name in the current nss source code (generated by mxr). ...
CERT_FindCertByDERCert
text? and the ?nsstrustdomain? to find the certificate that matches the der-encoded certificate. a match is found when the issuer and serial number of the der-encoded certificate are found on a certificate in the certificate database. returns a pointer to a certcertificate representing the certificate in the database that matched the dercert, or null if none was found. the certificate is a shallow copy, use cert_destroycertificate to decrement the reference count on the certificate instance. see also occurrences of cert_findcertbydercert in the current nss source code (generated by lxr). ...
CERT_FindCertByIssuerAndSN
to contain the issuer name and the serial number (see [example]) description this function creates a certificate key using the issuerandsn and it then uses the key to find the matching certificate in the database. returns a pointer to a certcertificate representing the certificate in the database that matched the issuer and serial number, or null if none was found. the certificate is a shallow copy, use cert_destroycertificate to decrement the reference count on the certificate instance. example certissuerandsn issuersn; issuersn.derissuer.data = caname->data; issuersn.derissuer.len = caname->len; issuersn.serialnumber.data = authoritykeyid->authcertserialnumber.data; issuersn.serialnumber.len = authoritykeyid->authcertserialnumber.len; issuercert = cert_findcertbyissuerandsn(cert->...
Certificate functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
NSS Code Coverage
orange: 0-40% of blocks tested. red: file not tested. ...
Cryptography functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
HTTP delegation
start with sec_http. to find an example implementation, you may look at bug 111384, which tracks the implementation in mozilla client applications. specifying an ocsp proxy the remainder of this document is a short howto. one might expect the api defines a simple function that accepts the uri and data to be sent, and returns the result data. but there is no such simple interface. the api should allow nss to use the http client either asynchronously or synchronously. in addition, during an application session with ocsp enabled, a large number of ocsp requests might have to be sent. therefore the api should allow for keep-alive (persistent) http connections. http uris consist of host:port and a path, e.g. http://ocsp.provider.com:80/cgi-bin/ocsp-responder if nss needs to access a http server, i...
HTTP delegation
start with sec_http. to find an example implementation, you may look at bug 111384, which tracks the implementation in mozilla client applications. specifying an ocsp proxy the remainder of this document is a short howto. one might expect the api defines a simple function that accepts the uri and data to be sent, and returns the result data. but there is no such simple interface. the api should allow nss to use the http client either asynchronously or synchronously. in addition, during an application session with ocsp enabled, a large number of ocsp requests might have to be sent. therefore the api should allow for keep-alive (persistent) http connections. http uris consist of host:port and a path, e.g. http://ocsp.provider.com:80/cgi-bin/ocsp-responder if nss needs to access a http server, i...
Build instructions for JSS 4.3.x
build instructions for jss 4.3.x newsgroup: mozilla.dev.tech.crypto before building jss, you need to set up your system as follows: build nspr/nss by following the nspr/nss build instructions, to check that nss built correctly, run all.sh (in mozilla/security/nss/tests) and examine the results (in mozilla/test_results/security/computername.#/results.html. install a java compiler and runtime. jss supports java version 1.5 or later. we suggest you use the latest. you must have perl version 5.005 or later. now you are ready to build jss. follow these steps: switch to the appropriate directory and check out jss from the root of your source tree. cvs co -r jss_4_3_1_rtm mozilla/security/jss or cvs co -r jss_4_3_rtm mozilla/security/jss setup environment variables needed...
JSS FAQ
Mozilla › Projects › NSS › JSS › JSS FAQ
org/mozilla/jss/util/base64inputstream.java jss/samples/pqggen.java jss/samples/pkcs12.java if i don't call setcipherpolicy, is the domestic policy used by default? yes, domestic is the default because we call nss_setdomesticpolicy() during cryptomanager.initialize(). setcipherpolicy does not need to be called by a jss app unless that app wants to limit itself to export-allowed cipher suites. my ssl connection is hanging on windows? nspr makes use of nt vs. windows distinction and provides different nt and windows builds. many netscape products, including nss, have nt and windows builds that are essentially the same except one difference: one is linked with the nt version of nspr and the other is linked with the windows version of nspr. the nt fiber problem a...
Using JSS
Mozilla › Projects › NSS › JSS › Using JSS
and nss libraries for i/o and crypto. jss version 3.0 linked statically with nss, so it only required nspr. jss versions 3.1 and later link dynamically with nss, so they also require the nss shared libraries. the exact library names vary according to the convention for each platform. for example, the nspr library is called nspr4.dll or libnspr4.dll on windows and libnspr4.so on solaris. the following table gives the core names of the libraries, omitting the platform-specific prefix and suffix. jss dependencies core library name description binary release location nspr4 nspr os abstraction layer http://ftp.mozilla.org/pub/mozilla.org/nspr/releases plc4 nspr standard c library replacement functions ...
NSS Memory allocation
recently allocated that arena, but rather will be the stack of the code that first allocated that arena from the heap, and then placed it on the free list. to solve that problem, it is generally necessary to disable the arena free list, so that arenas are actually freed back to the heap each time they are freed, and are allocated afresh from the heap each time they are allocated. this makes nss slower, but produces accurate leak allocation stacks. to accomplish that, set an environment variable prior to the initialization of nss and nspr. this can be done outside the program entirely, or can be done by the program itself, in the main() function. set the environment variable nss_disable_arena_free_list to have any non-empty value, e.g. nss_disable_arena_free_list=1. ...
NSS 3.15.1 release notes
introduction network security services (nss) 3.15.1 is a patch release for nss 3.15. the bug fixes in nss 3.15.1 are described in the "bugs fixed" section below. distribution information nss 3.15.1 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_1_rtm/src/ new in nss 3.15.1 new functionality tls 1.2: tls 1.2 (rfc 5246) is supported. hmac-sha256 cipher suites (rfc 5246 and rfc 5289) are supported, allowing tls to be used without md5 and sha-1. note the following limitations. the hash function used in the signature for tls 1.2 client authentication must be the hash function of the tls 1.2 prf, which is always sha-256 in nss 3.15.1. aes...
NSS 3.15.5 release notes
distribution information the hg tag is nss_3_15_5_rtm. nss 3.15.5 requires nspr 4.10.2 or newer. nss 3.15.5 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_5_rtm/src/ new in nss 3.15.5 new functionality added support for the tls application layer protocol negotiation (alpn) extension. ...
NSS 3.16.1 release notes
distribution information the hg tag is nss_3_16_1_rtm. nss 3.16.1 requires nspr 4.10.5 or newer. nss 3.16.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_16_1_rtm/src/ new in nss 3.16.1 new functionality added the "ecc" flag for modutil to select the module used for elliptic curve cryptography (ecc) operations. ...
NSS 3.16.2.1 release notes
introduction network security services (nss) 3.16.2.1 is a patch release for nss 3.16, based on the nss 3.16.2 release. the bug fixes in nss 3.16.2.1 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_16_2_1_rtm. nss 3.16.2.1 requires nspr 4.10.6 or newer. nss 3.16.2.1 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_2_1_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.16.2.1. users are encouraged to upgrade immediately. bug 1064636 - (cve-2014-1568) rsa signature forgery in nss. see also mfsa 2014-73 for details. new in nss 3.16.2.1 new functionality no ne...
NSS 3.16.2.2 release notes
distribution information the hg tag is nss_3_16_2_2_rtm. nss 3.16.2.2 requires nspr 4.10.6 or newer. nss 3.16.2.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_16_2_2_rtm/src/ new in nss 3.16.2.2 new functionality no new functionality is introduced in this release. this is a patch release to fix a regression. ...
NSS 3.16.2.3 release notes
distribution information the hg tag is nss_3_16_2_3_rtm. nss 3.16.2.3 requires nspr 4.10.6 or newer. ...
NSS 3.16.6 release notes
distribution information the hg tag is nss_3_16_6_rtm. nss 3.16.6 requires nspr 4.10.6 or newer. nss 3.16.6 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_6_rtm/src/ new in nss 3.16.6 new functionality no new functionality is introduced in this release. this is a patch release to fix a regression. ...
NSS 3.17.2 release notes
distribution information the hg tag is nss_3_17_2_rtm. nss 3.17.2 requires nspr 4.10.7 or newer. nss 3.17.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_17_2_rtm/src/ new in nss 3.17.2 new functionality no new functionality is introduced in this release. this is a patch release to fix a regression and other bugs. ...
NSS 3.17.4 release notes
distribution information the hg tag is nss_3_17_4_rtm. nss 3.17.4 requires nspr 4.10.7 or newer. nss 3.17.4 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_4_rtm/src/ new in nss 3.17.4 new functionality no new functionality is introduced in this release. this is a patch release to fix multiple bugs. ...
NSS 3.19.1 release notes
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.2.2 release notes
(current users of nss 3.19.3 or nss 3.19.4 are advised to update to nss 3.20.2, nss 3.21, or a later release.) distribution information the hg tag is nss_3_19_2_2_rtm. nss 3.19.2.2 requires nspr 4.10.10 or newer. ...
NSS 3.19 release notes
ixes 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. new in nss 3.19 new functionality for some certificates, such as root ca certificates that don't embed any constraints, nss might impose additional constraints such as name constraints. a new api (cert_getimposednameconstraints) has been added that allows one to lookup imposed constraints. it is possible to override the directory (sqlite_lib_dir) in which the nss build system will look for the sqlite library. new functions in cert.h cert_getimposednameconstraints - check if any imposed constraints exist for the given certificate, and if found, return the constraints as encoded certificate extensions. notable changes in nss 3.1...
NSS 3.20.2 release notes
distribution information the hg tag is nss_3_20_2_rtm. nss 3.20.2 requires nspr 4.10.10 or newer. nss 3.20.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_20_2_rtm/src/ security fixes in nss 3.20.2 bug 1158489 / cve-2015-7575 - prevent md5 downgrade in tls 1.2 signatures. ...
NSS 3.21.1 release notes
introduction network security services (nss) 3.21.1 is a security patch release for nss 3.21. the bug fixes in nss 3.21.1 are described in the "security fixes" section below. distribution information the hg tag is nss_3_21_1_rtm. nss 3.21.1 requires nspr 4.10.10 or newer. nss 3.21.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_21_1_rtm/src/ new in nss 3.21.1 new functionality no new functionality is introduced in this release. security fixes in nss 3.21.1 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures. an attacker could create a specially-crafted certificate which, when parsed by n...
NSS 3.21.2 release notes
distribution information the hg tag is nss_3_21_2_rtm. nss 3.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. ...
NSS 3.21.3 release notes
distribution information the hg tag is nss_3_21_3_rtm. nss 3.21.3 requires nspr 4.10.10 or newer. nss 3.21.3 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_3_rtm/src/ new in nss 3.21.3 new functionality no new functionality is introduced in this release. ...
NSS 3.21.4 release notes
distribution information the hg tag is nss_3_21_4_rtm. nss 3.21.4 requires nspr 4.12 or newer. nss 3.21.4 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_4_rtm/src/ new in nss 3.21.4 no new functionality is introduced in this release. ...
NSS 3.22.1 release notes
distribution information the hg tag is nss_3_22_1_rtm. nss 3.22.1 requires nspr 4.12 or newer. nss 3.22.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_22_1_rtm/src/ new in nss 3.22.1 new functionality no new functionality is introduced in this release. ...
NSS 3.22.2 release notes
introduction network security services (nss) 3.22.2 is a security patch release for nss 3.22. the bug fixes in nss 3.22.2 are described in the "security fixes" section below. distribution information the hg tag is nss_3_22_2_rtm. nss 3.22.2 requires nspr 4.12 or newer. nss 3.22.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_22_2_rtm/src/ new in nss 3.22.2 new functionality no new functionality is introduced in this release. security fixes in nss 3.22.2 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures. an attacker could create a specially-crafted certificate which, when parsed by n...
NSS 3.22.3 release notes
distribution information the hg tag is nss_3_22_3_rtm. nss 3.22.3 requires nspr 4.12 or newer. nss 3.22.3 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_3_rtm/src/ new in nss 3.22.3 new functionality no new functionality is introduced in this release. ...
NSS 3.25.1 release notes
client applications experienced with nss 3.25. notable changes in nss 3.25.1 md5 signature algorithms sent by the server in certificaterequest messages are now properly ignored. previously, with rare server configurations, an md5 signature algorithm might have been selected for client authentication and caused the client to abort the connection soon after. bugs fixed in nss 3.25.1 the following bug has been fixed in nss 3.25.1: ignore md5 signature algorithms in certificate requests compatibility nss 3.25.1 shared libraries are backwards compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.25.1 shared libraries without recompiling or relinking. applications that restrict their use of nss apis to the functions...
NSS 3.26.2 release notes
ient applications experienced with nss 3.26.1. notable changes in nss 3.26.2 md5 signature algorithms sent by the server in certificaterequest messages are now properly ignored. previously, with rare server configurations, an md5 signature algorithm might have been selected for client authentication and caused the client to abort the connection soon after. bugs fixed in nss 3.26.2 the following bug has been fixed in nss 3.26.2: ignore md5 signature algorithms in certificate requests compatibility nss 3.26.2 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.26.2 shared libraries without recompiling or relinking. furthermore, applications that restrict their use of nss apis to t...
NSS 3.26 release notes
urce tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_26_rtm/src/ new in nss 3.26 new functionality the selfserv test utility has been enhanced to support alpn (http/1.1) and 0-rtt added support for the system-wide crypto policy available on fedora linux, see http://fedoraproject.org/wiki/changes/cryptopolicy introduced build flag nss_disable_libpkix which allows compilation of nss without the libpkix library notable changes in nss 3.26 the following ca certificate was added cn = isrg root x1 sha-256 fingerprint: 96:bc:ec:06:26:49:76:f3:74:60:77:9a:cf:28:c5:a7:cf:e8:a3:c0:aa:e1:1a:8f:fc:ee:05:c0:bd:df:08:c6 npn is disabled, and alpn is enabled by default the nss test suite now completes with the experimental tls 1.3 ...
NSS 3.27.2 Release Notes
that an nss server includes in its tls certificaterequest message. if this function is not used, nss will include the distinguished names for all trust anchors installed in the database. this can be a lengthy list. previous versions of nss leaked the memory used to store distinguished names when ssl_settrustanchors() was used. this release fixes that error. bugs fixed in nss 3.27.2 the following bug has been fixed in nss 3.27.2: bug 1318561 - ssl_settrustanchors leaks compatibility nss 3.27.2 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.27.2 shared libraries without recompiling or relinking. furthermore, applications that restrict their use of nss apis to the functions lis...
NSS 3.28.4 release notes
distribution information the hg tag is nss_3_28_4_rtm. nss 3.28.4 requires nspr 4.13.1 or newer. nss 3.28.4 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_4_rtm/src/ new in nss 3.28.4 no new functionality is introduced in this release. ...
NSS 3.28 release notes
nts a key exporter based on the tls 1.3 early exporter secret. this api is equivalent in function to ssl_exportkeyingmaterial, but it can only succeed if 0-rtt was attempted (on the client) or accepted (on the server). ssl_sendadditionalkeyshares configures a tls 1.3 client so that it generates additional key shares when sending a clienthello. ssl_signatureschemeprefset allows an application to set which signature schemes should be supported in tls and to specify the preference order of those schemes. ssl_signatureschemeprefget allows an application to learn the currently supported and enabled signature schemes for a socket. request to test and prepare for tls 1.3 this release contains improved support for tls 1.3, however, the code that suppor...
NSS 3.29.2 release notes
distribution information the hg tag is nss_3_29_2_rtm. nss 3.29.2 requires netscape portable runtime (nspr) 4.13.1 or newer. nss 3.29.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_29_2_rtm/src/ new in nss 3.29.2 new functionality no new functionality is introduced in this release. ...
NSS 3.29.3 release notes
distribution information the hg tag is nss_3_29_3_rtm. nss 3.29.3 requires nspr 4.13.1 or newer. nss 3.29.3 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_3_rtm/src/ new in nss 3.29.3 no new functionality is introduced in this release. ...
NSS 3.29.5 release notes
distribution information the hg tag is nss_3_29_5_rtm. nss 3.29.5 requires nspr 4.13.1 or newer. nss 3.29.5 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_5_rtm/src/ new in nss 3.29.5 no new functionality is introduced in this release. ...
NSS 3.30.1 release notes
distribution information the hg tag is nss_3_30_1_rtm. nss 3.30.1 requires nspr 4.14 or newer. nss 3.30.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_30_1_rtm/src/ new in nss 3.30.1 no new functionality is introduced in this release. ...
NSS 3.30 release notes
that need to distinguish them from other other root cas, may use the exported function pk11_hasattributeset. support for callback functions that can be used to monitor ssl/tls alerts that are sent or received. new functions in cert.h cert_compareava - performs a comparison of two certava structures, and returns a seccomparison result. in pk11pub.h pk11_hasattributeset - allows to check if a pkcs#11 object in a given slot has a specific boolean attribute set. in ssl.h ssl_alertreceivedcallback - register a callback function, that will be called whenever an ssl/tls alert is received ssl_alertsentcallback - register a callback function, that will be called whenever an ssl/tls alert is sent ssl_setsessionticketkeypair - configures an asymmetric key pair,...
NSS 3.34.1 release notes
3.34.1, which is a minor release. 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. sha-256 fingerprint: d8:e0:fe:bc:1d:b2:e3:8d:00:94:0f:37:d2:7d:41:34:4d:99:3e:73:4b:99:d5:65:6d:97:78:d4:d8:14:36:24 removed entries from certdata.txt for actively distrusted certificates that ...
NSS 3.36.5 release notes
distribution information the hg tag is nss_3_36_5_rtm. nss 3.36.5 requires nspr 4.19 or newer. nss 3.36.5 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_5_rtm/src/ new in nss 3.36.5 new functionality no new functionality is introduced in this release. ...
NSS 3.36.6 release notes
distribution information the hg tag is nss_3_36_6_rtm. nss 3.36.6 requires nspr 4.19 or newer. nss 3.36.6 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_6_rtm/src/ new in nss 3.36.6 new functionality no new functionality is introduced in this release. ...
NSS 3.36.7 release notes
it was released on 19 january 2019. distribution information the hg tag is nss_3_36_7_rtm. nss 3.36.7 requires nspr 4.19 or newer. nss 3.36.7 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_7_rtm/src/ other releases are available in nss releases. ...
NSS 3.36.8 release notes
it was released on 21 june 2019. distribution information the hg tag is nss_3_36_8_rtm. nss 3.36.8 requires nspr 4.19 or newer. nss 3.36.8 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_8_rtm/src/ other releases are available in nss releases. new in nss 3.36.8 new functionality no new functionality is introduced in this release. ...
NSS 3.40 release notes
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. this is a c++ library for building certification paths. mozilla::pkix apis are not exposed in the libraries nss builds. it is easier to build nss on windows in mozilla-build environments. ...
NSS 3.41.1 release notes
it was released on 22 january 2019. distribution information the hg tag is nss_3_41_1_rtm. nss 3.41.1 requires nspr 4.20 or newer. nss 3.41.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_41_1_rtm/src/ other releases are available in nss releases. new in nss 3.41.1 new functionality no new functionality is introduced in this release. ...
NSS 3.44.1 release notes
it was released on 21 june 2019. the nss team would like to recognize first-time contributors: greg rubin distribution information the hg tag is nss_3_44_1_rtm. nss 3.44.1 requires nspr 4.21 or newer. nss 3.44.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_44_1_rtm/src/ other releases are available in nss releases. ...
NSS 3.44.2 release notes
it was released on 2 october 2019. distribution information the hg tag is nss_3_44_2_rtm. nss 3.44.2 requires nspr 4.21 or newer. nss 3.44.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_44_2_rtm/src/ other releases are available in nss releases. new in nss 3.44.2 no new functionality is introduced in this release. ...
NSS 3.44.3 release notes
it was released on 19 november 2019. the nss team would like to recognize first-time contributors: craig disselkoen distribution information the hg tag is nss_3_44_3_rtm. nss 3.44.3 requires nspr 4.21 or newer. nss 3.44.3 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_3_rtm/src/ other releases are available in nss releases. ...
NSS 3.46.1 release notes
it was released on 2 october 2019. distribution information the hg tag is nss_3_46_1_rtm. nss 3.46.1 requires nspr 4.22 or newer. nss 3.46.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_46_1_rtm/src/ other releases are available in nss releases. new in nss 3.46.1 no new functionality is introduced in this release. ...
NSS 3.46 release notes
lla.org/security/nss/releases/nss_3_46_rtm/src/ other releases are available in nss releases. new in nss 3.46 this release contains no significant new functionality, but concentrates on providing improved performance, stability, and security. of particular note are significant improvements to aes-gcm performance on arm. ...
NSS 3.47.1 release notes
it was released on 19 november 2019. the nss team would like to recognize first-time contributors: craig disselkoen distribution information the hg tag is nss_3_47_1_rtm. nss 3.47.1 requires nspr 4.23 or newer. nss 3.47.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_47_1_rtm/src/ other releases are available in nss releases. ...
NSS 3.48.1 release notes
it was released on 13 january 2020. distribution information the hg tag is nss_3_48_1_rtm. nss 3.48.1 requires nspr 4.23 or newer. nss 3.48.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_48_1_rtm/src/ other releases are available in nss releases. new in nss 3.48.1 no new functionality is introduced in this release. ...
NSS 3.49.1 release notes
it was released on 13 january 2020. distribution information the hg tag is nss_3_49_1_rtm. nss 3.49.1 requires nspr 4.24 or newer. nss 3.49.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_49_1_rtm/src/ other releases are available in nss releases. new in nss 3.49.1 no new functionality is introduced in this release. ...
NSS 3.49.2 release notes
it was released on 23 january 2020. distribution information the hg tag is nss_3_49_2_rtm. nss 3.49.2 requires nspr 4.24 or newer. nss 3.49.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_49_2_rtm/src/ other releases are available in nss releases. new in nss 3.49.2 no new functionality is introduced in this release. ...
NSS 3.49 release notes
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. see bug 1594933 for details. bugs fixed in nss 3.49 bug 1513586 - set downgrade sentinel for client tls versions lower than 1.2. bug 1606025 - remove -wmaybe-uninitialized warning in sslsnce.c bug 1606119 - fix ppc hw crypto build failure bug 1605545 - memory leak in pk11install_platform_generate bug 1602288 - fix build failure due to missing posix signal.h bug 1588714 - implement checkarmsupport for win64/aarch64 bug 1585189 - nss database uses 3des instead of aes to encrypt db entries bug 1603257 - fix...
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 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...
NSS Sample Code Utilities_1
nss sample code common: utilities this is a library of utilities used by many of the samples. this code shows the following: extract seed from noise file read der encoding from a file extract the password from a text file get the module password print as ascii or hexadecimal sample code #include <prlog.h> #include <termios.h> #include <base64.h> #include <unistd.h> #include <sys/stat.h> #include <prprf.h> #include "util.h" /* * these utility functions are adapted from those found in * the sectool library used by the nss security tools and * other nss test applications. */ /* * newline */ static void newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* * printasascii */ void printasascii(prfiledesc* out, const unsigned char *data, unsigned int len) { c...
Hashing - sample 1
/* this source code form is subject to the terms of the mozilla public * license, v. 2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
Initialize NSS database - sample 2
nss sample code 2: initialize the nss database. the nss sample code below demonstrates how to initialize the nss database. /* * print a usage message and exit */ static void usage(const char *progname) { fprintf(stderr, "\nusage: %s -d [-p ]" " [-f ]\n\n", progname); fprintf(stderr, "%-15s specify a db directory path\n\n", "-d "); fprintf(stderr, "%-15s specify a plaintext password\n\n", "-p "); fprintf(stderr, "%-15s specify a password file\n\n", "-f "); exit(-1); } /* * initslotpassword */ char * initslotpassword(pk11slotinfo *slot, prbool retry, void *arg) { file *input; file *output; char *p0 = null; char *p1 = null; ...
Utilities for nss samples
compile file size. get seed from a noise gile. generate random numbers. get a module password. extract the password from a text file. print data as hexadecimal. util.h /* this source code form is subject to the terms of the mozilla public * license, v. 2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
NSS release notes template
distribution information the hg tag is nss_3_xx_rtm. nss 3.xx requires nspr 4.xx or newer. ...
PKCS 12 functions
ater sec_pkcs12decodervalidatebags mxr 3.2 and later sec_pkcs12decoderverify mxr 3.2 and later sec_pkcs12destroyexportcontext mxr 3.2 and later sec_pkcs12enablecipher mxr 3.2 and later sec_pkcs12encode mxr 3.2 and later sec_pkcs12isencryptionallowed mxr 3.2 and later sec_pkcs12setpreferredcipher mxr 3.2 and later ...
PKCS 7 functions
later sec_pkcs7includecertchain mxr 3.2 and later sec_pkcs7iscontentempty mxr 3.2 and later sec_pkcs7setcontent mxr 3.4 and later sec_pkcs7verifydetachedsignature mxr 3.4 and later sec_pkcs7verifysignature mxr 3.2 and later secmime_decryptionallowed mxr 3.4 and later ...
Build instructions
t and microsoft visual studio 2010. (the free edition works, and other versions like visual studio 2008 and visual studio 2012 may also work.) use start-shell-msvc2010.bat from mozillabuild to get a bash shell with the path already configured, and execute these instructions from within that bash shell. for rhel-5, you need to use the new assembler. you can install the new assembler as root as follows: yum install binutils220 you can then use the new assembler by adding /usr/libexec/binutils220 to the beginning of your build path. this can be done in sh or bash as follows: export path=/usr/libexec/binutils220:$path the following build instructions should work for all platforms (with some platform-specific changes as noted). build instructions for recent versions (mercurial) clone the ...
Installation guide
nspr: libnspr4.so libplds4.so libplc4.so nss: (note the use of * for libfreebl -- some platforms have multiple ones) libfreebl*3.so libfreebl*3.chk libsoftokn3.so libsoftokn3.chk libnss3.so libsmime3.so libssl3.so libnssckbi.so ...
Sample manual installation
the nss build system does not include a target to install header files and shared libraries in the system directories, so this needs to be done manually. after building nss with "gmake nss_build_all", the resulting build can be found in the nss source tree as follows: nss header files: mozilla/dist/public/nss nspr header files: mozilla/dist/<obj-dir>/include nspr/nss shared libs: mozilla/dist/<obj-dir>/lib nss binary executables: mozilla/dist/<obj-dir>/bin. where <obj-dir> would vary according to the type of build and the platform. for example, <obj-dir> for a debug build of nss on the x86 platform with a linux kernel version 2.6 with glibc would be: linux2.6_x86_glibc_pth_dbg.obj from these directories, you can copy the files to any system (or other) directory. if the destina...
FC_GetInfo
name fc_getinfo - return general information about the pkcs #11 library. syntax ck_rv fc_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. 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-...
FC_GetSessionInfo
pinfo [out] pointer to the ck_session_info structure to be returned. description fc_getsessioninfo obtains information about a session. a user may call fc_getsessioninfo without logging into the token (to assume the nss user role). if the nss cryptographic module is in the error state, fc_getsessioninfo returns ckr_device_error. otherwise, it fills in the ck_session_info structure with the following information: state: the state of the session, i.e., no role is assumed, the user role is assumed, or the crypto officer role is assumed flags: bit flags that define the type of session ckf_rw_session (0x00000002): true if the session is read/write; false if the session is read-only. ckf_serial_session (0x00000004): this flag is provided for backward compatibility and is always set to true...
FC_GetTokenInfo
a particular token in the system. syntax ck_rv fc_gettokeninfo(ck_slot_id slotid, ck_token_info_ptr pinfo); parameters fc_gettokeninfo 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'...
FC_InitPIN
lled when the pkcs #11 security officer (so) is logged into the token and the session is read/write, that is, the session must be in the "r/w so functions" state (cks_rw_so_functions). the role of the pkcs #11 so is to initialize a token and to initialize the normal user's pin. in the nss cryptographic module, one uses the empty string password ("") to log in as the pkcs #11 so. the module only allows the pkcs #11 so to log in if the normal user's pin has not yet been set or has been reset. return value fc_initpin() returns the following return codes. ckr_ok: normal user's pin initialization succeeded. ckr_session_handle_invalid: the session handle is invalid. ckr_user_not_logged_in: the session is not in the "r/w so functions" state. ckr_pin_invalid: the pin has an invalid utf-8 char...
FC_Login
es four parameters: hsession [in] a session handle usertype [in] the user type (cku_so or cku_user) ppin [in] a pointer that points to the user's pin ulpinlen [in] the length of the pin description fc_login() logs a user into a token. the security officer (cku_so) only logs in to initialize the normal user's pin. the so pin is the empty string. the nss cryptographic module doesn't allow the so to log in if the normal user's pin is already initialized. return value fc_login() returns the following return codes. ckr_ok: the user logged in successfully. ckr_device_error: the token is in the error state. ckr_host_memory: memory allocation failed. ckr_pin_incorrect: the pin is incorrect. ckr_pin_len_range: the pin is too long (ulpinlen is greater than 255). the function sh...
FC_OpenSession
flags [in] papplication notify [in] pointer to a notification callback function. not currently supported. phsession [out] pointer to a session handle. ...
NSC_Login
gin() takes four parameters: hsession [in] a session handle usertype [in] the user type (cku_so or cku_user) ppin [in] a pointer that points to the user's pin ulpinlen [in] the length of the pin description nsc_login() logs a user into a token. the security officer (cku_so) only logs in to initialize the normal user's pin. the so pin is the empty string. the nss cryptographic module doesn't allow the so to log in if the normal user's pin is already initialized. return value nsc_login() returns the following return codes. ckr_ok: the user logged in successfully. ckr_device_error: the token is in the error state. ckr_host_memory: memory allocation failed. ckr_pin_incorrect: the pin is incorrect. ckr_pin_len_range: the pin is too long (ulpinlen is greater than 255).the function shou...
NSPR functions
conds to printervaltime. pr_secondstointerval pr_millisecondstointerval nspr i/o layering nspr file descriptors can be layered, corresponding to the layers in the network stack. the ssl library in nss implements the ssl protocol as an nspr i/o layer, which sits on top of another nspr i/o layer that represents tcp. you can implement an nspr i/o layer that wraps your own tcp socket code. the following nspr functions allow you to create your own nspr i/o layer and manipulate it. pr_getuniqueidentity pr_createiolayerstub pr_getdefaultiomethods pr_getidentitieslayer pr_getlayersidentity pr_pushiolayer pr_popiolayer wrapping a native file descriptor if your current tcp socket code uses the standard bsd socket api, a lighter-weight method than creating your own nspr i/o layer is to simply impo...
NSS cryptographic module
nt nsc_getfunctionlist function returns pointers to the functions that implement the default mode of operation. to enable the fips mode of operation, use the function fc_getfunctionlist instead to get pointers to the functions that implement the fips mode of operation. the nss cryptographic module also exports the function nsc_moduledbfunc for managing the nss module database secmod.db. the following sections document the data types and functions. pkcs #11 data types pkcs #11 functions in the non-fips (default) mode of operation pkcs #11 functions in the fips mode of operation nsc_moduledbfunc ...
troubleshoot.html
ilding 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.exe, which should be distributed with the cygnus...
OLD SSL Reference
ence into the format described in the mdn style guide. if you are inclined to help with this migration, your help would be very much appreciated. upgraded documentation may be found in the current nss reference ssl reference newsgroup: mozilla.dev.tech.crypto writer: sean cotter manager: wan-teh chang chapter 1 overview of an ssl application ssl and related apis allow compliant applications to configure sockets for authenticated, tamper-proof, and encrypted communications. this chapter introduces some of the basic ssl functions. chapter 2, "getting started with ssl" illustrates their use in sample client and server applications. initialization initializing caches configuration communication functio...
SSL functions
the public functions listed here are used to configure sockets for communication via the ssl and tls protocols. in addition to the functions listed here, applications that support ssl use some of the certificate functions, crypto functions, and utility functions described below on this page. other sources of information: the nss_reference documents the functions most commonly used by applications to support ssl. the nss home page links to additional ssl documentation. if documentation is available for a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (dxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss ve...
NSS Tools
the links for each tool take you to the source code, documentation, plans, and related links for each tool. the links will become active when information is available. currently, you must download the nss 3.1 source and build it to create binary files for the nss tools. for information about downloading the nss source, see https://developer.mozilla.org/nss/building. ...
Utility functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
NSS Tools cmsutil
using cmsutil newsgroup: mozilla.dev.tech.crypto the cmsutil command-line utility uses the s/mime toolkit to perform basic operations, such as encryption and decryption, on cryptographic message syntax (cms) messages. syntax to run cmsutil, type the command cmsutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section. each command takes one option. each option may take zero or more arguments. to see a usage string, issue the command without options. options and arguments options specify an action. option arguments modify an action. the options and arguments for the cmsutil command are defined as follows: options -ddecode a message. -c encrypt a message. -e envelope a message. -o ...
NSS Tools dbck-tasks
the dbck tool should be able to update a databa ...
Pork
pork is a c++ parsing and rewriting tool chain. the core of pork is a c++ parser that provides exact character positions for the start and end of every ast node, as well as the set of macro expansions that contain any location. this information allows c++ to be automatically rewritten in a precise way. the inputs driving the rewriting would normally be provided by a program-analysis system outside of pork. (see dehydra, treehydra). pork has been tested mostly on linux, but in theory it should be possible to make it work on other systems. note: pork is not presently used at mozilla. please refer to the oink link below for a more up-to-date toolchain. pork is based on the elsa (and oink) tool chain, and the mcpp preprocessor. as of october 2009 oink incorporates the pork functionalit...
Rhino downloads archive
...
Rhino history
to produce a version of navigator written entirely in java and so it needed an implementation of javascript written in java. when netscape stopped work on "javagator," as it was called, somehow rhino escaped the axe (rumor had it that the executives "forgot" it existed). for a time, a couple of major companies (including sun) licensed rhino for use in their products and paid netscape to do so, allowing work on rhino to continue. now rhino is part of mozilla's open-source repository. originally, rhino compiled all javascript code to java bytecodes in generated classfiles. this produced the best performance (often beating the c implementation of javascript when run on a jit), but suffered from two faults. first, compilation time was long since generating java bytecodes and loading the generat...
Rhino optimization
nation of recursive functions. 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. 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 speculat...
Rhino requirements and limitations
requirements recent versions of rhino have only been tested with jdk 1.4 and greater. older versions support jdks as early as 1.1. to use the javaadapter feature or an optimization level of 0 or greater, rhino must be running under a security manager that allows the definition of class loaders. limitations liveconnect if a javaobject's field's name collides with that of a method, the value of that field is retrieved lazily, and can be counter-intuitively affected by later assignments: javaobj.fieldandmethod = 5; var field = javaobj.fieldandmethod; javaobj.fieldandmethod = 7; // now, field == 7 you can work around this by forcing the field value to be converted to a javascript type when you take its value: javaobj.fieldandmethod = 5; var field = javaobj.fieldandmethod + 0; // ...
The JavaScript Runtime
tecodes. the generated bytecodes in turn depend upon runtime support routines. each javascript script or function is compiled to a separate class. compilation of javascript source to class files is supported. it is possible to specify the class files as well as the packages to generate into. types and values there are six fundamental types in javascript. these types are implemented with the following java types and values: javascript fundamental type java type undefined a singleton object defined by context.getundefinedtype() null null boolean java.lang.boolean number java.lang.number, that is, any of java.lang.byte, java.lang.short, java.lang.integer, java.lang.float, or java.lang.double. not java.lang.long, since a double r...
Rhino serialization
l also be saved as markers upon serialization and resolved in the new scope upon deserialization. use the addexcludedname method of scriptableoutputstream to add new names. by default, scriptableoutputstream excludes all the names defined using context.initstandardobjects. if you are using rhino serialization in an environment where you always define, say, a constructor foo, you should add the following code before calling writeobject: out.addexcludedname("foo"); out.addexcludedname("foo.prototype"); this code will prevent foo and foo.prototype from being serialized and will cause references to foo or foo.prototype to be resolved to the objects in the new scope upon deserialization. exceptions will be thrown if foo or foo.prototype cannot be found the scopes used in either scriptableoutputst...
FOSS
ipt to c++ objects rust mozjs - rust bindings used by servo gnome gjs - javascript bindings to gnome (broadly, to any library using the gobject introspection mechanism) objective caml http://alain.frisch.fr/soft.html#spider - bindings to embed spidermonkey in ocaml applications perl http://jspl.msg.mx/ - bindings to cross-embed spidermonkey and perl. includes a js shell that allows you to use cpan modules from javascript. python http://pypi.python.org/pypi/python-spidermonkey wxwidgets gluescript (formerly wxjavascript) code generators jsapigen - generates bindings for embedding spidermonkey in c applications extensions http://code.google.com/p/jslibs/ - zlib, sqlite, nspr, ode, libpng, libjpeg, libffi, (...) libraries for spidermonkey http://w...
Future directions
n "ideal future state" for the engine. that means the code as it is today won't match this document, and that's ok. whenever practical, new code and changes should move code closer to the ideal future. and of course, the idea of the future is always evolving in time as things change and we learn more. concurrent and wasm gc we are working towards a concurrent collector. we would also like to allow webassembly to interact with gc-managed data. parallelism most machines that run spidermonkey have multiple cores, so parallelism is almost certainly part of our future. it will take some experimentation to build the right set of parallel facilities. during that experimentation, we must take care to apply parallelism with conceptual clarity and discipline. the api the spidermonkey api is c++.
JSAPI Cookbook
/* jsapi */ jsobject *string; jsobject *string_prototype; js::value val; // get the string constructor from the global object. if (!js_getproperty(cx, global, "string", &val)) return false; if (jsval_is_primitive(val)) return throwerror(cx, global, "string is not an object", __file__, __line__); stri...
JS::GetFirstArgumentAsTypeHint
typehint(jscontext* cx, callargs args, jstype *result); 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. fs callargs the arguments of the function call. behavior jstype * receives the result of conversion. see below. description js::getfirstargumentastypehint converts first argument of @@toprimitive method to jstype. if args.get(0) is one of the strings "string", "number", or "default", set *result to jstype_string, jstype_number, or jstype_void accordingly and return true. otherwise, return false with a typeerror pending. see also mxr id search for js::getfirstargumentastypehint bug 1054756 -...
JS::MutableHandle
scription const t &get() const returns *ptr. operator const t&() const t operator->() const t *address() returns ptr. void set(t v) sets the value of *ptr to v. description js::mutablehandle<t> is a non-const reference to js::rooted&lt;t&gt;. it is used in the same way as js::handle&lt;t&gt; and includes a |set(const t &v)| method to allow updating the value of the referenced js::rooted&lt;t&gt;. a js::mutablehandle<t> can be created from a js::rooted&lt;t&gt; by using |js::rooted<t>::operator&()|. if you want to add additional methods to js::mutablehandle for a specific specialization, define a js::mutablehandlebase<t> specialization containing them. there are typedefs available for the main types: namespace js { typedef mutabl...
JS::SetLargeAllocationFailureCallback
allback syntax typedef void (* js::largeallocationfailurecallback)(void *data); name type description data void * data parameter passed to js::setlargeallocationfailurecallback. added in spidermonkey 38 description if a large allocation fails when calling pod_{calloc,realloc}cangc, the js engine may call the large-allocation- failure callback, if set, to allow the embedding to flush caches, possibly perform shrinking gcs, etc. to make some room. the allocation will then be retried (and may still fail.) js::setlargeallocationfailurecallback sets a callback function for it. see also mxr id search for js::setlargeallocationfailurecallback mxr id search for js::largeallocationfailurecallback bug 936236 bug 987995 - added data parameter ...
JS::SetOutOfMemoryCallback
f void (* outofmemorycallback)(jscontext *cx, void *data); name type description data void * data parameter passed to js::setoutofmemorycallback. added in spidermonkey 38 description unlike the error reporter, which is only called if the exception for an oom bubbles up and is not caught, the js::outofmemorycallback is called immediately at the oom site to allow the embedding to capture the current state of heap allocation before anything is freed. if the large-allocation-failure callback is called at all (not all allocation sites call the large-allocation-failure callback on failure), it is called before the out-of-memory callback; the out-of-memory callback is only called if the allocation still fails after the large-allocation-failure callback has ret...
JSCheckAccessOp
als 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 when a script attempts to access an object property. the callback can deny the script access to the property. see also jsclass bug 957688 ...
JSConstDoubleSpec
constdoublespec; typedef jsconstscalarspec<int32_t> jsconstintegerspec; // added in spidermonkey 38 name type description val double or int32_t value for the double or integer. name const char * name to assign the double. flags uint8_t property attributes for the double. obsolete since jsapi 35 currently these can be 0 or more of the following values or'd: jsprop_enumerate: property is visible in for loops. jsprop_readonly: property is read-only. jsprop_permanent: property cannot be deleted. jsprop_exported: property can be exported outside its object. jsprop_index: property is actually an array element. if this field is 0, js_defineconstdoubles uses the default attributes jsprop_readonly | jsp...
JSConvertOp
t any type. however, the engine itself only requires support for jstype_string, jstype_number, and jstype_void, if js_convertvalue is not used. if you do not use the js_convertvalue method, you may omit support for other types. (support for the other types may eventually be removed.) the callback returns true to indicate success or false to indicate failure. jsclass hooks jsclass offers the following hook: the jsclass.convert callback implements the [[defaultvalue]] behavior for objects having that class. see also mxr id search for jsconvertop jsclass ...
JSEnumerateOp
cription jsenumerateop is called just before an object is enumerated (via a for...in statement, an array comprehension, or a call to js_enumerate). it should define any remaining lazy properties that should be enumerable but are not yet defined in obj. this hook does not implement iteration: once the properties are defined, the javascript engine can enumerate them. jsclass hooks jsclass offers following hook: the jsclass.enumerate hook is for classes that implement lazy properties using jsclass.resolve. see also mxr id search for jsenumerateop jsnewenumerateop jsclass ...
JSExnType
this article covers features introduced in spidermonkey 17 possible exception types. value prototype in javascript jsexn_none an unthrowable error. (lower bound) jsexn_err error jsexn_internalerr internalerror jsexn_evalerr evalerror jsexn_rangeerr rangeerror jsexn_referenceerr referenceerror jsexn_syntaxerr syntaxerror jsexn_typeerr typeerror jsexn_urierr urierror jsexn_limit (upper bound) description these types are part of a jserrorformatstring structure. they define which error to throw in case of a runtime error. jsexn_none marks an unthrowable error. see also mxr id search for jsexntype jserrorformatstring bug 684526 ...
JSExtendedClass.wrappedObject
...
JSFastNative
eginrequest()). argc unsigned int the number of arguments supplied to the function by the caller (as opposed to, say, the number of arguments the function is specified to take in its jsfunctionspec). vp jsval * the arguments, including the this argument, the return-value slot, and the callee function object are accessible through this pointer using macros described below. description the callback should use the following macros to access the fields of vp: macro name description js_callee(cx, vp) returns the function object that was called, as a jsval. native methods must not call js_callee after calling js_set_rval. (the return value and the callee are stored in the same stack slot.) js_this(cx, vp) returns t...
JSFinalizeOp
t by the application, file handles, etc.) finalizers must never store a reference to obj. warning: this hook is called during garbage collection. any jsapi call that would allocate memory from the gc heap will fail if called from a finalizer. for other ways to interact with garbage collection (e.g. implementing weak references), see js_setgccallback. jsclass hooks jsclass offers the following hook: the jsclass.finalize callback is a hook for destructor code. the garbage collector calls the finalize hook of each jsobject it collects. see also mxr id search for jsfinalizeop jsclass js_setgccallback ...
JSHasInstanceOp
e the value whose type is being checked. bp bool * out parameter. on success, the callback stores the result of the type check in *bp. description jshasinstanceop is called to check whether v is an instance of obj. return false on error or exception, true on success with true in *bp if v is an instance of obj, false in *bp otherwise. jsclass hooks jsclass offers the following hook: the jsclass.hasinstance callback implements js_hasinstance and the javascript instanceof keyword. see also mxr id search for jshasinstanceop jsclass js_hasinstance ...
JSMarkOp
ng. obj jsobject * the object to be marked. arg void * opaque data which the mark hook must pass through to js_markgcthing. description call js_markgcthing for each gc thing directly reachable from obj. use jsval_is_gcthing to check whether a value needs to be marked and jsval_to_gcthing to convert the jsval to a pointer. jsclass hooks jsclass offers the following hook: the javascript engine calls the jsclass.mark callback during the mark phase of garbage collection. see also jsclass bug 638291 ...
JSNewEnumerateOp
description cx jscontext * the context in which the enumeration is taking place. obj js::handleobject the object to be enumerated. properties js::autoidvector &amp; out parameter. id array to populate with all property keys. enum_op jsiterateop obsolete since jsapi 37 specifies which step in iteration is happening. see the description below. statep js::mutablehandleid obsolete since jsapi 37 in/out parameter. the meaning depends on enum_op. see the description below. idp js::mutablehandleid obsolete since jsapi 37 in/out parameter. the meaning depends on enum_op. see the description below. description from spidermonkey 38, jsnewenumerateop is the type of objectops::enumerate. this callback overr...
JSNewResolveOp
ll *objp to signify "not resolved". with only jsclass_new_resolve and no jsclass_new_resolve_gets_start, the hook can assume *objp is null on entry. this is not good practice, but enough existing hook implementations count on it that we can't break compatibility by passing the starting object in *objp without a new jsclass flag. flags the flags argument is the logical or of zero or more of the following flags. the flags describe what kind of property access triggered the resolve callback. (the same flags are used in js_lookuppropertywithflags.) jsresolve_qualified obsolete since jsapi 20 the property access uses the . or [] operator: obj.id or obj[id], not id. jsresolve_assigning obsolete since jsapi 31 the property appears on the left-hand side of an assignment. jsresolv...
JSObject
see js_getprototype. an object inherits properties, including methods, from its prototype (which is another object). most objects have a parent. see js_getparent. an object's parent is another object, usually either the global object or an object that represents an activation record. the javascript engine sometimes uses this relationship to implement lexical scoping. security-sensitive applications can use this relationship to make every object a member of some security domain. almost every object can have any number of its own properties. ...
JSObjectOps.dropProperty
o jsobjectops.lookupproperty that found a property. obj jsobject * the object of which prop is an own property. that is, the value that the jsobjectops.lookupproperty hook stored in the *objp out parameter. prop jsproperty * the property to release. that is, the value that jsobjectops.lookupproperty hook stored in the *propp out parameter. description the following contract governs jsobjectops callers and implementations: whenever jsobjectops.lookupproperty returns a jsproperty pointer, the property is locked. while the property is locked, the caller may access it using other jsobjectops callbacks. it may not otherwise call into the jsapi in ways that might trigger other property accesses. (in a js_threadsafe build, that would risk deadlock.) when f...
JSObjectOps.getAttributes
he property access is happening. obj jsobject * the object whose property attributes are being accessed. id jsid the name or index of the property whose attributes are being accessed. prop jsproperty * the property whose attributes are being accessed. this may be null. attrsp unsigned int * in/out parameter. see the description section below. description get or set attributes of the property obj[id]. returns js_false on error or exception, else js_true with current attributes in *attrsp. if prop is non-null, it must come from the *propp out parameter of a prior jsobjectops.defineproperty or jsobjectops.lookupproperty call. for more information on property attributes, see js_getpropertyattributes. ...
JSObjectOps.getRequiredSlot
dslotop)(jscontext *cx, jsobject *obj, uint32 slot); typedef jsbool (*jssetrequiredslotop)(jscontext *cx, jsobject *obj, uint32 slot, jsval v); name type description cx jscontext * the js context in which we access the slot. obj jsobject * the object whose slot we access. slot uint32 the index of the slot to access. see note below. v jsval the value to store in the slot, for jssetrequiredslotop. description get and set a required slot, one that should already have been allocated. these operations are infallible, so required slots must be pre-allocated, or implementations must suppress out-of-memory errors. the native ops (js_objectops, see js/src/jsobj.cpp) access slots reserved by including a call t...
JSReserveSlotsOp
the new object. description warning: jsapi applications should not use this hook. a class cannot freely use a reserveslots hook to reserve a different number of slots for each object. rather, within a jsruntime, every call to the same reserveslots hook must return the same value (excepting a few internal classes such as function, call, and block). jsclass hooks jsclass offers the following hook: the jsclass.reserveslots callback is called each time a new object is created. the optional jsclass.reserveslots hook allows a class to make computed per-instance object slots reservations, in addition to or instead of using jsclass_has_reserved_slots(n) in the jsclass.flags initializer to reserve a constant-per-class number of slots. implementations of this hook should return t...
JSResolveOp
rn true if the object has no lazy property with the given id; or return false to indicate any other error. obsolete since jsapi 36 the callback must return true if the property is resolved, or if the object has no lazy property with the given id; or false to indicate any other error. note: jsnewresolveop provides a cheaper way to resolve lazy properties. jsclass hooks jsclass offers the following hook: jsclass.resolve callback is called when a property is not found on an object. it can be used to implement lazy properties. js looks for a property in an object, and if not found, tries to resolve the given id. after calling resolve, the engine looks again to see if resolve defined obj[id]. if so, the property lookup succeeds. if not, the process is repeated with obj's prototype. ...
JSRuntime
te context for each html page; every script in the page could use the same context. objects may be shared among jscontexts within a jsruntime. there's no fixed association between an object and the context in which it is created. sample code to set up and tear down a jsruntime and a jscontext is at jsapi user guide. threads only one thread may use a jscontext or jsruntime. earlier versions allowed using js_clearcontextthread and other functions to move a jscontext from one thread to another. this feature has since been removed. see also js_newruntime js_destroyruntime js_newcontext js_destroycontext ...
JSTraceOp
ange state of the object or corresponding native structures. the only exception for this rule is the case when the embedding needs a tight integration with gc. in that case the embedding can check if the traversal is a part of the marking phase through calling js_isgcmarkingtracer and apply a special code like emptying caches or marking its native structures. jsclass hooks jsclass offers the following hook: the jsclass.trace callback is called to enumerate all traceable things reachable. see also mxr id search for jstraceop jsclass ...
JSVAL_IS_DOUBLE
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 number represented as a jsdouble. 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. example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js double data type. if (jsval_is_double(myitem)) { . . . } see also bug 952650 ...
JSVAL_IS_INT
t number represented in memory as an integer. 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. example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js integer data type. if (jsval_is_int(myitem)) { . . . } see also bug 952650 ...
JSVAL_IS_NULL
determine if a given 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)) { ... } see also bug 952650 ...
JSVAL_IS_NUMBER
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 a javascript 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. example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js integer or double value. if (jsval_is_number(myitem)) { ... } see also bug 952650 ...
JSVAL_IS_STRING
s 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 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. example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a string. if (jsval_is_string(myitem)) { ... } see also bug 952650 ...
JSVAL_IS_VOID
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 the javascript value undefined. syntax jsval_is_void(v) description jsval_is_void(v) is true if v is jsval_void, which represents the javascript value undefined. example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is void. if (jsval_is_void(myitem)) { ... } see also bug 952650 ...
JSVersion
each version has a name, which is a string used by js_stringtoversion and js_versiontostring. ...
JSXDRObjectOp
see also jsclass bug 726944 ...
JS_AddArgumentFormatter
e type description cx jscontext * the context in which to install the formatter. format const char * the format string prefix that should be handled by formatter, or whose handler should be removed. formatter jsargumentformatter the function to be used to convert arguments described by the given format. this function is described in more detail below. description js_addargumentformatter establishes formatter as the conversion function for format strings beginning with format in the context cx. on success, it returns js_true. otherwise it returns js_false. (at the moment, js_addargumentformatter fails only if there is no memory available to record the registration.) js_addargumentformatter does not copy format, it points at the string st...
JS_AddExternalStringFinalizer
his 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. register a custom string memory manager. syntax int js_addexternalstringfinalizer(jsstringfinalizeop finalizer); name type description finalizer jsstringfinalizeop pointer to a callback function, described below. the js engine will automatically call this function each time a string created by js_newexternalstring is garbage-collected. callback syntax typedef void (*jsstringfinalizeop)(jscontext *cx, jsstring *str); name type description cx jscontext * pointer to a jscontext which the finalizer may use for certain very limited operations (not documented). since the...
JS_Add*Root
n, the address of a local (stack-based) variable may not be used for rp. if js_add*root succeeds, then as long as this variable points to a javascript value or pointer to gc-thing, that value/gc-thing is protected from garbage collection. if the variable points to an object, then any memory reachable from its properties is automatically protected from garbage collection, too. js_addgcthingroot allows the caller to have a single root that may hold either strings or objects. a jsval is not a gc-thing (it has tag bits and may be a different size altogether) and thus the address of a jsval variable must not be passed to js_addgcthingroot. do not pass a pointer to a js string or object to any of these functions—rp must point to a variable, the location of the pointer itself, and not an object...
JS_CallFunction
e information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the "current" object on which the function operates; the object specified here is "this" when the function executes. fun js::handlefunction pointer to the function to call. fun should be a native function or jsapi-compiled function. see below. name const char * pointer to the name of function to call. fval js::handlevalue pointer to the function value to call. args const js::handlevaluearray &amp; reference to the array of argument values to pass to the function. added in spidermonkey 31 argc unsigned number of arguments you are passing to the function. obsolete since jsapi 3...
JS_ClearNewbornRoots
for all contexts. see js_enterlocalrootscope for a better way to manage newborns in cases where native hooks (functions, getters, setters, etc.) create many gc-things, potentially without connecting them to predefined local roots such as *rval or argv[i] in an active jsnative function. using js_enterlocalrootscope disables updating of the context's per-gc-thing-type newborn roots, until control flow unwinds and leaves the outermost nesting local root scope. see also bug 572057 bug 659462 ...
JS_ClearPendingException
e caller must be in a request on this jscontext. description js_clearpendingexception cancels the currently pending exception in cx, if any. (there is a pending exception if the most recently thrown exception in cx has not yet been caught or cleared.) when any jsapi call fails with an exception, the caller must either use js_clearpendingexception to catch the exception; or return false to allow the exception to propagate to the caller. note that a jsapi failure does not necessarily indicate that an exception is pending. many jsapi functions can simply report an error and return false without building and throwing an exception object. use js_isexceptionpending or js_getpendingexception to check for a pending exception. see examples in the jsapi phrasebook. see also mxr id search for j...
JS_ContextIterator
text in the cycle. iterp must point to a variable of type jscontext *. if *iterp is null, js_contextiterator modifies it to point to the first jscontext in the list. ...
JS_ConvertArguments
tiple 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. ...
JS_DefineFunctions
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 regardless of their flags. onlydefinelateproperties define only properties which have a jsprop_define_late flag. dontdefinelateproperties ...
JS_DefineProperty
id for the property name. js_defineproperty is the fundamental operation on which several more convenient, higher-level functions are based, including js_definefunction, js_definefunctions, js_defineproperties, js_defineconstdoubles, js_defineobject, and js_initclass. it differs from js_setproperty in that: it does not behave like ordinary property assignment in the javascript language; it allows the application to specify additional details (getter, setter, and attrs) governing the new property's behavior; it never calls a setter; it can call the jsclass.addproperty callback when js_setproperty would not, because it can replace an existing property. the parameters specify the new property's name, initial stored value, getter, setter, and property attributes (attrs). if obj already ...
JS_DeleteProperty
meter) 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 parameter. first, a property lookup is performed. then one of the following cases applies: if obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then obj's jsclass.delproperty hook is called. no property is deleted, but this is not an error. if obj has the specified property but it is permanent, nothing happens. no property is deleted, but this is not an error. otherwise obj has a non-permanent own propert...
JS_DeleteProperty2
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 version of the function. js_deletepropertybyid2 is the same but takes a js::handleid for the property name. first, a property lookup is performed. then one of the following cases applies: if obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then *succeeded is set to true and obj's jsclass.delproperty hook is called (which may change *succeeded). no property is deleted, but this is not an error. if obj has the specified property but it is permanent, then *succeeded receives false. no property is delete...
JS_DumpHeap
strace_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 indicates the real kind should be looked up in the arena. jstrace_outofline = 0x07, // the following kinds do not have an exposed c++ idiom. jstrace_base_shape = 0x0f, jstrace_jitcode = 0x1f, jstrace_lazy_script = 0x2f, jstrace_type_object = 0x3f, jstrace_last = jstrace_type_object }; description see bug 378261 for detail. when tracing a thing, the gc needs to know about the layout of the object it is looking at. there are a fixed number of different layouts that the ...
JS_EnterLocalRootScope
s use is discouraged since it could be removed at any time. try to avoid using it. enter a local root scope. syntax jsbool js_enterlocalrootscope(jscontext *cx); name type description cx jscontext * pointer to the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description scoped local root management allows native functions, getter/setters, etc. to avoid calling js_addroot and js_removeroot to manage global roots temporarily. js_addroot roots a variable, ensuring that whatever the variable points to at any given moment is protected from gc. by contrast, local root scopes protect newly-created objects, doubles, and strings. there is no need to tell the js engine about each variable that may point to...
JS_ExecuteScript
is should just be the embedding's global object. obsolete since jsapi 39 obj must not be an array, an e4x xml object, a with object, or a proxy. in ecmascript terms, the script is executed in a new execution context, but that context is not initialized quite as described in any of the three cases in ecma 262-3 §10.2. instead: the scope chain is initialized to contain obj, followed by its parent, then its parent's parent, etc. until null is reached. variable initialization is performed. if the jsoption_varobjfix option is in effect (recommended), then the last object in the scope chain is used as the variable object. otherwise obj is used. the this value is obj. scopechain js::autoobjectvector &amp; an explicit scope chain. scopechain mus...
JS_ExecuteScriptVersion
n the simplest cases, this should just be the embedding's global object. obj must not be an array, an e4x xml object, a with object, or a proxy. in ecmascript terms, the script is executed in a new execution context, but that context is not initialized quite as described in any of the three cases in ecma 262-3 §10.2. instead: the scope chain is initialized to contain obj, followed by its parent, then its parent's parent, etc. until null is reached. variable initialization is performed. if the jsoption_varobjfix option is in effect (recommended), then the last object in the scope chain is used as the variable object. otherwise obj is used. the this value is obj. script jsobject * the compiled script to execute. rval jsval * ...
JS_FS
gs uint16 the bitwise or of any number of function flags. selfhostedname const char * the function's name in self-hosted javascript code. description use these macros to define an array of jsfunctionspecs to pass to js_definefunctions or js_initclass. js_fn (whose name pays homage to the old jsnative/jsfastnative split) simply adds the flag jsfun_stub_gsops. js_fninfo allows the simple adding of jsjitinfos. js_self_hosted_fn declares a self-hosted function. finally js_fnspec has slots for all the fields. the _sym variants allow defining a function with a symbol key rather than a string key. for example, use js_sym_fn(iterator, ...) to define an @@iterator method. (in builds without es6 symbols, it defines a method with the string id "@@iterator".) see an example in ...
JS_GetFunctionFlags
cription 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. jsfun_generic_native the function is an array generic, such as array.map. jsfun_heavyweight the function uses language features such as closures, with, or eval that require extra work on the part of the interpreter. jsfun_lambda the function is a javascript function written as a functionexpression rather than a functiond...
JS_GetFunctionObject
description js_getfunctionobject returns the javascript function object for a specified function pointer, fun. ...
JS_GetGlobalObject
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 global object, where it is automatically protected from garbage collection and the application can ...
JS_GetInstancePrivate
obj js::handle&lt;jsobject*&gt; the object for which to retrieve private data. clasp jsclass * class against which to test the object. args js::callargs * optional argument, used for error reporting. added in spidermonkey 32 argv 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 priv...
JS_GetParent
the initial parent of an object created via the jsapi depends on the particular jsapi function (of which there are many that create objects, including but not limited to js_newobject, js_constructobject, js_defineobject, js_valuetoobject, js_newarrayobject, js_newscriptobject, js_newfunction, js_compilefunction, js_definefunction, js_definefunctions, and js_initclass). some of these functions allow the application to specify a parent object. if the jsapi function creating the object has a parent parameter, and the application passes a non-null value to it, then that object becomes the new object's parent. otherwise, if the context is running any scripts or functions, a default parent object is selected based on those. otherwise, if the context has a global object, it is used. otherwise the ...
JS_GetProperty
h the specified name. it behaves like the javascript expression obj[name]. js_getucproperty is the unicode version of the function. js_getpropertybyid is the same but takes a js::handleid for the property name. in the simplest case, js_getproperty stores the value of the property in *vp and returns true. however, several different hooks can affect property gets. the full algorithm is described below. details first, a property lookup is performed. if the lookup proceeds without error, exactly one of the following cases applies: if the property is not found, then *vp is set to undefined. then the jsclass.getproperty hook of obj's class is called with the arguments (cx, obj, id, vp). for many objects, including objects of standard classes such as object and array, this hook does nothing an...
JS_GetReservedSlot
has a non-null jsclass.reserveslots callback, then objects of that class have n reserved slots in which the application may store data. these fields are not directly exposed to scripts. reserved slots may contain any js::value, and the garbage collector will hold the value alive as long as the object itself is alive. reserved slots may also contain private values to store pointer values (whose lowest bit is 0) or uint32_t, when non-javascript values must be stored; the garbage collector ignores such values when it sees them. (note that private values must not be exposed directly to javascript. it's only legal to store and retrieve data from private values. they cannot be returned from functions, set as properties on objects, embedded in javascript arrays, and so on.) new objects' reserved...
JS_GetTypeName
stype type); name type description cx jscontext * pointer to a js context from which to derive runtime information. type jstype one of jstype_void, jstype_object, jstype_function, jstype_string, jstype_number, or jstype_boolean. description js_gettypename returns a pointer to a string literal description of a specified js data type, type. ...
JS_InstanceOf
nstanceof returns true if obj is of the given class and false otherwise. that is, it returns js_getclass(obj) == clasp. js_instanceof can also be used in native functions to check the class of an argument when a particular class is required. 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_getcl...
JS_IsConstructing_PossiblyWithGivenThisObject
est. 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 called from js_constructobject and js_initclass where the class has the jsclass_construct_prototype flag set, spidermonkey passes the constructor a non-standard this object. in such cases, the following example would provide the additional information of whether a special this was supplied. jsbool foo_native(jscontext *cx, unsigned int argc, jsval *vp) { jsobject *maybethis; if (js_isconstructing_possiblywithgiventhisobject(cx, vp, &maybethis)) { // native called as a constructor if (maybethis) // native called as a constructor with maybethis as 'this' } else { // nativ...
JS_IterateCompartments
void *data, jsiteratecompartmentcallback compartmentcallback); name type description cx jsruntime * the runtime of the compartments to iterate over. data void * this will be passed as the data parameter of the jsiteratecompartmentcallback. compartmentcallback jsiteratecompartmentcallback callback function (see below). callback function typedef void (*jsiteratecompartmentcallback)(jsruntime *rt, void *data, jscompartment *compartment); name type description cx jsruntime * the runtime of the compartments. data void * data parameter passed to js_iteratecompartments. compartmentcallback jscompartment * the pointer to the compartment. de...
JS_LockGCThing
text. rt jsruntime * a runtime. thing void * 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_NewExternalString
s the character buffer of the jsstring to be created. the array must be populated 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 strin...
JS_NewObject
1.8 name type description cx jscontext * the context in which to create the new object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. clasp const jsclass * pointer to the class to use for the new object. if this is null, an ordinary javascript object is created. the jsclass may be used to override low-level object behavior, including such details as the physical memory layout of the object and how property lookups are done. added in spidermonkey 1.8.1 clasp->flags must not have the jsclass_global_flags bits set (use js_newglobalobject instead). if clasp is non-null, the caller must ensure that the jsclass remains alive throughout the lifetime of the new object, including the garbage c...
JS_NewRegExpObject
s_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject a pointer to a global object. bytes or chars const char * or const char16_t * a pointer to the string that contains a regular expression. length size_t the length of bytes or chars, in characters. flags unsigned regular expression flags. see below. flags name description regexp constructor flag jsreg_fold fold uppercase to lowercase. i jsreg_glob global execution, creates array of matches. g jsreg_multiline treat ^ and $ as begin and end of line. m jsreg_sticky only match starting at lastindex. y description js_newregexpobject and js_newucregexpobjec...
JS_NewUCString
and returns a new string, using the memory starting at buf and ending at buf + length as the character storage. js_newucstring is the unicode version of the function. the character array, buf, must be allocated on the heap using js_malloc. on success, the javascript engine adopts responsibility for memory management of this region. the application must not read, write, or free the buffer. this allows the javascript engine to avoid needless data copying. on success, js_newstring and js_newucstring return a pointer to the new string. on error or exception, they return null. see also js_convertvalue js_getemptystringvalue js_getstringbytes js_getstringchars js_getstringlength js_internstring js_internucstring js_internucstringn js_newstringcopyn js_newstringcopyz js_newucstringcopyn...
JS_PreventExtensions
ble. obsolete since jsapi 39 description all javascript objects recognize the concept of extensibility: whether new properties may be added to the object. in some situations, it may be convenient to prohibit new properties. in javascript this may be accomplished using the object.preventextensions method. the similar jsapi method is js_preventextensions. the failure-mode information below is new as of spidermonkey 36. before then, js_preventextensions did not accept a succeeded argument; in those cases where *succeeded would be set to false, js_preventextensions would throw a typeerror and return false. unlike object.preventextensions, js_preventextensions doesn't necessarily throw a typeerror if the object couldn't be made non-extensible. there are instead two modes of failur...
JS_SameValue
this article covers features introduced in spidermonkey 1.8.1 determines if two jsvals are the same, as determined by the samevalue algorithm in ecmascript 262, 5th edition. samevalue slightly differs from strict equality (===) in that +0 and -0 are not the same and in that nan is the same as nan. ...
JS_SetCallReturnValue2
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. causes a native to return a reference value (as allowed by ecma 262-3 §11.2.3). syntax void js_setcallreturnvalue2(jscontext *cx, jsval v); name type description cx jscontext * the context in which the native function is running. v jsval the id of the property of the reference value to be returned from the native. descri...
JS_SetCompartmentNameCallback
n spidermonkey 17 set callback function to name each compartment. syntax void js_setcompartmentnamecallback(jsruntime *rt, jscompartmentnamecallback callback); name type description cx jsruntime * the runtime to set the callback function. callback jscompartmentnamecallback callback function which will be called to name each compartment (see below). callback function typedef void (* jscompartmentnamecallback)(jsruntime *rt, jscompartment *compartment, char *buf, size_t bufsize); name type description cx jsruntime * the runtime of the compartments. compartmentcallback jscompartment * the pointer to the compartment to be named. buf char * the ...
JS_SetContextCallback
specifies a callback function that is automatically called whenever a jscontext is created or destroyed. syntax void js_setcontextcallback(jsruntime *rt, jscontextcallback cxcallback, void *data); name type description rt jsruntime * pointer to a js runtime. cxcallback jscontextcallback pointer to the callback function, described below. data void * any data passed as 3rd argument to the callback function. added in spidermonkey 31 callback syntax typedef bool (* jscontextcallback)(jscontext *cx, unsigned contextop, void *data); name type description cx jscontext * pointer to a jscontext which the callback may use to call into jsapi functions. this is the context which was just created, or is ab...
JS_SetDestroyCompartmentCallback
ck function for each compartment being destroyed. syntax void js_setdestroycompartmentcallback(jsruntime *rt, jsdestroycompartmentcallback callback); name type description cx jsruntime * the runtime to set the callback function. callback jsdestroycompartmentcallback callback function which will be called for each compartment being destroyed (see below). callback function typedef void (* jsdestroycompartmentcallback)(jsfreeop *fop, jscompartment *compartment); name type description cx jsruntime * the runtime of the compartments. compartmentcallback jscompartment * the pointer to the compartment which is to be destroyed. description js_setdestroycompartmentcallback sets callback func...
JS_SetErrorReporter
on. syntax jserrorreporter js_geterrorreporter(jsruntime *rt); jserrorreporter js_seterrorreporter(jsruntime *rt, jserrorreporter er); name type description cx jsruntime * pointer to a js runtime whose errors should be reported via your function. er jserrorreporter the user-defined error reporting function to use in your application, described below. callback syntax typedef void (* jserrorreporter)(jscontext *cx, const char *message, jserrorreport *report); name type description cx jscontext * the context in which the error happened. message const char * an error message. report jserrorreport * an error report record containing additional details about the error. de...
JS_SetExtraGCRoots
data closure pointer, to be passed through to traceop. ...
JS_SetGCZeal
ite 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 a good practice. this function is available only in debug builds. to enable this function in an optimized build, define the macro js_gc_zeal building spidermonkey. (in a debug build of gecko, you can also set the current gc zeal level using the javascript.options.gczeal preference.) see also mxr id search for js_setgczeal ...
JS_SetInterruptCallback
t it should first use js_setinterruptcallback to set the context's interrupt callback to null. otherwise the engine may call the interrupt callback again, reentering it. provides request. in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx. the callback does not need to call js_beginrequest()). description these functions allow setting an interrupt callback that will be called from the js thread some time after any thread triggered the callback using js_requestinterruptcallback. to schedule the gc and for other activities the engine internally triggers interrupt callbacks. the embedding should thus not rely on callbacks being triggered through the external api only. important note: additional callbacks can occur insi...
JS_SetObjectPrincipalsFinder
ater, use js_setruntimesecuritycallbacks instead. syntax jsobjectprincipalsfinder js_setobjectprincipalsfinder(jsruntime *rt, jsobjectprincipalsfinder fop); name type description rt jsruntime * the runtime to configure. fop jsobjectprincipalsfinder the new object-principals-finder callback. description js_setobjectprincipalsfinder allows the application to set a callback that the javascript engine uses to obtain an object's principals. this callback is described in jsobjectprincipalsfinder. js_setobjectprincipalsfinder returns the previous object-principals-finder callback. mxr id search for js_setobjectprincipalsfinder ...
JS_SetOperationCallback
therwise the engine may call the operation callback again, reentering it. provides request. in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx. the callback does not need to call js_beginrequest()). applications must not use both the operation callback api and the older branch callback api. description these functions allow setting an operation callback that will be called from the js thread some time after any thread triggered the callback using js_triggeroperationcallback. to schedule the gc and for other activities the engine internally triggers operation callbacks. the embedding should thus not rely on callbacks being triggered through the external api only. important note: additional callbacks can occur insi...
JS_SetPropertyAttributes
oundp jsbool * out parameter. flag indicating whether or not the specified property was located. description js_setpropertyattributes sets the attributes for a specified property, name of an object obj. js_setucpropertyattributes is the unicode version of the function. attrs is an unsigned integer containing the attribute value to set. it is the bitwise or of zero or more of the following values: flag purpose jsprop_enumerate property is visible in for and in loops. jsprop_readonly property is read only. jsprop_permanent property cannot be deleted. jsprop_exported property can be imported by other objects. jsprop_index property is actually an index into an array of properties, and is cast to a const char *...
JS_SetThreadStackLimit
this is deprecated, use js_setnativestackquota instead. syntax 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. ...
JS_StringToVersion
returns a jsversion value representing the version string. syntax jsversion js_stringtoversion(const char *string); name type description string const char * version string to convert. description js_stringtoversion attempts to convert the version string to a jsversion value. ...
JS_TracerInit
ed by the function js_tracerinit initialize a jstracer for object graph tracing. syntax void js_tracerinit(jstracer *trc, jsruntime *rt, jstracecallback callback); name type description trc jstracer * the tracer to be initialized. cx jscontext * the context in which to perform tracing. callback jstracecallback a callback, described below, which the tracing apis will call each time a pointer is found from one gc thing to another. callback syntax typedef void (*jstracecallback)(jstracer *trc, void *thing, uint32 kind); name type description trc jstracer * the tracer visiting obj. thing void * a gc thing. kind uint32 one of the constants jstrace_object, jstrace_doubl...
JS_ValueToNumber
mber, conversion succeeds. if v is undefined, null, false, or true, conversion succeeds, and the result is nan, 0, 0, or 1 respectively. if v is a string, conversion proceeds as specified in ecma 262-3 §9.3.1. js_valuetonumber always succeeds in this case, returning js_true. if the string is not a numeric string, *dp is set to nan. otherwise v is an object. js_valuetonumber carries out the following steps to convert it to a number. if at any step an error or exception occurs, or conversion succeeds, the rest of the steps are skipped. (this behavior is implemented by v's jsobjectops.defaultvalue hook, so host objects can override it all.) first, the object's jsclass.convert callback is called. for objects of standard classes, this is js_convertstub, which simply calls v.valueof() if ...
JS_ValueToString
g "true", "false", "null", or "undefined", accordingly. if v is a number, conversion succeeds, and the result is a string representation of that number as specified in ecma 262-3 §9.8.1. this might be "nan", "infinity", or "-infinity". otherwise the result is a decimal representation of the number, possibly using exponential notation. otherwise v is an object. js_valuetostring uses the steps below to convert it to a string. if at any point an error or exception occurs, or conversion succeeds, the rest of the steps are skipped. (this behavior is implemented by v's jsobjectops.defaultvalue method, so host objects can override it all.) if v.tostring() is a function, it is called. if that method returns a primitive value, the value is converted to a string as described above and conversi...
JS_VersionToString
returns a string representation of a jsversion value. syntax const char * js_versiontostring(jsversion version); name type description version jsversion version value to convert. description js_versiontostring attempts to convert the version to a const char * string representation. ...
Stored value
he same thing as the property's current value. the javascript engine sets aside a field of type jsval for the stored value of most object properties, even properties that have getters. the stored value is updated each time the program gets or sets the property. the new stored value is the result of getting or setting the property, after the getter or setter, if any, is called. js_defineproperty allows the application to specify a property's initial stored value. js_lookupproperty fetches a property's stored value without triggering its getter. properties with the jsprop_shared attribute do not have a stored value. es5 accessor properties, as in {get length() { return 0; }, automatically have jsprop_shared. properties of objects that have custom jsobjectops do not have a stored value. stored v...
jsint
typedef ... ...
JSDBGAPI
js_connectshark js_disconnectshark js_startshark js_stopshark ...
Profiling SpiderMonkey
ilable. see the documentation on the --enable-jprof mozconfig option. we're working to add support for other profilers, such as oprofile, intel vtune, and callgrind. when we have js scriptable profiling options available for all tier 1 platforms, we'll look at adding global start/stop profiling functions. if you'd like to profile something at a higher level of detail than the js shark functions allow, there are corresponding c functions available at the bottom of jsdbgapi.h. costs of thread safety currently, threadsafe spidermonkey costs us 10-15% on some benchmarks vs. a non-threadsafe js shell. if you're looking to investigate that, build a standalone copy of spidermonkey and compare it with xpcshell. ...
SpiderMonkey 45
//ftp.mozilla.org/pub/spidermonkey/releases/45.0.2/mozjs-45.0.2.tar.bz2 sha256: 570530b1e551bf4a459d7cae875f33f99d5ef0c29ccc7742a1b6f588e5eadbee md5: 2ca34f998d8b5ea79d8616dd26b5fbab spidermonkey 45 is the javascript engine that shipped in firefox 45. it continues to improve performance over previous spidermonkey releases. it also contains new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. or file bugs at bugzilla.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. compilin...
SpiderMonkey 52
to the mozilla-esr52 repository and clicking on the first sm(pkg) link you see. that will open a small window in the bottom left with a line like "artifact uploaded:mozjs-52.x.y.tar.bz2". spidermonkey 52 is the javascript engine that shipped in firefox 52. it continues to improve performance over previous spidermonkey releases. it also contains new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. you may wish to make the bugs block bug 837921 (aliased as "sm.embedding"). platform support migrating to spidermonkey 52 new javascript language features new c++ apis deleted apis api ...
SavedFrame
ounger frames. savedframe stacks should generally be captured, allocated, and live within the compartment that is being observed or debugged. usually this is a content compartment. capturing savedframe stacks from c++ use js::capturecurrentstack declared in jsapi.h. from js use savestack, accessible via components.utils.getjstestingfunction(). including and excluding chrome frames consider the following savedframe stack. arrows represent links from child to parent frame, content.js is from a compartment with content principals, and chrome.js is from a compartment with chrome principals. function a from content.js | v function b from chrome.js | v function c from content.js the content compartment will ever have one view of this stack: a -> c. ho...
SpiderMonkey: The Mozilla JavaScript runtime
pidermonkey internals: gc separate internals article on the gc spidermonkey internals: hacking tips collection of helpful tips & tools for hacking on the engine related topics javascript foss projects using or based on spidermonkey releases spidermonkey release notes current and past versions: 52, 45, 38, 31, 24, 17 community mailing list spidermonkey questions on stack overflow report a bug ...
TPS Tab Lists
a tabs asset list is an array of objects with the following keys: uri: the uri of the tab, required. title: the title of the tab, optional. if specified, only used during verify actions. profile: the name of the profile the tab belongs to. required for verify actions. for example: var tabs1 = [ { uri: "http://hg.mozilla.org/automation/crossweave/raw-file/2d9aca9585b6/pages/page1.html", title: "crossweave test page 1", profile: "profile1" }, { uri: "data:text/html,<html><head><title>hello</title></head><body>hello</body></html>", title: "hello", profile: "profile1" } ]; tab lists and phase actions tabs cannot be modified or deleted, only added or verified with the following functions: tabs.add - opens the specified tabs in the browser window. tabs...
Zest runtimes
as zest is written in json it requires a runtime in order to be evaluated. the following runtimes are available: java https://github.com/mozilla/zest - this is the reference implementation the following runtimes are planned or an an early stage of implementation: https://github.com/mozilla/zest/tree/master/js javascript https://github.com/darkowlzz/zest-runner https://github.com/darkowlzz/zest-cli - this is the zest-cli of js based runner. python no code available yet if you are interested in working on an existing or new zest runtime then please get in touch via the zest group. related links zest overview ...
Zest usecase: Reporting Security Vulnerabilities to Developers
words, for example in a pdf or via a bug tracker. unfortunately in many cases developers may lack the security knowledge to understand or reproduce the problem. also security teams often use tools which the developers do not have access to or have no experience with. and developers sometime fail to solve the underlying problems. while it will still be necessary to describe vulnerabilities, zest allows security teams to create reproducible test cases which they can then share with the developers. these test cases can be used by the developers to reproduce the issues and test their fixes. ideally security engineers will be able to use their favourite security tools to create zest scripts while developers will be able to rerun those scripts using the tools that they are familiar with. in this ca...
compare-locales
or 3.5+ installed on your machine. the easiest way is to just run $ pip install -u compare-locales running it compare-locales gathers the directories to compare from a toml file, usually found in $app/locales/l10n.toml. the details of the configuration file are described in the l10n-config docs. you pass the path to the toml file and the parent dir of the localizations as first arguments, followed by the locale codes of the locales you want to compare. if you want to test the localization for de, run $ compare-locales browser/locales/l10n.toml ./l10n/ de to check mobile, replace the previous line with: $ compare-locales mobile/android/locales/l10n.toml ./l10n/ zh-tw to check mail, suite, calendar that lives on comm-central, you can either rely on the check-out of mozilla within co...
Mozinfo
ying (complex) plethora of os and architecture combinations conform to a subset of values of relevance to mozilla software. the current implementation exposes relevant key, values: os, version, bits, and processor. additionally, the service pack in use is available on the windows platform. api usage mozinfo is a python package. downloading the software and running python setup.py develop will allow you to do import mozinfo from python. mozinfo.py is the only file contained is this package, so if you need a single-file solution, you can just download or call this file through the web. the top 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. mozi...
Redis Tips
odb and manipulating pointers and commonly-used and/or rapidly-changing metadata in redis. maybe the data doesn't belong in your redis memory at all? for example, if you have a job queueing system, you might want redis to manage the queues themselves, and store pointers for the job data which might be retrieved by workers from some different, disk-resident db. (this is, for instance, how tj holowaychuk's implemented kue: https://github.com/learnboost/kue.) memory usage in redis is important to think about. the speed benefits of redis are lost when you overflow into disk memory. as a conservative calculation, i multiply all the bytes i think i might store and multiply by 10, which antirez once recommended as a worst-case factor for data structure overhead. keyspace design here are ...
The Rust programming language
re 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 examples, and learn everything you could possibly wish to know at the rust official web site. rust and the future of systems programming unlocking the power of parallelism with rust rust for web developers safe systems programming with r...
Exploitable crashes
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 publicly. put a security severity rating in the bug's keyw...
Pinning violation reports
if a site makes use of key pinning, and your browser sees a certificate chain for that site which does not match the pin, firefox will reject the connection and display an error page. ...
Security and the jar protocol
ardless of its mime type (in other words, its mime type was assumed to be application/zip, regardless of what it actually was). this means that no matter what the file's real contents are, as far as firefox is concerned, it was a zip archive. this ordinarily isn't a big deal, since site developers wouldn't put up dangerous files and set them up to download like zip archives. however, if a site allows file uploads, zip files are typically treated as relatively innocuous by web sites in that situation, since they're not executable. unless, of course, the browser thinks it's a jar file. so starting with gecko 1.8.0.15 and 1.8.1.10, the jar: protocol is only allowed if the mime type of the file is application/java-archive. a site that serves a file with that type is essentially promising that ...
Gecko object attributes
upport for more information. member-of points to the root of the atomic container that this object is in. this will always be an ancestor of the current object. see the live region support for more information. common widget attributes checkable true when the widget is known to behave like a checkbox. note some widgets which appear to be checkboxes might in fact be cyclers (see "cycles" below). action 0 is named either "check" or "uncheck". applied to: state_checkable state datatype warning: obsolete, do not use! a qname that refers to an xsd (schema) defined type. for example, a datatype may be xsd:integer. when this is not specified, the default is string, unless the value interface is exposed, which indicates the type is numeric. for more information please read about schema ...
ROLE_TABLE
« gecko roles page represents a table that contains rows and columns of cells, and optionally, row headers and column headers. also refer to the following roles: role_columnheader, role_rowheader, role_column, role_row, role_cell. mapped to at-spi: role_table atk: atk_role_table ua: nsaccessibilitygrouprole msaa/ia2: role_system_table used by aria: grid html: <table> xul: <listbox/> ...
Implementation Details
xposed. instead, the same information is available via theisimpledomdocument interface. at-spi events refer to specific pages to get information of supported events for interested at api: gecko msaa ia2 at-spi implementation features this section highlights special features of at apis implementation by gecko. unsupported features we do not support some at apis features. please refer to pages below for interesting at api: msaa ia2 at-spi differences with other applications this section provides information about implementation differences between gecko based applications and other applications. msaa at-spi how to find the content window and load the document in xul-based clients, screen readers may need to find the content window so that they know where to start grabbing the accessible ...
AT APIs Support
ations make full use of the gecko architecture, not only for html content, but also for the entire user interface. widgets such as menus, tab panels, tree views and dialogs are provided via an xml language called xul (extensible user-interface language). none of the user interface contains standard os controls. this is done to ensure a common look and feel across all supported platforms, and to allow for different skins (appearances). developing a xul window is not that different from developing a web page, but the elements available to add widgets are more powerful and designed to be similar to desktop widgets. examples of xul applications: firefox - web-browser thunderbird - email client seamonkey - web-browser, advanced e-mail and newsgroup client, irc chat client, and html editing m...
The Places database
con 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 other history entry. delete annotations that belong to the expiring pages. at shutdown...
Frecency algorithm
the total visit count includes embedded, undefined, etc visits...
Retrieving part of the bookmarks tree
ultnode. before accessing the children of any result container, you must first open it, and then you can iterate the children. as long as the container is open, it will listen for notifications from the bookmarks system to keep itself up-to-date. when you're done, be sure to close the container to free up the resources. otherwise, it will continue to get observer notifications and update itself, slowing down the whole browser. var rootnode = result.root; rootnode.containeropen = true; // iterate over the immediate children of this folder and dump to console for (var i = 0; i < rootnode.childcount; i ++) { var node = rootnode.getchild(i); dump("child: " + node.title + "\n"); } // close a container after using it! rootnode.containeropen = false; if you encounter a node with a type of res...
Using the Places favicon service
ces annotations called "favicon" and forwards these to the favicon service. these annotation uris are described in more detail in using the places annotation service. you should always use nsifaviconservice.getfaviconimageforpage() to get the favicon for a page. if the page has no favicon, or we have never heard of the page, this function will return a "chrome:" uri of the default favicon. this allows efficient caching, since the default favicon will probably be cached in its decoded form by the image library. if there is an error loading the favicon for an annotation uri, the default favicon data will be returned by the annotation service's protocol handler. however, since the uri will be different from the default favicon, the decoded image will not be cached by the image library. see also...
places.sqlite Database Troubleshooting
this article describes troubleshooting actions to deal with a broken places.sqlite database. how to (try to) recover from a corrupt places.sqlite sometimes after a firefox/aurora/nightly upgrade, history disappears, but bookmarks are at their place. in the profile folder a places.sqlite-corrupt file has been created. in some cases, this procedure may allow you to recover the corrupt file along with all of its contents (history). close firefox and ensure it's done closing in your task manager. before you proceed, make a backup of the firefox profile folder, in any case. create a folder to use temporarily for this work, such as my_work_folder. copy places.sqlite-corrupt from the firefox profile folder to the work folder. download the latest precompiled binary sqlite command-li...
extISessionStorage
browser). extisessionstorage is defined in toolkit/components/exthelper/extiapplication.idl. implemented via xpcom service for extiapplication: see the instructions on the fuel (firefox), steel (thunderbird) and smile (seamonkey) pages. method overview these methods are usually accessed via application.storage. ...
Toolkit API
nsion packaging: specific information about how to package extensions theme packaging: specific information about how to package themes multiple-item extension packaging: specific information about multiple-item extension xpis xul application packaging: specific information about how to package xulrunner applications chrome registration printing in xul apps see also the following developer pages contain examples and discussions of particular topics: xul xul overlays developing extensions xulrunner developing themes dom rdf storage ...
Aggregating the In-Memory Datasource
useful here */); // etc... return ns_ok; } it may be tempting to keep a pointer to the aggregate's nsirdfdatasource in a member variable, butyou can't do that. why? because if you did, you'd hold a circular reference that would never unwind. notes describing all of the vagaries of xpcom aggregation is beyond the scope of this document. the basic idea is to overload queryinterface(), allowing it to return adelegate object that supports the interface. there is some trickery involved on the delegate's part to ensure that reference counting is done sanely, and that the reflexive, symmetric, and transitive properties of queryinterface() are preserved. if you're really interested, i'd recommend reading about it in a com book. for more information on writing a datasource, see the rdf da...
Bundling multiple binary components
since binary components are linked against a single gecko sdk, a dependency to a particular version of gecko is created. if the component uses only "frozen" xpcom interfaces, there is a good chance the same binary component will work with different versions of gecko (version 1.8 and 1.9, for example). the more likely case is that the component uses "unfrozen" interfaces and those interfaces can change between gecko versions. this can create a difficult situation for extension developers trying to support multiple gecko versions (firefox 2 and 3, for example). ...
Creating a Python XPCOM component
process type information, but it has a nice feature - it can spit out a template for a python implementation of any interface. just execute this file as a script with the interface name as a param. for example: % cd c:\mozilla\bin\python\xpcom % python xpt.py nsisample class nsisample: _com_interfaces_ = xpcom.components.interfaces.nsisample # if this object needs to be registered, the following 2 are also needed. # _reg_clsid_ = "{a new clsid generated for this object}" # _reg_contractid_ = "the.object.name" def get_value( self ): # result: string pass def set_value( self, param0 ): # result: void - none # in: param0: string pass as you can see, the output is valid python code, with basic signatures and useful comments for eac...
Fun With XBL and XPConnect
lication of xbl in which a simple xpcom interface is made accessible to a xul widget. the interface definition feature of xbl is used to define an interface through xpconnect to a c++ object that does auto completion. once the regular xul textfield widget is bound to this interface, it calls the auto complete function of the object using regular javascript. the basic model of interaction is as follows: binding to the xpcom object the widget holds onto an xpcom object that is the auto complete engine that will perform our auto complete lookups. <binding name="autocomplete" extends="xul:box"> <content> <xul:textfield class="addressingwidget"/> <xul:menupopup/> </content> <implementation> <property name="autocompletesession"> <![cdata[ components.classes['com...
XPCOM glue
Mozilla › Tech › XPCOM › Glue
compiling or linking against xpcom headers there are three ways to compile/link against xpcom headers/libraries: frozen linkage: dependent glue (dependent on xpcom.dll) xpcom modules, i.e. extension or xulrunner application components, should use the dependent glue. code which wishes to use only frozen symbols but can tolerate a load-time dependency on xpcom.dll should link against xpcomglue_s.lib and xpcom.lib. ...
XPCOM hashtable guide
ce-counted) nsclasshashtable reference-counted concrete classes nsrefptrhashtable interface pointers nsinterfacehashtable each of these classes is a template with two parameters. the first is the hash key and the second is the data to be stored. there are a number of builtin hash keys available in nshashkeys.h, the more useful of which are listed below. key type hashkey class strings nsstringhashkey/nscstringhashkey integers nsuint32hashkey/nsuint64hashkey pointers nsptrhashkey<t> owned interface pointers nsisupportshashkey reference-counted concrete classes nsrefptrhashkey there are a number of more esoteric hashkey classes in nshashkeys.h, and you can always roll ...
How to build a binary XPCOM component using Visual Studio
al studio project and file templates (or wizards) for creating xpcom modules and components do not currently exist. for now, you can use the included xpcom project that contains a simple xpcom component. you can use the project as a starting point and modify the component files to add your own functionality. to make the project, you start with a standard multi-thread dll project. ...
How To Pass an XPCOM Object to a New Window
...
Interfacing with the XPCOM cycle collector
ns_impl_cycle_collection_unlink(msomemember) these macros should handle a variety of cases, such as reference counted pointers to cycle collected nsisupports or non-nsisupports objects, as well as arrays of these pointers. handling jsobjects fields if your class needs to store a pointer to a jsobject then you need to tell the cycle collector about it. the approach you should take is as follows. firstly it must be held in a js::heap<jsobject *> field. for example, suppose your class nsfoo has field msomeobj: private: ... js::heap<jsobject*> msomeobj; ... when you have something in the js object pointer you need to use mozilla::holdjsobjects to tell the gc to trace it and keep the object alive: ... msomeobj = ... ; mozilla::holdjsobjects(this); ... in the unlink method (or ...
Components.classesByID
is exactly like components.classes except that the elements are indexed by the canonical form of their cid, and does not only represent the component classes that have been registered with the component manager using a contractid, but also those registered using a plain cid. usage in order to retrieve the object for a given cid, you can use that cid as an index with components.classesbyid as follows: var clazz = components.classesbyid["{ed132c20-eed1-11d2-baa4-00805f8a5dd7}"]; ...
Components.interfaces
rfaces object are indexed by interface name. you can retrieve an interface object using: var iface = components.interfaces.nsisupportsarray; this will return you the interface object for the nsisupportsarray interface. ...
Components.lastResult
e target call is made and save it in a local variable to test its value rather than doing 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.re...
Components.utils.unload
re/ or resource:/// or resource://app/) as these may be in use by other extensions and the application. only unload modules you include as part of your extension. syntax components.utils.unload( url ); parameters url the "resource://" url of the script to unload. this must be the same url that was used to load the script. example you can unload a module called mymodule.jsm using the following line of code: components.utils.unload("resource://myaddon/modules/mymodule.jsm"); note: currently components.utils.unload clears the global object of an unloaded module. this may cause modules to misbehave after unloading even if you have a reference to them. see bug 769253 see also bug 481603 the documentation in xpccomponents.idl the tests in js/xpconnect/tests/unit/ ...
Components object
components! the components object is the object through which xpconnect functionality is reflected into javascript. the components object is actually a native instance of the nsixpccomponents interface which is reflected into javascript as a top level object using xpconnect. some properties of components require advanced privileges and may not work in web pages. ...
PyXPCOM
pyxpcom is actively used in activestate komodo products, for example. with pyxpcom, a developer can talk to xpcom or embed gecko from a python application. pyxpcom is similar to javaxpcom (java-xpcom bridge) or xpconnect (javascript-xpcom bridge). mozilla defines many external interfaces available to embeddors and component developers. pyxpcom provides access to these interfaces as python interfaces. pyxpcom also contains several classes that provide access to functions for initializing and shutting down xpcom and gecko from python, as well as some xpcom helper functions. ...
RbXPCOM
rbxpcom (ruby cross-platform com) provides bindings between the popular ruby programming language and xpcom. you can find additional information using the resource links below. project page (mozdev) manual (mozdev) mailing list (mozdev) newsgroup (mozdev) ...
Using components
there is also another way to start, which is exactly equivalent to the above. var {cc: classes, ci: interfaces} = components; there are many more than just classes and interfaces. var { cu: utils, ci: interfaces, cc: classes, cr: results, cs: stack, cm: manager, ce: exception, } = components; here is a full breakdown of what is contained in components. ...
Profiling XPCShell
50} 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 line number; the function's size; the amount of time (in milliseconds) the fastest call took; the time of the slowest call; the average time spend; the total time; the time spend in the function itself is given (that is the total time excluding the time spend in functions called from this function). notes you need a trunk build from after 2007-05-28. using an earlier build will cause the profiler to hang the more adventurous can use the nsixpctoolsprofiler.idl interface directly, but be aware that you ...
Standard XPCOM components
nscategorymanagerthe xpcom category manager.nsdirectoryservicethe xpcom directory service. this service returns the locations of "well known" directories in an os-independent manner. for instance, it can give you the path of the system's temporary directory, desktop directory, current working directory, and so on.nslocalfilea component implementing nsilocalfile. ...
NS_InitXPCOM2
current working directory should be used. aappfilelocationprovider [in] the object to be used by xpcom to locate application specific directories and files (e.g., the user profile, the component registry, etc.). this parameter may be nsnull. return values the ns_initxpcom2 function returns ns_ok if successful. otherwise, it returns an error code. some of the possible errors are documented below: ns_error_not_initialized indicates that static globals were not yet initialized, which may happen if this method is called before xpcom's static initialization code executes. this error may also occur if xpcom is being initialized after ns_shutdownxpcom has been called. remarks you must call ns_initxpcom2 (or ns_initxpcom3) before proceeding to use xpcom in a process. the one exception is ...
NS_NewLocalFile
« xpcom api reference summary the ns_newlocalfile function creates an instance of nsilocalfile that provides a platform independent representation of a file path. #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...
NS_NewNativeLocalFile
« xpcom api reference summary the ns_newnativelocalfile function creates an instance of nsilocalfile that provides a platform independent representation of a file path. #include "nsxpcom.h" #include "nsilocalfile.h" nsresult ns_newnativelocalfile( const nsacstring& apath, prbool 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 ...
nsresult
pilers that don't support this feature of c++11), it falls back to being an unsigned 32-bit integer, as in past versions of gecko. note: prior to gecko 19.0, nsresult was not strongly typed. as a result, it was possible for code to misuse it, such as returning an nsresult value from a function whose signature indicates it returns a boolean. because nsresult is strongly typed, code like the following will result in an error at compile time: bool foo() { ... if (something) { return ns_error_failure; } ... } see also error codes returned by mozilla apis ...
operator=
« xpcom api reference summary this operator is a shortcut for the assign family of functions. self_type& operator=( const self_type& astring ); parameters astring [in] a nsacstring to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator=( char_type achar ); parameters achar [in] a character to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. see also...
operator+=
« xpcom api reference summary this operator+= is a shortcut for the append family of functions. self_type& operator+=( const self_type& astring ); parameters astring [in] a nsacstring to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator+=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator+=( char_type achar ); parameters achar [in] a character to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. s...
operator=
« xpcom api reference summary this operator= is a shortcut for the append family of functions. self_type& operator+=( const self_type& astring ); parameters astring [in] a nsastring to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. self_type& operator=( char_type achar ); parameters achar [in] a character to append to this string. return values this operator returns a reference back to the object being modified to allow operator chaining. see als...
nsMemory
#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. ...
RefPtr
e but hasn't yet been fixed. while refptr should not generally be used to hold a pointer to an xpcom interface, this is flexible. there are no technical problems with doing so, and in some cases it may be necessary (see bug 756640 comment 1). for example, we have template classes such as owningnullptr that can contain a refptr to an xpcom interface. xxx it's not clear that the details in the following paragraph are correct. it was derived from an old #developers discussion. it's unclear to me when the compiler will reject an attempt to use nscomptr to hold a concrete class pointer and when it will not (will it only rejecte it if a qi is involved in the construction or or assignment to the nscomptr (common in implementation details of nscomptr) but not when an instance of the concrete class ...
IAccessibleEditableText
known last changed in gecko 1.9 (firefox 3) this interface is typically used in conjunction with the iaccessibletext interface and complements that interface with the additional capability of clipboard operations. note that even a read only text object can support the copy capability so this interface is not limited to editable objects. the substrings used with this interface are specified as follows: if startoffset is less than endoffset, the substring starts with the character at startoffset and ends with the character just before endoffset. if endoffset is lower than startoffset, the result is the same as a call with the two arguments exchanged. the whole text can be defined by passing the indices zero and iaccessibletext.ncharacters(). if both indices have the same value, an empty string...
IAccessibleHypertext
ndex. this is the case when a link spans the given character index. [propget] hresult hyperlinkindex( [in] long charindex, [out] long hyperlinkindex ); parameters charindex a 0 based index of the character for which to return the link index. if iaccessibletext is used to represent the text containing the link, then the character index is only valid if it is greater than or equal to zero and lower than the number of characters in the text. hyperlinkindex the 0 based index of the hyperlink that is associated with this character index, or -1 if charindex is not on a link. return value e_invalidarg if bad [in] passed, [out] value is null. s_false if there is nothing to return, [out] value is -1. s_ok. nhyperlinks() returns the number of links and link groups contained within this hypertext...
amIInstallTrigger
d(); parameters none. return value install() starts a new installation of a set of add-ons. boolean install( in nsivariant aargs, in amiinstallcallback acallback optional ); parameters aargs the add-ons to install. this should be a js object, each property is the name of an add-on to be installed. the value of the property should either be a string url, or an object with the following properties: url for the add-on's url iconurl for an icon for the add-on hash for a hash of the add-on. acallback optional a callback to call as each installation succeeds or fails. return value true if the installations were successfully started. installchrome starts installing a new add-on. this method is deprecated, please use install() in the future. boolean installchrom...
amIWebInstallInfo
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 install(); attributes attribute type description installs nsivariant an array of addoninstall objects. ...
amIWebInstallListener
] in nsivariant ainstalls, [optional] in pruint32 acount); boolean onwebinstallrequested(in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, [optional] in pruint32 acount); note: prior to gecko 8.0, all references to nsidomwindow used in this interface were nsidomwindowinternal. methods onwebinstallblocked() called when the website is not allowed to directly prompt the user to install add-ons. boolean onwebinstallblocked( in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, in pruint32 acount optional ); parameters awindow the window that triggered the installs. auri the uri of the site that triggered the installs. ainstalls the addoninstalls that were blocked. ...
imgICache
image/public/imgicache.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) as of firefox 18, there is no longer a single image cache. that means that using getservice in order to obtain it will yield incorrect results. ...
jsdIStackFrame
context. scripts typically select this with the "language" attribute. see the version_* consts on jsdidebuggerservice. unique tag among all valid jsdicontext objects, useful as a hash key. private data for this context, if it is an nsisupports, |null| otherwise. retrieve the underlying context wrapped by this jsdicontext. top of the scope chain for this context. |true| if this context should be allowed to run scripts, |false| otherwise. this attribute is only valid for contexts which implement nsiscriptcontext. setting or getting this attribute on any other context will throw a ns_error_no_interface exception. stack frame objects. these are only valid inside the jsdiexecutionhook which gave it to you. after you return from that handler the bottom frame, and any frame you found attached throug...
mozIAsyncHistory
toolkit/components/places/moziasynchistory.idlscriptable this interface allows you to add multiple visits to a single url in a batch. 1.0 66 introduced gecko 24.0 inherits from: nsisupports last changed in gecko 24.0 (firefox 24.0 / thunderbird 24.0 / seamonkey 2.21) implemented by: @mozilla.org/browser/history;1 as a service: var asynchistory = components.classes["@mozilla.org/browser/history;1"] .getservice(components.interfaces.moziasynchistory); method overview void getplacesinfo(in jsval aplaceidentifiers, in mozivisitinfocallback acallback); void isurivisited(in nsiuri auri, in mozivisitedstatuscallback acallback); void updateplaces(in moziplaceinfo, [optional] in mozivisitinfocallback acallback); m...
mozIColorAnalyzer
ing it. void findrepresentativecolor( in nsiuri imageuri, in mozirepresentativecolorcallback callback ); parameters imageuri a uri pointing to the image - ideally a data: uri, but any scheme that will load when setting the src attribute of a dom img element should work. ...
mozIStorageAsyncStatement
an asynchronous sql statement. this differs from mozistoragestatement by only being usable for asynchronous execution. (mozistoragestatement can be used for both synchronous and asynchronous purposes.) this specialization for asynchronous operation allows us to avoid needing to acquire synchronization primitives also used by the asynchronous execution thread. in contrast, mozistoragestatement may need to acquire the primitives and consequently can cause the main thread to lock for extended intervals while the asynchronous thread performs some long-running operation. inherited interface mozistoragebasestatement ...
mozIStoragePendingStatement
storage/public/mozistoragependingstatement.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 method overview void cancel(); methods cancel() cancels the pending statement. fails only if you attempt to cancel the operation more than once. note: for read statements, such as select, once you cancel the statement, you will receive no further notifications about results. ...
mozIStorageProgressHandler
storage/public/mozistorageprogresshandler.idlscriptable please add a summary to this article. last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsisupports method overview boolean onprogress(in mozistorageconnection aconnection); methods onprogress() the onprogress() method is called periodically while an sqlite operation is ongoing. this allows you to monitor the progress and possibly display status information to the user. boolean onprogress( in mozistorageconnection aconnection ); parameters <tt>aconnection</tt> a mozistorageconnection connection indicating the connection for which the callback was invoked. return value return true to abort the request or false to allow it to continue. see also storage mozstorage introduc...
mozITXTToHTMLConv
constant type description kentities unsigned long enables conversion of basic special characters to html entities. this applies to "<", "&", and ">" (which are converted to &lt;, &amp;, and &gt;, respectively). kglyphsubstitution unsigned long enables conversion of smilies and non-ascii special characte...
nsIAboutModule
in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview unsigned long geturiflags(in nsiuri auri); nsichannel newchannel(in nsiuri auri); constants constant value description uri_safe_for_untrusted_content (1 << 0) a flag that indicates whether a uri is safe for untrusted content. if it is, web pages and so forth will be allowed to link to this about: uri. otherwise, only chrome will be able to link to it. allow_script (1 << 1) a flag that indicates whether script should be enabled for the given about: uri even if it's disabled in general. hide_from_aboutabout (1 << 2) a flag that indicates whether this about: uri doesn't want to be listed in about:about, especially if it's not useful wi...
GetAccessibleAbove
« nsiaccessible page summary this method returns an accessible node geometrically above this one. nsiaccessible getaccessibleabove(); return value returns an accessible node geometrically above this one. see also nsiaccessible.getaccessibletoright() nsiaccessible.getaccessibletoleft() nsiaccessible.getaccessiblebelow() ...
GetAccessibleToLeft
« nsiaccessible page summary this method returns an accessible node geometrically to the left of this one. nsiaccessible getaccessibletoleft(); return value returns an accessible node geometrically to the left of this one. see also nsiaccessible.getaccessibletoright() nsiaccessible.getaccessibleabove() nsiaccessible.getaccessiblebelow() ...
GetAccessibleToRight
« nsiaccessible page summary this method returns an accessible node geometrically to the right of this one. nsiaccessible getaccessibletoright(); return value returns an accessible node geometrically to the right of this one. see also nsiaccessible.getaccessibletoleft() nsiaccessible.getaccessibleabove() nsiaccessible.getaccessiblebelow() ...
nsIAccessibleImage
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void getimageposition(in unsigned long coordtype, out long x, out long y); void getimagesize(out long width, out long height); methods getimageposition() returns the coordinates of the image accessible. this method is the same as nsiaccessible.getbounds() excepting coordinate origin parameter. ...
nsIAccessibleRelation
up of one or more objects. when there is more than one object in the group each member may have one and the same target, for example a grouping object. it is also possible that each member has multiple additional targets, for example one for every other member in the group. relation_node_child_of 0x06 this object is a child of a target object. relation_flows_to 0x07 content flows from this object to a target object, that is has content that flows logically to another object in a sequential way, for example text flow. relation_flows_from 0x08 content flows to this object from a target object, that is has content that flows logically from another object in a sequential way, for example text flow. ...
nsIAccessibleText
ffsets around the given offset. this accessible get return the dom node and layout frame with the uniform attributes for this range of text. nsiaccessible getattributerange( in long offset, out long rangestartoffset, out long rangeendoffset ); parameters offset rangestartoffset rangeendoffset return value getcharacteratoffset() it would be better to return an unsigned long here, to allow unicode chars > 16 bits. wchar getcharacteratoffset( in long offset ); parameters offset return value getcharacterextents() returns the bounding box of the specified position. the virtual character after the last character of the represented text, that is the one at position length is a special case. it represents the current input position and will therefore typically be queried by at mor...
nsIAppShell
anting to be unhooked. resumenative() resumes the use of additional platform-specific methods to run() gecko events on the main application thread. calls to suspendnative() and resumenative may be nested. on some platforms this will be a no-op. void resumenative(); parameters none. run() enter an event loop. do not leave until exit() is called. void run(); parameters none. runinstablestate() allows running of a "synchronous section", in the form of an nsirunnable once the event loop has reached a "stable state". a stable state is reached when the currently executing task/event has finished, (see: webappapis.html#synchronous-section). in practice this runs arunnable once the currently executing event finishes. if called multiple times per task/event, all the runnables will be executed, in t...
nsIAppShellService
e of the e* constants. createwindowlessbrowser() this method creates a browser that does not have a window. if the browser is exited, this windowless browser will not prevent firefox from exiting. e10s notes: the browser is created in process. to get an out of process element you want to communicate with via message manager, then append a browser element with remote attribute set to true. ...
nsIAsyncVerifyRedirectCallback
see also ...
nsIAuthInformation
of this object to indicate to the caller what was entered by the user. attributes attribute type description authenticationscheme autf8string the authentication scheme used for this request, if applicable. if the protocol for this authentication does not support schemes, this will be the empty string. otherwise, this will be a string such as "basic" or "digest". this string will always be in lowercase. read only. domain astring the initial value should be used to prefill the dialog or be shown in some other way to the user. on return, this parameter should contain the domain entered by the user. this attribute is only used if flags include #need_domain. flags unsigned long flags describing this dialog. a bitwise or of the constants. it is possible that neither #auth_host nor #auth_p...
nsIAuthModule
voidptr aouttoken, out unsigned long aouttokenlength); void wrap([const] in voidptr aintoken, in unsigned long aintokenlength, in boolean confidential, out voidptr aouttoken, out unsigned long aouttokenlength); constants constant value description req_default 0 default behavior. req_mutual_auth (1 << 0) client and server will be authenticated. req_delegate (1 << 1) the server is allowed to impersonate the client. the req_mutual_auth flag may also need to be specified in order for this flag to take effect. methods getnexttoken() this method is called to get the next token in a sequence of authentication steps. void getnexttoken( [const] in voidptr aintoken, in unsigned long aintokenlength, out voidptr aouttoken, out unsigned long aouttokenlength ); parameters ainto...
nsIAuthPrompt
inherits from: nsisupports last changed in gecko 1.9 (firefox 3) this interface is implemented by @mozilla.org/login-manager/prompter;1. ...
nsIAuthPrompt2
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) this interface is usually acquired using getinterface on notification callbacks or similar. it can be used to prompt users for authentication information, either synchronously or asynchronously. this interface is implemented by @mozilla.org/login-manager/prompter;1. ...
nsIAuthPromptProvider
iven prompt reason. void getauthprompt( in pruint32 apromptreason, in nsiidref iid, [iid_is(iid),retval] out nsqiresult result ); parameters apromptreason the reason for the authentication prompt, one of the prompt_* constants. iid the desired interface, for example, ns_get_iid(nsiauthprompt2). result a nsiauthprompt2 interface. exceptions thrown ns_error_not_available if no prompt is allowed or available for the given reason. ...
nsIBlocklistPrompt
pt( [array, size_is(acount)] in nsivariant aaddons, in pruint32 acount optional ); parameters aaddons an array of addons and plugins that are blocked. these are javascript objects with properties: name - the plugin or extension name version - the version of the extension or plugin icon - the plugin or extension icon disable - can be used by the nsiblocklistprompt to allows users to decide whether a soft-blocked add-on should be disabled blocked - true if the item is hard-blocked, false otherwise item - the nsiplugintag or addon object acount optional the number of addons. ...
nsICache
equested - 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 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 s...
nsIChannelPolicy
netwerk/base/public/nsichannelpolicy.idlscriptable a container for policy information to be used during channel creation. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 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 nsiconten...
nsICommandLine
esolveuri(in astring aargument); attributes attribute type description length long number of arguments in the command line. the application name is not part of the command line. read only. preventdefault boolean there may be a command-line handler which performs a default action if there was no explicit action on the command line (open a default browser window, for example). this flag allows the default action to be prevented. state unsigned long the type of command line being processed. see state constants. read only. windowcontext nsidomwindow a window to be targeted by this command line. in most cases, this will be null (xremote will sometimes set this attribute). read only. workingdirectory nsifile the working directory for this command line. use this property instead of...
nsIComponentManager
d getclassobjectbycontractid(in string acontractid, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result); void removebootstrappedmanifestlocation(in nsilocalfile alocation); methods addbootstrappedmanifestlocation() loads a "bootstrapped" chrome.manifest file from the specified directory or xpi file. a "bootstrapped" chrome manifest supports some of the instructions allowed in a regular chrome manifest, see the chrome registration documentation for details. this method was introduced in gecko 8 to let bootstrapped add-ons provide content at chrome:// uris. until gecko 10 you had to call this method manually from within the add-on's startup() method (with a matching removebootstrappedmanifestlocation() call in the add-on's shutdown() method). if you're targeting ...
nsIConsoleListener
inherits from: nsisupports last changed in gecko 1.7 method overview void observe(in nsiconsolemessage amessage); methods observe() called by the nsiconsoleservice when a message is posted to the console. ...
nsIContentPrefObserver
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void oncontentprefremoved(in astring agroup, in astring aname); void oncontentprefset(in astring agroup, in astring aname, in nsivariant avalue); methods oncontentprefremoved() called when a content preference is removed. ...
nsIControllers
xul elements can also have controllers, although they do not have any default controllers. ...
nsIConverterInputStream
1.0 66 introduced gecko 1.8 inherits from: nsiunicharinputstream last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: @mozilla.org/intl/converter-input-stream;1. ...
nsIConverterOutputStream
1.0 66 introduced gecko 1.8 inherits from: nsiunicharoutputstream last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: @mozilla.org/intl/converter-output-stream;1. ...
nsICrashReporter
escription 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 nsiurl get or set the url to which crash reports will be submitted. only https and http urls are allowed, as the submission is handled by os-native networking libraries. exceptions thrown ns_error_failure on get if no url is set. ns_error_invalid_arg on set if a non-http(s) url is assigned. ns_error_not_initialized if crash reporting is not initialized. submitreports boolean user preference for submitting crash reports. methods annotatecrashreport() add some extra data to be submitted wi...
nsIDNSRecord
netwerk/dns/nsidnsrecord.idlscriptable this interface represents the result of a dns lookup. since a dns query may return more than one resolved ip address, the record acts like an enumerator, allowing the caller to easily step through the list of ip addresses. inherits from: nsisupports last changed in gecko 1.7 method overview prnetaddr getnextaddr(in pruint16 aport); native code only! acstring getnextaddrasstring(); boolean hasmore(); void rewind(); attributes attribute type description canonicalname acstring for example, www.mozilla.org --> rheet.mozilla.org. read only. methods native code only!getnextaddr this function copies the value of the next ip address into the given prnetaddr struct and increments the internal address iterator. prnetaddr getnext...
nsIDNSService
e aflags parameter passed to asyncresolve() and resolve(). constant value description resolve_bypass_cache (1 << 0) this flag suppresses the internal dns lookup cache. resolve_canonical_name (1 << 1) the canonical name of the specified host will be queried. resolve_priority_medium (1 << 2) the query is given medium priority. if used with low, medium takes precedence. resolve_priority_low (1 << 3) the query is given lower priority. if used with medium, medium takes precedence. resolve_speculate (1 << 4) indicates request is speculative. speculative requests return errors if prefetching is disabled by configuration. resolve_disable_ipv6 (1 << 5) if this flag is set, only ipv4 addresses wi...
nsIDOMChromeWindow
ndowstate 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 must check this. void beginwindowmove( in nsidomevent mousedownevent ); parameters mousedownevent exceptions thrown ns_error_not_implemented if the operating system does not support this method...
nsIDOMFile
this is also used by the datatransfer object to describe files dragged into a web application using drag and drop. note that in gecko, this interface currently inherits from nsisupports, but in the file api specification, it should be a blob. ...
nsIDOMGeoPositionAddress
tring the county. read only. postalcode domstring the postal or zip code. read only. premises domstring the premises. read only. region domstring the region. read only. street domstring the street of the address. read only. streetnumber domstring the street number of the address. read only. historical note, which is likely of no interest to most readers: the types of the attributes below all changed from string to domstring in gecko 1.9.2 beta 5. see also using geolocation ...
nsIDOMHTMLSourceElement
it does not specify anything on its own. ...
nsIDOMOfflineResourceList
it includes methods for adding resources to and removing resources from the cache, as well as for enumerating the dynamically managed resource list. dom/interfaces/offline/nsidomofflineresourcelist.idlscriptable please add a summary to this article. ...
nsIDOMOrientationEvent
dom/interfaces/events/nsidomorientationevent.idlscriptable please add a summary to this article. ...
nsIDOMSimpleGestureEvent
domsimplegestureevent.idlscriptable this interface describes a mouse or trackpad gesture event. 1.0 66 introduced gecko 1.9.1 inherits from: nsidommouseevent last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) the nsidomsimplegestureevent interface is the datatype for all mozilla-specific simple gesture events in the document object model. the following events are generated: mozswipegesture - generated when the user completes a swipe across across the input device. mozmagnifygesturestart - generated when the user begins the magnify ("pinch") gesture. the "delta" value represents the initial movement. mozmagnifygestureupdate - generated periodically while the user is continuing the magnify ("pinch") gesture. the "delta" value represents the...
nsIDOMStorageEventObsolete
e domain of the storage area which changed, or "#session" if the event represents a change to session storage. read only. methods initstorageevent() initializes a storage event. void initstorageevent( in domstring typearg, in boolean canbubblearg, in boolean cancelablearg, in domstring domainarg ); parameters typearg the type argument. canbubblearg true if the event is allowed to bubble, otherwise false. cancelablearg true if the event can be canceled, otherwise false. domainarg the domain to which the event belongs, or "#session" if the event is associated with session storage. see also storage storageevent structured client-side storage (html 5 specification) nsidomstorageitem ...
nsIDOMWindow2
face is the primary interface for a dom window object. it represents a single window object that may contain child windows if the document in the window contains an html frameset document, or if the document contains <iframe> elements. inherits from: nsidomwindow last changed in gecko 1.9 (firefox 3) because nsidomwindow is frozen, this interface was introduced in firefox 3 (gecko 1.9) to allow dom windows to take on new features. dom windows implement nsidomwindow2, which is a subclass of nsidomwindow. in gecko 7.0 this interface has been merged into nsidomwindow. attributes attribute type description applicationcache nsidomofflineresourcelist the application cache object for this window. read only. windowroot nsidomeventtarget the window...
nsIDebug
hat failed. afile file containing assertion. aline line number of assertion. break() requests the software break into a debugger. if no debugger is running then this usually results in a program crash. however, on windows a dialog is first presented giving the user the option of aborting, breaking, or ignoring the request. the dialog can be suppressed by use of the windbgdlg registry key. this allows the debugger to be attached before the software break. void break( in string afile, in long aline ); parameters afile file containing break request. aline line number of break request. warning() shows a warning. void warning( in string astr, in string afile, in long aline ); parameters astr warning message. afile file containing warning. aline line number of warning. see also ns...
nsIDirectoryServiceProvider2
xpcom/io/nsidirectoryservice.idlscriptable an extension of nsidirectoryserviceprovider which allows multiple files to be returned for the given key. inherits from: nsidirectoryserviceprovider last changed in gecko 0.9.6 method overview nsisimpleenumerator getfiles(in string prop); methods getfiles() the directory service calls this when it gets a request for a prop and the requested type is nsisimpleenumerator. nsisimpleenumerator getfiles( in string prop ); parameters prop the symbolic name of the file list. return value an enumerator for a list of file locations. the elements in the enumeration are nsifile. use an xpcom return code of ns_success_aggregate_result if this result should be aggregated with other "lower" providers. if you are implementing this from js,...
nsIDownloadProgressListener
nager.removelistener() to stop listening. as the states of downloads change, the methods described here are called by the download manager so your code can take whatever steps it needs to. this interface works very similarly to the nsiwebprogress interface. it is important to note that there is no service for this listener. rather, the developer must create an object with the methods provided below to implement it. method overview void ondownloadstatechange(in short astate, in nsidownload adownload); void onlocationchange(in nsiwebprogress awebprogress, in nsirequest arequest, in nsiuri alocation, in nsidownload adownload); obsolete since gecko 1.9.1 void onprogresschange(in nsiwebprogress awebprogress, in nsirequest arequest, in long long acurselfprogress, in ...
nsIDragSession
sfer the data transfer object for the current drag operation. dragaction unsigned long sets the action (copy, move, link and so on) for the current drag. (see nsidragservice) numdropitems unsigned 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 ...
nsIDynamicContainer
at the service can populate the container if necessary. note: all result nodes implement a property bag if you need to store state. void oncontainernodeopening( in nsinavhistorycontainerresultnode acontainer, in nsinavhistoryqueryoptions aoptions ); parameters acontainer the container node for the container being opened. aoptions the options used to generate this query. containers should follow these when possible, for example, whether to expand queries, etc. implementations should use this when possible if adding query and folder nodes to the container. do not modify this value. oncontainerremoving() this method is called when the given container is about to be deleted from the bookmarks table, so that the service can do any necessary cleanup. it is called before the container is dele...
nsIEnvironment
he value of the env variable. an empty string will be returned when the env variable does not exist or when the value itself is an empty string - please use exists() to probe whether the env variable exists or not. exists() check the existence of an environment variable. this method checks whether an environment variable is present in the environment or not. note: * for unix/linux platforms we follow the unix definition: an environment variable exists when getenv() returns a non-null value. an environment variable does not exist when getenv() returns null. for non-unix/linux platforms we have to fall back to a "portable" definition (which is incorrect for unix/linux!!!!) which simply checks whether the string returned by get() is empty or not. boolean exists( in astring aname ); para...
nsIErrorService
string bundle keys can also be mapped. ...
ExtensionManager (Toolkit)
note: this api is obsolete starting in gecko 2.0, and has been replaced by the new add-on manager. ...
nsIFTPEventSink
the nsiftpeventsink is an extension of nsisupports. it can be used as a notification callback on an ftp channel. netwerk/protocol/ftp/nsiftpchannel.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview void onftpcontrollog(in boolean server, in string msg) methods onftpcontrollog allows a consumer to receive a log of the ftp control connection conversation. void onftpcontrollog ( in boolean server, in string msg); parameters server a boolean value specifying whether you are a server or a client. msg a string holding response of the last command which had been sent. ...
nsIFactory
inherits from: nsisupports last changed in gecko 0.9.5 method overview void createinstance(in nsisupports aouter, in nsiidref iid, [retval, iid_is(iid)] out nsqiresult result); void lockfactory(in prbool lock); methods createinstance() creates an instance of the class associated with this factory. unlike getservice, this returns a new instance each time it is called. ...
nsIFaviconService
() this method checks to see if this favicon is in the failed favicon cache. boolean isfailedfavicon( in nsiuri afaviconuri ); parameters afaviconuri the uri of an icon in the favicon service. can be null. return value returns true if the favicon is in the failed cache, meaning you probably shouldn't try to load it. a false return value means that it's worth trying to load it. this allows you to avoid trying to load "foo.com/favicon.ico" for every page on a site that doesn't have a favicon. removefailedfavicon() this method removes the given favicon from the failed favicon cache. if the icon is not in the cache, this function will silently succeed. void removefailedfavicon( in nsiuri afaviconuri ); parameters afaviconuri the uri of an icon in the favicon service. can ...
nsIFeed
11:00 pm), and are always indicated using utc. note: this field is rarely implemented. subtitle nsifeedtextconstruct returns a subtitle for the feed, based on its description, subtitle, and appropriate extensions. textinput nsiwritablepropertybag2 information about a text box that can be displayed along with the feed by aggregators that support it, to allow the reader to send a response back to the source of the feed. note: this field is almost never used, and is incompatible with many aggregators. type unsigned long indicates the type of content presented by a feed. see constants. note: you should consider this a bit mask of values; at some point, the type may include more than one of these values ored together. read only. ...
nsIFeedEntry
1.0 66 introduced gecko 1.8 inherits from: nsifeedcontainer last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) attributes attribute type description content nsifeedtextconstruct the full text of the entry's content. this comes from the atom:content and/or content:encoded fields. ...
nsIFeedProgressListener
toolkit/components/feeds/public/nsifeedlistener.idlscriptable this interface defines callbacks used during the processing of an rss or atom feed. programs using the feed content access api do not have to implement any of these callbacks; they are optional, but allow you to provide feedback during the parsing process. 1.0 66 introduced gecko 1.8 inherits from: nsifeedresultlistener last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void handleentry(in nsifeedentry entry, in nsifeedresult result); void handlefeedatfirstentry(in nsifeedresult result); void handlestartfeed(in nsifeedresult result); void reporterror(in astring errortext, in long linenumber, in boolean bozo); method...
nsIFeedResult
lt stylesheet available to transform the source of the feed. some feeds include this information in a processing instruction. it's generally intended for use by clients designed to work with specific feeds. uri nsiuri the address from which the feed was fetched. version astring the version of the feed; null if a non-feed is processed. this value will be one of the following: atom, rss2, rss09, rss091, rss091userland, rss092, rss1, atom03, atomentry, rssitem methods registerextensionprefix() registers a prefix for a namespace used to access an extension in the feed or entry. warning: this method is not implemented at this time. void registerextensionprefix( in astring anamespace, in astring aprefix ); parameters anamespace the namespace ...
nsIFileOutputStream
nsioutputstream last changed in gecko 1.7 method overview void init(in nsifile file, in long ioflags, in long perm, in long behaviorflags); constants behavior flag constants constant value description defer_open 1<<0 see the same constant in nsifileinputstream. the deferred open will be performed when one of the following is called: seek() tell() write() flush() defer_open is useful if we use the stream on a background thread, so that the opening and possible stating of the file happens there as well. note: using this flag results in the file not being opened during the call to init(). this means that any errors that might happ...
nsIFilePicker
.raw filters for file extensions. filterxml 0x010 corresponds to the *.xml filter for file extensions. filterxul 0x020 corresponds to the *.xul filter for file extensions. filterapps 0x040 corresponds to the platform specific application filter for file extensions. application files for the user's platform will pass through the filter. filterallowurls 0x80 allow urls. filteraudio 0x100 corresponds to the *.aac, *.aif, *.flac, *.iff, *.m4a, *.m4b, *.mid, *.midi, *.mp3, *.mpa, *.mpc, *.oga, *.ogg, *.ra, *.ram, *.snd, *.wav and *.wma filters for file extensions. filtervideo 0x200 corresponds to the *.avi, *.divx, *.flv, *.m4v, *.mkv, *.mov, *.mp4, *.mpeg, *.mpg, *.ogm, *.ogv, *.ogx, *.rm, *.rmvb, *.smil, ...
nsIFileStreams
netwerk/base/public/nsifilestreams.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview void init(in nsifile file, in long ioflags, in long perm, in long behaviorflags); constants constants value description delete_on_close 1<<1 if this is set, the file will be deleted by the time the stream is closed. it may be removed before the stream is closed if it is possible to delete it and still read from it. if open_on_read is defined, and the file was recreated after the first delete, the file will be deleted again when it is closed again. ...
nsIFileURL
...
nsIFrameLoader
l] in boolean aignorerootscrollframe); void updatepositionandsize(in nsiframe aiframe); native code only! attributes attribute type description delayremotedialogs boolean depthtoogreat boolean find out whether the loader's frame is at too great a depth in the frame tree. this can be used to decide what operations may or may not be allowed on the loader's docshell. read only. docshell nsidocshell get the docshell from the frame loader. read only. messagemanager nsichromeframemessagemanager the message manager handling messages for this frame. read only. methods activateframeevent() activates event forwarding from client (remote frame) to parent. void activateframeevent( in astring atype,...
nsIFrameLoaderOwner
with the given nsiframeloaderowner. this may only be possible in a very limited set of circumstances, or never, depending on the object implementing this interface. void swapframeloaders( in nsiframeloaderowner aotherowner ); parameters aotherowner the other frame loader owner with which to swap frame loaders. exceptions thrown ns_error_dom_security_err if the swap is not allowed on security grounds. ns_error_not_implemented if the swapping logic is not implemented for the either the current frame loader owner or the specified one with which you're trying to swap. see also nsiframeloader ...
nsIFrameMessageListener
s interface is used when implementing out-of-process handling of frames; the process handling a frame should implement this interface in order to receive messages. method overview void receivemessage(); methods receivemessage() note: this method is for javascript only. called to deliver a message to the frame handling process; called with one parameter, which has the following properties: name the name of the message. sync a boolean value indicating whether or not the message should be handled synchronously. if true, the response should be returned in the specified json object. json the json object in which to return the response if the message is being handled synchronously. objects unimplemented an array of ...
nsIHTMLEditor
etoinsert selectelement() set the selection at the suppled element. void selectelement( in nsidomelement aelement ); parameters aelement an element in the document. setbackgroundcolor() set the value of the "bgcolor" attribute on the document's <body> element. void setbackgroundcolor( in astring acolor ); parameters acolor the html color string, such as "#ffccff" or "yellow" setbodyattribute() set an attribute on the document's <body> element such as text, link, background colors. void setbodyattribute( in astring aattr, in astring avalue ); parameters aattr the attribute to be set. avalue the value of the attribute. setcaretafterelement() create a collapsed selection just after aelement. the selection is set to parent-of-aelement with an offset ...
nsIHTTPHeaderListener
inherits from: nsisupports last changed in gecko 1.9 (firefox 3) note: the plugin author must provide an instance to {geturl,posturl}() that implements both nsipluginstreamlistener and nsihttpheaderlistener. this instance is passed in through {geturl,posturl}()'s streamlistener parameter. the browser will then qi this streamlistener to see if it implements nsihttpheaderlistener. ...
nsIHttpActivityObserver
ed by nsisockettransport. if the activity type is activity_type_http_transaction, this will be one of the constants specified in activity subtype constants above. atimestamp the time at which the activity occurred, specified as microseconds elapsed since the epoch of midnight on january 1, 1970. aextrasizedata any additional size data available with this activity. see interpreting activity data below. aextrastringdata any additional string data available with this activity. see interpreting activity data below. interpreting activity data depending on the values of the aactivitytype and aactivitysubtype fields, the aextrasizedata and aextrastringdata parameters take on different meanings. socket transport activity when the activity type is activity_type_socket_transport and the subtype is sta...
nsIINIParser
xample provides a function you can call to obtain the value for a specific key in a given ini file. /** * returns the value for a given property in an ini file * @param {nsifile} inifile * the ini file to get the value from * @param {string} section * the name of the section in the ini file. ini sections are * defined by square brakets and look like this: [settings] * all entries below such a section definition belong to that * section (until the next section). * @param {string} prop * the name of the property to get. */ function getinivalue (inifile, section, prop) { var inifact = components.manager.getclassobjectbycontractid( "@mozilla.org/xpcom/ini-parser-factory;1", components.interfaces.nsiiniparserfactory ); var iniparser = inifact.createiniparser(in...
nsIINIParserFactory
that you can use to parse it. nsiiniparser createiniparser( in nsilocalfile ainifile ); parameters ainifile the ini file to parse. return value the nsiiniparser object you can use to parse the ini file. ...
nsIINIParserWriter
nsiiniparserwriter xpcom/ds/nsiiniparser.idlscriptable allows writing to an ini-format configuration file. 1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 13.0 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10) this interface provides methods that allow writing to ini-format configuration files. ini files contain zero or more sections, denoted by a name in square brackets, followed by zero or more lines of text with a property name on the left, then an equals sign ("="), then the value of the property. to create an nsiiniparserwriter object, you use the nsiiniparserfactory interface to create a parser, then nsisupports.queryinterface() that to get an nsiiniparserwriter, like this: let writer = components.classes["@mozi...
nsIInterfaceRequestor
interface(). the main difference is that interfaces returned are not required to provide a way back to the object implementing nsiinterfacerequestor. the semantics of nsisupports.queryinterface() dictate that given an interface a that you nsisupports.queryinterface() on to get to interface b, you must be able to nsisupports.queryinterface() on b to get back to a. nsiinterfacerequestor, however, allows you to obtain an interface c from a that may (or most likely) will not have the ability to get back to a. method overview void getinterface(in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result); methods getinterface() retrieves the specified interface pointer. void getinterface( in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result ); parameters uuid the iid of the i...
nsIJSID
an unnamed jsid also results when you implement a function that is passed an nsiidref parameter, such as queryinterface(). ...
nsIJetpack
essage. note: multiple callbacks may be registered for the same message; they will all be triggered. void registerreceiver( in astring amessagename, in jsval areceiver ); parameters amessagename the name of the message from the jetpack process on which the callback is triggered. areceiver a javascript function. the first argument passed to it is the name of the message, and all arguments following it are either json-serializable types or handles. if the message was sent synchronously from the jetpack process via callmessage(), then the return value of this function is passed back to the jetpack process. unregisterreceiver() this unregisters a callback previously registered with registerreceiver() void unregisterreceiver( in astring amessagename, in jsval areceiver ); parameters a...
nsIJumpListBuilder
) jump lists are built and then applied. modifying an applied jump list is not permitted. callers should begin the creation of a new jump list using initlistbuild(), add sub lists using addlisttobuild(), then commit the jump list using commitlistbuild(). lists are built in real-time during the sequence of build calls, make sure to check for errors on each individual step. the default number of allowed items in a jump list is ten. users can change the number through system preferences. user may also pin items to jump lists, which take up additional slots. applications do not have control over the number of items allowed in jump lists; excess items added are dropped by the system. item insertion priority is defined as first to last added. users may remove items from jump lists after they are c...
nsILivemarkService
teuri nsiuri object representing the site uri, or null to clear the site uri for this livemark container. exceptions thrown ns_error_invalid_arg if the folder id isn't known or identifies a folder that isn't a livemark container; also if the siteuri argument isn't a valid nsiuri object (or null) start() this method starts the livemark refresh timer. being able to manually control this allows activity such as bookmarks import to occur without kicking off http traffic. void start(); parameters none. stopupdatelivemarks() stop the livemark refresh timer. void stopupdatelivemarks(); parameters none. see also places livemark service nsinavbookmarksservice ...
Using nsILoginManager
rking with the login manager extensions often need to securely store passwords to external sites, web applications, and so on. to do so securely, they can use nsiloginmanager, which provides for secure storage of sensitive password information and nsilogininfo, which provides a way of storing login information. getting nsiloginmanager to get a component implementing nsiloginmanager, use the following: var passwordmanager = components.classes["@mozilla.org/login-manager;1"].getservice( components.interfaces.nsiloginmanager ); most login manager functions take an nsilogininfo object as a parameter. an nsilogininfo object contains the following attributes: hostname, form submit url, http realm, username, username field, password, and password field. the hostname, username and password at...
nsILoginManager
the login manager's data store, returning an array of matching logins. if there are no matching logins, an empty array is returned. void searchlogins( out unsigned long count, in nsipropertybag matchdata, [retval, array, size_is(count)] out nsilogininfo logins ); parameters count the number of elements in the returned array. matchdata the data used for the search. this does not follow the same requirements as findlogins() for those fields; wildcard matches are not specified. logins an array of matching nsilogininfo objects. example this method can be called from javascript like this: var logins = myloginmgr.searchlogins({}, matchdata); var numlogins = logins.length; setloginsavingenabled() enables or disables storing logins for a specified host. when login storing i...
nsIMessageListener
ssagesender interfaces. listeners are attached using the nsimessagelistenermanager interface. methods void receivemessage(); receivemessage() this is for js only. this function receives a message from one of the three message-sending functions in the message manager framework: broadcastasyncmessage sendasyncmessage sendsyncmessage. the received message is an object with the following properties: target the target of the message. either an element owning the message manager, or the message manager itself if no element owns it. if the message was sent from a frame script using a nsicontentframemessagemanager, then this property is the xul <browser> element for the frame from which the message was sent. name the message name. this is the f...
nsIMimeConverter
inherits from: nsisupports implemented by: @mozilla.org/messenger/mimeconverter;1. ...
nsIMsgCustomColumnHandler
it can be used in the thunderbird threadpane for extensions to overlay their own columns. mailnews/base/public/nsimsgcustomcolumnhandler.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsitreeview this interface is meant to be implemented by extensions, as shown in the tutorial. the interface inherits from nsitreeview, however when you're implementing a custom handler in javascript its not necessary to implement all of nsitreeview's methods. ...
nsIMsgDBViewCommandUpdater
us(); parameters none. displaymessagechanged() called 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. ...
nsIMsgHeaderParser
if they are already in either addrs or other_addrs. (if other_addrs contain addresses which are not in addrs, they are not added. that argument is for passing in addresses that were already mentioned in other header fields.) addresses are considered to be the same if they contain the same mailbox part (case-insensitive.) real names and other comments are not compared. removealiasestome allows the address parser to use the preference which contains regular expressions which also mean 'me' for the purpose of stripping the user's email address(es) out of addrs string removeduplicateaddresses( in string addrs, in string other_addrs, in prbool removealiasestome ); parameters addrs the addresses to remove duplicates from. other_addrs other addresses that the duplicate remova...
nsIMsgIncomingServer
ng helper function to construct the pretty name in a server type specific way - for example, mail for foo@test.com, news on news.mozilla.org. read only. defaultcopiesandfoldersprefstoserver boolean if the server supports fcc/sent/etc, default prefs can point to the server. otherwise, copies and folders prefs should point to local folders. by default this value is set to true via global pref 'allows_specialfolders_usage' (mailnews.js). for nntp, the value is overridden to be false. if isps want to modify this value, they should do that in their rdf file by using this attribute. please look at mozilla/mailnews/base/ispdata/aol.rdf for usage example. displaystartuppage boolean dobiff boolean downloadmessagesatstartup boolean read only. downloadonbiff boolean downloadsettings n...
nsIMsgProtocolInfo
oolean unused. read only. requiresusername boolean true if the server requires a username to log on. read only. serveriid nsiidptr the iid of the server-specific interface, used during account creation. read only. showcomposemsglink boolean true if compose ui actions should be enabled for the account type. read only. specialfoldersdeletionallowed boolean true if the user can delete folders like inbox, trash, etc. read only. methods getdefaultserverport() 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...
nsIMsgSearchSession
to create an instance, use: var searchsession = components.classes["@mozilla.org/messenger/searchsession;1"] .createinstance(components.interfaces.nsimsgsearchsession); to use the instance append search terms, set the scope, and then call search(). ...
nsIMsgWindow
fault message window is stored in the global variable msgwindow. method overview void displayhtmlinmessagepane(in astring title, in astring body, in boolean clearmsghdr); void stopurls(); void closewindow(); attributes attribute type description windowcommands nsimsgwindowcommands this allows the backend code to send commands to the ui, such as clearmsgpane. statusfeedback nsimsgstatusfeedback this allows the backend code to send status feedback to the ui. msgheadersink nsimsgheadersink this allows the backend code to send message header information to the ui. transactionmanager nsitransactionmanager ...
nsIObserver
t common implementation of nsiobserverservice is the xpcom observer service. with this implementation, it's safe (and common practice) for an implementation of nsiobserver to remove itself as an observer during the observe callback, or to add or remove other observers. be careful, though, because other uses of nsiobserver may not support these operations correctly within observe. example the following code is an implementation of nsiobserver that is registered to receive notifications for the "mytopicid" topic. see observer notifications for a list of built-in topics possible. observing preferences works slightly differently. see code snippets:preferences - using preference observers for an example. function myobserver() { this.register(); } myobserver.prototype = { observe: function...
nsIPluginHost
y!destroy void destroy(); parameters none. native code only!findproxyforurl fetches a url. (corresponds to npn_geturl and npn_geturlnotify.) posts to a url with post data and/or post headers. (corresponds to npn_posturl and npn_posturlnotify.) returns the 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 ...
nsIPrefBranch2
in gecko 13 this interface was merged into the nsiprefbranch interface. method overview void addobserver(in string adomain, in nsiobserver aobserver, in boolean aholdweak); void removeobserver(in string adomain, in nsiobserver aobserver); methods addobserver() add a preference change observer. on preference changes, the following arguments will be passed to nsiobserver.observe(): asubject - the nsiprefbranch object (this). atopic - the string defined by ns_prefbranch_prefchange_topic_id adata - the name of the preference which has changed, relative to the "root" of the asubject branch. asubject.get*pref(adata) will get the new value of the modified preference. for example, if your observer is registered with addobserver("bar.", ...) on a branch with ...
nsIPrefService
modules/libpref/public/nsiprefservice.idlscriptable this interface is the main entry point into the back end preferences management library. the preference service is directly responsible for the management of the preferences files and also facilitates access to the preference branch object which allows the direct manipulation of the preferences themselves. inherits from: nsisupports last changed in gecko 1.7 method overview nsiprefbranch getbranch(in string aprefroot); nsiprefbranch getdefaultbranch(in string aprefroot); void readuserprefs(in nsifile afile); void resetprefs(); void resetuserprefs(); void savepreffile(in nsifile afile); methods getbranch() call to get a preferences "branch" which accesses user pr...
nsIPushSubscription
long long the last time a message was sent to this subscription, in milliseconds since the epoch. quota long the number of remaining background messages for this subscription, or -1 if exempt. methods getkey() returns a byte array containing the key material for this subscription. the remote server can use these keys to encrypt and authenticate message payloads. the following key names are supported: p256dh the ecdh public key, used as the input keying material in the hkdf invocation during encryption. auth the shared authentication secret, used as the salt in the hkdf invocation. void getkey( in domstring name, [optional] out uint32_t keylen, [array, size_is(keylen), retval] out uint8_t key ); parameters name the encrypt...
nsIResumableChannel
ple 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. similarly, the status of this channel during onstartrequest may be ns_error_entity_changed, which indicates that the entity has changed, as indicated by a changed entityid. in both of these cases, 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 ...
nsISHistory
finished loading. when the document finishes loading the value -1 is returned. read only. shistoryenumerator nsisimpleenumerator called to obtain a enumerator for all the documents stored in session history. the enumerator object thus returned by this method can be traversed using nsisimpleenumerator. to access individual history entries of the enumerator, perform the following steps: call getshistoryenumerator() to obtain handle the nsisimpleenumerator object. use nsisimpleenumerator.getnext() on the object returned by step #1 to obtain handle to the next object in the list. the object returned by this step is of type nsisupports. perform a queryinterface on the object returned by step #2 to nsishentry. use nsishentry to access properties of...
nsIScreen
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. lockminimumbrightness() locks the minimum brightness of the screen, preventing it from becoming any dimmer than that brightness level. each call to this method must eventually be followed by a corresponding call to unlockminimumbrightness() with the same value for the brightness parameter. void lockminimumbrightness( in unsigned long brightness ); parameters brightness the new minimum brightness level; this must be one of the values specified in screen brightness constants. unlockminimumbrightness() releases a lock on the minimum brightness of the screen, which was ...
nsIScriptableInputStream
eturn value the number of bytes. exceptions thrown ns_base_stream_closed if called after the stream has been closed. close() closes the stream. note: the close method may be called more than once, but subsequent calls are ignored. void close(); parameters none. init() wrap the given nsiinputstream with this nsiscriptableinputstream. note: the init method may be called more than once, allowing a nsiscriptableinputstream instance to be reused. void init( in nsiinputstream ainputstream ); 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.
nsIScriptableUnicodeConverter
if the other apis you are reading data from or writing data to don't require you to use this legacy representation, you should use textdecoder and textencoder (available to chrome javascript via components.utils.importglobalproperties) instead of this api. intl/uconv/idl/nsiscriptableuconv.idlscriptable this interface is a unicode encoder for use by scripts. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: @mozilla.org/intl/scriptableunicodeconverter. ...
nsISearchEngine
ring responsetype, [optional] in astring purpose ); parameters data data to add to the submission object. that is the search terms. responsetype [optional] the mime type that we'd like to receive in response to this submission. if 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 ...
nsISelectionController
ard or backwards in selection. scrollpage() will scroll the page without affecting the selection. void scrollpage( in boolean forward ); parameters forward scroll forward or backwards in selection. scrollselectionintoview() scrolls a region of the selection, so that it is visible in the scrolled view. note: if issynchronous is true, calling this method may flush the pending reflow. this is dangerous for some objects. see bug 418470, comment 12 for details. void scrollselectionintoview( in short type, in short region, in short flags ); parameters type the selection to scroll into view. (selectiontype) region the region inside the selection to scroll into view. (selectionregion) flags one of the scroll_* constants. exception...
nsISocketProvider
ssed in this interface will be used instead of the address structure passed for a later request. anonymous_connect 1 << 1 when setting this flag, the socket will not apply any credentials when establishing a connection. for example, an ssl connection would not send any client-certificates if this flag is set. methods native code only!addtosocket this function is called to allow the socket provider to layer a prfiledesc (a file descriptor) on top of another prfiledesc. for example, ssl via a socks proxy. parameters are the same as newsocket() with the exception of afiledesc, which is an input parameter instead. void addtosocket( in long afamily, in string ahost, in long aport, in string aproxyhost, in long aproxyport, in unsigned long aflags, in prfiledescs...
nsITXTToHTMLConv
inherits from: nsistreamconverter last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by "@mozilla.org/streamconv;1?from=text/plain&to=text/html". you should normally obtain an instance via the nsistreamconverterservice interface. method overview void preformathtml(in boolean value); void settitle(in wstring text); prior versions of the interface named the methods using the initialcaps style instead of the intercaps style. methods preformathtml() specifies whether or not to wrap the resulting html in an <pre> block. ...
nsITaskbarPreview
ected) 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 domstring a string containing the text displayed in the tooltip above the preview when the user hovers over it. by default, this is an empty string. ...
nsITaskbarPreviewButton
1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) you can't directly instantiate this interface. instead, you use the nsitaskbarwindowpreview.getbutton() to get the objects representing the buttons. ...
nsITaskbarPreviewController
ton button); void onclose(); attributes attribute type description height unsigned long the height in pixels of the preview image. this value may change at any time. see drawpreview() for more information. read only. thumbnailaspectratio float the thumbnail's aspect ratio. this doesn't need to match the preview's aspect ratio, and is allowed to be changed at any time. see drawthumbnail() for more information. read only. width unsigned long the width in pixels of the preview image. this value may change at any time. see drawpreview() for more information. read only. note: although these attributes are read only, that indicates that the previews controlled by an nsitaskbarpreviewcontroller cannot alter these val...
nsITaskbarTabPreview
fennec 1.0) tab preview support is disabled by default in gecko 1.9.2 creating an nsitaskbartabpreview for a window will automatically hide that window's nsitaskbarwindowpreview; this is done by windows and cannot be prevented. when there are no more tab previews left for a window, the window preview is automatically made visible again. an application may have as many tab previews as memory allows. you can't directly instantiate this interface; instead, call the nsiwintaskbar.createtaskbartabpreview(). method overview void ensureregistration(); violates the xpcom interface guidelines nativewindow gethwnd(); violates the xpcom interface guidelines void move(in nsitaskbartabpreview anext); attributes attribute type description ic...
nsITextInputProcessorNotification
.35) this interface tells details of a request or notification to ime. when gecko supports new notification to ime, this interface may have some new attributes. so, nsitextinputprocessorcallback won't be changed for keeping backward compatibility. attributes attribute type description type acstring the type of request or notification to ime. see type values below. types "request-to-commit" this is required to be handled. when this is requested, the callback should commit composition synchronously, i.e., nsitextinputprocessor.commitcomposition() should be called. if the callback doesn't want to commit the composition synchronously, it's okay to commit it later (i.e., asynchronously). however, gecko will commit the composition with the last compo...
nsIThread
lled when this thread wasn't the current thread. processnextevent() processes the next pending event. if there aren't any pending events, this method may wait -- depending on the value of the maywait parameter -- until an event is dispatched to the thread. this method is re-entrant but may only be called if this thread is the current thread. warning: calling nsithread.processnextevent allows network and ui events to run which can modify data structures that your code isn't expecting to be modified during a synchronous method call. this can cause random crashes and other bugs that may be hard to find and fix. consider use asynchronous callbacks instead. boolean processnextevent( in boolean maywait ); parameters maywait if true, this method blocks until an event is available...
nsIThreadObserver
nextevent() before an event is processed. this method is only called on the target thread. it is valid to change the thread\'s observer during a call to this method. void onprocessnextevent( in nsithreadinternal thread, in boolean maywait, in unsigned long recursiondepth ); parameters thread the nsithread on which the event is going to be processed. maywait true if the method is allowed to block the calling thread. this parameter will be false during thread shutdown. recursiondepth the number of calls to nsithread.processnextevent() on the call stack in addition to the current call. example it is possible to overlay processing events for a gui toolkit on top of the events for a thread: var nativequeue; observer = { ondispatchedevent(thread) { nativequeue.signal(); ...
nsIThreadPool
the thread pool takes ownership of the listener and releases it when the shutdown() method is called. threads created after the listener is set will also take ownership of the listener so that the listener will be kept alive long enough to receive the guaranteed nsithreadpoollistener.onthreadshuttingdown() notification. threadlimit unsigned long the maximum number of threads allowed at once in the pool; you may change this value by altering this attribute. methods shutdown() shuts down the thread pool. you must not call this method from any thread within the thread pool. instead, you should call it from another thread (typically the one that created the thread pool). when this method returns, the thread pool and all its threads will have been shut down, and it i...
nsIToolkitProfileService
toolkit/profile/public/nsitoolkitprofileservice.idlscriptable the profile service manages user profiles. inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) note: starting in gecko 1.9.1, this service is implemented by @mozilla.org/toolkit/profile-service;1. to access the service, you can use the following code: var toolkitprofileservice = components.classes["@mozilla.org/toolkit/profile-service;1"] .createinstance(components.interfaces.nsitoolkitprofileservice); prior to gecko 1.9.1 only the built-in profile manager was able to access the toolkit profile service. to access the built-in profile manager in versions of firefox up to 4.0 and thunderbird up to 3.3 you can launch with the -profileman...
nsITransactionManager
one. the listener's nsitransactionlistener.addref() method is called. void addlistener( in nsitransactionlistener alistener ); parameters alistener the nsitransactionlistener to add. beginbatch() turns on the transaction manager's batch mode, forcing all transactions executed by the transaction manager's dotransaction() method to be aggregated together until endbatch() is called. this mode allows an application to execute and group together several independent transactions so they can be undone with a single call to undotransaction(). void beginbatch(); parameters none. clear() clears the undo and redo stacks. void clear(); parameters none. dotransaction() calls a transaction's nsitransaction.dotransaction() method, then pushes it on the undo stack. this method calls the transaction's ...
nsITreeBoxObject
hich rows were removed. count the number of rows added or removed. use negative values for removed rows. example you deleted the row with index rowindex. inform the tree about this change by calling rowcountchanged(rowindex+1, -1); beginupdatebatch() notify the tree that the view is about to perform a batch update, that is, add, remove or invalidate several rows at once. this must be followed by calling endupdatebatch(), otherwise the tree will get out of sync. void beginupdatebatch(); endupdatebatch() notify the tree that the view has completed a batch update. void endupdatebatch(); clearstyleandimagecaches() called on a theme switch to flush out the tree's style and image caches. void clearstyleandimagecaches(); other references tree widget changes (applies to gecko 1.8.0 ...
nsIURIFixup
xposableuri(in nsiuri auri); nsiuri createfixupuri(in autf8string auritext, in unsigned long afixupflags); nsiuri keywordtouri(in autf8string akeyword); nsiurifixupinfo getfixupuriinfo(in autf8string auritext, in unsigned long afixupflags); constants constant value description fixup_flag_none 0 no fixup flags. fixup_flag_allow_keyword_lookup 1 allow the fixup to use a keyword lookup service to complete the uri. the fixup object implementer should honour this flag and only perform any lengthy keyword (or search) operation if it is set. fixup_flags_make_alternate_uri 2 tell the fixup to make an alternate uri from the input uri, for example to turn foo into www.foo.com. fixup_flag_use_utf8 ...
nsIURIFixupInfo
ting what we found/corrected when fixing up a uri. inherits from: nsisupports last changed in gecko 1.7 attributes attribute type description consumer nsisupports consumer that asked for the fixed up uri. preferreduri nsiuri best guess of what uri consumer expects. may be null if we can't deliver (eg. the input is an invalid uri and fixup_flag_allow_keyword_lookup is not passed). read only. fixeduri nsiuri 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. ...
nsIURLFormatter
tter.idlscriptable this interface exposes methods to substitute variables in url formats. 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) variable names can contain 'a-z' letters and '_' characters. mozilla applications linking to mozilla websites are strongly encouraged to use urls of the following format: http[s]://%service%.mozilla.[com|org]/%locale%/ method overview astring formaturl(in astring aformat); astring formaturlpref(in astring apref); methods formaturl() formats a string url. the set of known variables is predefined. if a variable is unknown, it is left unchanged and a non-fatal error is reported. astring formaturl( in astring aformat ); parameters...
nsIURLParser
netwerk/base/public/nsiurlparser.idlscriptable specifies the interface to an url parser that attempts to follow the definitions of rfc 2396. inherits from: nsisupports last changed in gecko 1.7 method overview void parseauthority(in string authority, in long authoritylen, out unsigned long usernamepos, out long usernamelen, out unsigned long passwordpos, out long passwordlen, out unsigned long hostnamepos, out long hostnamelen, out long port); void parsefilename(in string filename, in long filenamelen, out unsigned long basenamepos, out long basenamelen, out unsigned long extensionpos, out long extensionlen); void parsefilepath(in string filepath, in long filepathlen, out unsigned long directorypos, out long directorylen, out unsigned long basenamepos, out long basename...
nsIUTF8StringEnumerator
inherits from: nsisupports last changed in gecko 1.7 method overview autf8string getnext(); boolean hasmore(); methods getnext() returns the next string in the enumerator. the "next" element is the first string upon the first call. must be preceded by a call to hasmore(), 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. ...
nsIUpdate
ring the toolkit version of this update. previousappversion astring the application version prior to the application being updated. selectedpatch nsiupdatepatch the currently selected patch for this update. read only. serviceurl astring the url to the update service that supplied this update. showneverforversion boolean whether to show the "no thanks" button in the update prompt. this allows the user to never receive a notification for that specific update version again. showprompt boolean whether to show the update prompt which requires user confirmation when an update is found during a background update check. this overrides the default setting to download the update in the background. showsurvey boolean whether to show the survey link in the update prompt. the url must also...
nsIVersionComparator
b" is "+" then "number-a" is incremented by 1 and "string-b" becomes "pre". 1.0pre1 < 1.0pre2 < 1.0 == 1.0.0 == 1.0.0.0 < 1.1pre == 1.1pre0 == 1.0+ < 1.1pre1a < 1.1pre1 < 1.1pre10a < 1.1pre10 implemented by: @mozilla.org/xpcom/version-comparator;1. the service can be accessed directly via services.vc after loading services.jsm or with the following code: var versioncomparator = components.classes["@mozilla.org/xpcom/version-comparator;1"] .getservice(components.interfaces.nsiversioncomparator); method overview long compare(in acstring a, in acstring b); methods compare() compare two version strings. long compare( in acstring a, in acstring b ); parameters a the first version...
nsIWeakReference
inherits from: nsisupports last changed in gecko 0.9.9 an instance of nsiweakreference is a proxy object that cooperates with its referent to give clients a non-owning, non-dangling reference. clients own the nsiweakreference instance. ...
nsIWebBrowserChrome
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 parent. this flag is only meaningful if chrome_openas_chrome is set; content windows should not be dependent. chrome_modal 536870912 the modal style bit just affects the way the window looks...
nsIWebBrowserFindInFrames
ch to start the search. once the search is done, this will be set to be the last frame searched, whether or not a result was found. has to be equal to or contained within the rootsearchframe. rootsearchframe nsidomwindow frame within which to confine the search (normally the content area frame). set this to only search a subtree of the frame hierarchy. searchparentframes boolean whether to allow the search to propagate out of the currentsearchframe into its parent frame(s). search is always confined within the rootsearchframe. default is true. setting nsiwebbrowserfind.searchframes to true sets this to true. searchsubframes boolean whether to recurse down into subframes while searching. default is true. setting nsiwebbrowserfind.searchframes to true sets this to true. see also nsi...
nsIWebPageDescriptor
inherits from: nsisupports last changed in gecko 1.7 method overview void loadpage(in nsisupports apagedescriptor, in unsigned long adisplaytype); attributes attribute type description currentdescriptor nsisupports retrieves the page descriptor for the current document. read only. constants display type constants constant value description display_as_source 0x0001 generates an optionally syntax-highlighted (for xml/html documents) source of the original page. ...
nsIWebProgress
); attributes attribute type description domwindow nsidomwindow the dom window associated with this nsiwebprogress instance. read only. exceptions thrown ns_error_failure indicates that there is no associated dom window. isloadingdocument prbool indicates whether or not a document is currently being loaded in the context of this nsiwebprogress instance. read only. constants the following flags may be combined to form the anotifymask parameter for the addprogresslistener() method. they limit the set of events that are delivered to an nsiwebprogresslistener instance. these flags indicate the state transistions to observe, corresponding to nsiwebprogresslistener.onstatechange(). constant value description notify_state_request 0x00000001 only receive the nsiwebprogresslistene...
nsIWebSocketChannel
that the original pre-redirect uri can still be obtained. this is never null. read only. protocol acstring sec-websocket-protocol value. securityinfo nsisupports transport-level security information (if any). read only. uri nsiuri the uri corresponding to the protocol connection after any redirections are completed. read only. status codes the following values are permitted status codes. status code name description 0-999 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...
nsIWinAppHelper
.getservice(components.interfaces.nsiwinapphelper); the nsixulappinfo and nsixulruntime interfaces are also implemented 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 ...
nsIWindowsRegKey
meaning of these value types. this interface is somewhat restricted to using only these value types. there is no method that is directly equivalent to regqueryvalueex or regsetvalueex. in particular, this interface does not support the reg_multi_sz and reg_expand_sz value types. it is still possible to enumerate values that have other types (that is, getvaluetype() may return a type not defined below). constant value description type_none 0 reg_none type_string 1 reg_sz type_binary 3 reg_binary type_int 4 reg_dword type_int64 11 reg_qword methods close() this method closes the key. if the key is already closed, then this method does nothing. void close(); parameters none. create() this method open...
nsIWorker
3.0 / seamonkey 2.0) for usage details, see worker and the article using dom workers. method overview void postmessage(in domstring amessage, [optional] in nsiworkermessageport amessageport); attributes attribute type description onmessage nsidomeventlistener an object to receive notifications when messages are received on the worker's message port. methods postmessage() used to allow the worker to send a message back to the web application that created it. void postmessage( in domstring amessage, in nsiworkermessageport amessageport optional ); parameters amessage the message the worker wishes to post back to its creator. amessageport a message port on which to post the message; if not specified, the default message port is used. ...
nsIWorkerGlobalScope
1.0 66 introduced gecko 1.9.1 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) attributes attribute type description location nsiworkerlocation read only. navigator nsiworkernavigator read only. onerror nsidomeventlistener self nsiworkerglobalscope returns the global scope object itself. ...
nsIWorkerMessagePort
1.0 66 introduced gecko 1.9.1 inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) method overview void postmessage(in domstring amessage); methods postmessage() posts a message into the event queue. void postmessage( in domstring amessage ); parameters amessage the message to post. ...
nsIWorkerScope
message(in domstring amessage, [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 me...
nsIXMLHttpRequest
r, please refer to the xmlhttprequest documentation instead. this page contains documentation, specific to mozilla application and add-on developers. the interface definition: //github.com/realityripple/uxp/blob/master/dom/xhr/nsixmlhttprequest.idl elevated privileges as mentioned in the "non-standard properties" the property of channel was read-only. when using the xpcom interface, as seen below in example 2, we can get access to this. the most obvious benefit is that we can set nsirequest - constants in the xhr.channel.loadflags. for instance, as done in example 2, the flag of load_anonymous is added, this strips all user data (cookies, tokens, etc). using event handlers from native code (not sure if it's up-to-date) from native code, the way to set up onload and onerror handlers is ...
nsIXMLHttpRequestEventTarget
r. onerror nsidomeventlistener a javascript function object that gets invoked if the operation fails to complete due to an error. onload nsidomeventlistener a javascript function object that gets invoked when the operation is successfully completed. onloadend nsidomeventlistener a javascript function object that gets invoked when the operation is completed for any reason; it will always follow a an abort, error, or load event. onloadstart nsidomeventlistener a javascript function object that gets invoked exactly once when the operation begins. onprogress nsidomeventlistener a javascript function object that gets invoked zero or more times, after the loadstart event, but before any abort, error, or load events occur. handling the events when the handler functions for these events...
nsIXULAppInfo
ant. read only. id acstring the xul application's uuid. can be an empty string, if id is not set. has to be defined for advanced application features such as the extension manager and update service. this has traditionally been in the form "{aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee}" but for new applications a more readable form is encouraged: "appname@vendor.tld". only the following characters are allowed: a-z a-z 0-9 - . @ _ { } * read only. name acstring the name of the application. this must be ascii, and is normally mixed-case, for example "firefox", "thunderbird" or "seamonkey". must not be null or an empty string. read only. platformbuildid acstring the build id/date of gecko and the xulrunner platform. read only. platformversi...
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. ...
nsIXULSortService
de a node in the xul widget whose children are to be sorted. ...
nsIXULWindow
er 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. constants constant value description lowestz 0 loweredz 4 the z level of an independent window opened with the "alwayslowered" chrome flag. normalz 5 the default z level of an independent window. raisedz 6 the z level...
nsIXmlRpcClient
pportsprint16, nsisupportsprint32: i4, nsisupportsprbool: boolean, nsisupportschar, nsisupportscstring: string, nsisupportsfloat, nsisupportsdouble: double, nsisupportsprtime: datetime.iso8601, nsiinputstream: base64, nsisupportsarray: array, nsidictionary: struct note that both nsisupportsarray and nsidictionary can only hold any of the supported input types. return value will be converted as follows: i4 or int: nsisupportsprint32 boolean: nsisupportsprbool string: nsisupportscstring double: nsisupportsdouble datetime.iso8601: nsisupportsprtime base64: nsisupportscstring array: nsisupportsarray struct: nsidictionary faults (server side errors) are indicated by returning ns_error_failure. via nsixpconnect::getpendingexception()->data a nsixmlrpcfault object can be retreieved with more informa...
nsIZipWriter
le/in/zip archive", components.interfaces.nsizipwriter.compression_default, thefile, false); zipw.close(); the argument myzipfilepath isn't a path but rather it has to be an nsifile instance specifying the location of the new zip file. the file need not exist, but the directory that contains it (nsifile.parent) must exist. recursively add all contents of a directory to zip file this example below can be copied and pasted into your scratchpad, set the environment to "browser" and can run. what it does is shows a file picker dialog and asks you to pick a folder. once you pick a folder, it will create a zip file inside this folder with the same name as the folder. it will then recursively go through all contents in the folder selected and add them into this zip file. this example is also a g...
nsMsgPriorityValue
defined in comm-central/ mailnews/ base/ public/ mailnewstypes2.idl typedef long nsmsgpriorityvalue; [scriptable, uuid(94c0d8d8-2045-11d3-8a8f-0060b0fc04d2)] interface nsmsgpriority { const nsmsgpriorityvalue notset = 0; const nsmsgpriorityvalue none = 1; const nsmsgpriorityvalue lowest = 2; const nsmsgpriorityvalue low = 3; const nsmsgpriorityvalue normal = 4; const nsmsgpriorityvalue high = 5; const nsmsgpriorityvalue highest = 6; // the default for a priority picker const nsmsgpriorityvalue default = 4; }; ...
nsMsgSearchOp
hopvalue is = 2; /* is and isn't also apply to some non-text attrs */ const nsmsgsearchopvalue isnt = 3; const nsmsgsearchopvalue isempty = 4; const nsmsgsearchopvalue isbefore = 5; /* for date attributes */ const nsmsgsearchopvalue isafter = 6; const nsmsgsearchopvalue ishigherthan = 7; /* for priority. ...
NS_IF_RELEASE
this page still needs some work, help to improve it! summary macro decrements the reference count of a pointer by one. this macro also sets the pointer to null. ...
XPCOM primitive
primitives are rarely useful. the main use case is to store primitive values in a data structure that can only store xpcom objects, such as nsiarray. also, certain apis, such as nsitransferable.settransferdata(), require primitives. ...
NS_CStringAppendData
#include "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. ...
NS_CStringCopy
« xpcom api reference summary the ns_cstringcopy function copies the value from one nsacstring instance to another. this is a low-level api. #include "nsstringapi.h" nsresult ns_cstringcopy( nsacstring& adeststring, const nsacstring& asrcstring ); parameters adeststring [in] a nsacstring instance to be modified. asrcstring [in] a nsacstring instance containing the new string value. return values the ns_cstringcopy function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is designed to allow the implementation to efficiently assign the same value to two string objects. the implementation may employ reference counting techniques to optimize this operation. example /* attribute acstring value; */ ns_imethodimp mycompone...
NS_CStringCutData
#include "nsstringapi.h" nsresult ns_cstringcutdata( nsacstring& astring, pruint32 acutstart, pruint32 acutlength ); parameters astring [in] a nsacstring instance to be modified. 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. pass pr_uint32_max to specify the length from acutstart to the end of the string. ...
NS_CStringGetMutableData
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 = ns_cstringgetmutabledata(str, pr_uint32_max, &iter); char *end = iter + len; while (iter != end) { char c = *iter; if (c >= 'a' && c <= 'z') *iter = c + ('a' - 'a'); ++iter; } } history this function was finalized for mozilla 1.8. see bug 288786 for details. see also ns_cstringgetdata ...
NS_CStringInsertData
#include "nsstringapi.h" nsresult ns_cstringinsertdata( nsacstring& astring, pruint32 aoffset, const char* adata, pruint32 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. ...
NS_CStringSetData
#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. ...
NS_CStringSetDataRange
#include "nsstringapi.h" nsresult ns_cstringsetdatarange( nsacstring& astring, pruint32 acutstart, pruint32 acutlength, const char* adata, pruint32 adatalength = pr_uint32_max ); parameters astring [in] a 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. ...
NS_StringAppendData
#include "nsstringapi.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. ...
NS_StringContainerFinish
#include "nsstringapi.h" void ns_stringcontainerfinish( nsstringcontainer& astring ); parameters astring [in] a nsstringcontainer instance that is no longer needed. return values this function does not return a value. ...
NS_StringContainerInit
#include "nsstringapi.h" nsresult ns_stringcontainerinit( nsstringcontainer& astring ); parameters astring [in] a nsstringcontainer instance to be initialized. return 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. ...
NS_StringCopy
removed by bug 1332639 « xpcom api reference summary the ns_stringcopy function copies the value from one nsastring instance to another. this is a low-level api. #include "nsstringapi.h" nsresult ns_stringcopy( nsastring& adeststring, const nsastring& asrcstring ); parameters adeststring [in] a nsastring instance to be modified. asrcstring [in] a nsastring instance containing the new string value. return values the ns_stringcopy function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is designed to allow the implementation to efficiently assign the same value to two string objects. the implementation may employ reference counting techniques to optimize this operation. example code /* attribute acstring va...
NS_StringCutData
#include "nsstringapi.h" nsresult ns_stringcutdata( nsastring& astring, pruint32 acutstart, pruint32 acutlength ); parameters astring [in] a nsastring instance to be modified. 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. pass pr_uint32_max to specify the length from acutstart to the end of the string. return values the ns_stringcutdata function returns ns_ok if successful. ...
NS_StringGetData
#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). ...
NS_StringInsertData
#include "nsstringapi.h" nsresult ns_stringinsertdata( nsacstring& astring, pruint32 aoffset, const prunichar* adata, pruint32 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. ...
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. ...
NS_StringSetDataRange
#include "nsstringapi.h" nsresult ns_stringsetdatarange( nsastring& astring, pruint32 acutstart, pruint32 acutlength, const prunichar* adata, pruint32 adatalength = pr_uint32_max ); parameters astring [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. ...
nsMsgSearchOpValue
and isn't also apply to some non-text attrs */ 153 const nsmsgsearchopvalue isnt = 3; 154 const nsmsgsearchopvalue isempty = 4; 155 156 const nsmsgsearchopvalue isbefore = 5; /* for date attributes */ 157 const nsmsgsearchopvalue isafter = 6; 158 159 const nsmsgsearchopvalue ishigherthan = 7; /* for priority. ...
The Thread Manager
sithread that is implemented by the xpcom thread object to add support for observing dispatch activity on a thread. nsithreadobserver provides the ability to monitor a thread, to receive notifications when events are dispatched to it and when they're finished being processed. nsithreadeventfilter this interface is used by the nsithreadinternal.pusheventqueue() method in nsithreadinternal to allow event filtering. nsirunnable this interface is the base for all events/runnable objects which are dispatched to threads. tutorials making cross-thread calls using runnables ...
XPCOM Thread Synchronization
mozilla::condvar mozilla::monitor mozilla::monitorautoenter mozilla::mutex mozilla::mutexautolock mozilla::mutexautounlock ...
Frequently Asked Questions
comptr.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 "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 sco...
XPCOM category image-sniffing-services
in versions of firefox prior to firefox 3, extensions could add decoders for new image types. however, such decoders relied on servers sending correct mime types; images sent with incorrect mime 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. ...
already_AddRefed
« xpcom api reference already_addrefed in association with nscomptr allows you to assign in a pointer without addrefing it. you may want to use this as a return type from a function that has already produced an addrefed pointer as a result. in fact, it is preferred to use already_addrefed in this case over returning a raw pointer or nscomptr (see the nscomptr user manual). defined in: mfbt/alreadyaddrefed.h. example ... already_addrefed<nsifoo> getfoo() { nsifoo* foo = mfoo; ns_if_addref(foo); return foo; } // or already_addrefed<nsifoo> getfoo() { nscomptr<nsifoo> foo = mfoo; // ... return foo.forget(); } ... // the following assignment doesn't perform an additional addref, // as it would do if getfoo() returned a raw pointer. nscomptr<nsifoo> foo = getfoo(); s...
nsCOMPtr versus RefPtr
t_iid) == mrawptr). do_queryinterface versus do_queryobject the do_queryinterface helper is only available when assigning to nscomptr. it also requires that the argument singly inherit from nsisupports (since the type of the argument is nsisupports*). for other cases, there is do_queryobject, which is essentially a more powerful form of do_queryinterface. it differs from do_queryinterface as follows: do_queryobject inherits from nscomptr_helper, so it can be assigned into both nscomptr and refptr. the downside of this inheritance is that do_queryobject requires an extra virtual call to operator() in the helper method. do_queryobject is templated on the argument type, so it's possible to pass in objects that multiply inherit from nsisupports. however, when the destination type is an xpco...
xpidl
Mozilla › Tech › XPIDL › xpidl
ll xpcom objects through xpconnect note: starting in gecko 9.0, xpidl has been replaced with pyxpidl in the gecko sdk. pyxpidl has been used for some time now, but now this older tool has been fully retired. xpidl is based on the libidl idl compiler from the gnome project. the libidl compiler depends on glib, also from the gnome project. the xpidl compiler is now part of the build process, allowing us to generate headers used by the xpcom components. please check the build documentation for further information on where to get libidl and glib. using xpidl to add an idl file to the build, use the xpidlsrcs makefile variable. for testing purposes, or one-off interface compilation, xpidl can be run from the command line: usage: ./xpidl -m mode [-w] [-v] [-t version number] [-d filename.pp...
XTF
Mozilla › Tech › XTF
for example, the mozilla xforms project uses xtf to add support for the xforms namespace. documentation xtf readme the xtf readme. xtf home the xtf home (outdated). xtf: when xbl just won't cut it more recent primer to xtf by alex vincent. extending gecko with xbl and xtf a presentation given at xtech 2005 comparing xbl and xtf, as well as discussing xtf basics. view all... ...
Xray vision
derlying instance has a different prototype. if a script has created a property on an object instance that shadows a property on the prototype, the shadowing property is not visible in the xray second, we want to prevent the chrome code from running content code, so functions and accessor properties 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 ...
The Valgrind Test Job
valgrind test job builds the browser and runs it under valgrind, which can detect various common memory-related errors. this job only runs on linux64, which is the platform best suited to running valgrind. running the valgrind test job locally valgrind works best on linux. it also works on mac, though sometimes not as well. building you need a valgrind-enabled build of firefox. add the following lines to your mozconfig file. ac_add_options --enable-valgrind ac_add_options --disable-jemalloc running to run the valgrind test job locally, run the following command. mach valgrind-test see also the general instructions for using valgrind with mozilla code. understanding errors for each problem that valgrind finds, it emits a message describing the problem, along with a stack trace ...
Cached compose window FAQ
k. close or send the window. (the compose window is now cached) do new message again. this is the cached compose window. it should have been faster than in step 2. close or send the window. (the compose window is cached again) do new message again. this is the cached compose window. it should be as fast as in step 4. do new message again. there is no "cached" window, so this will be as slow as step 4. close one of the compose windows. (this window is now cached). close the other compose window. (this window is not cached, since you already have a cached compose window.) do new message again. this is the cached compose window. it should be as fast as in step 4. do new message again. there is no "cached" window, so this will be as slow as step 4. we cache at most <n> html c...
nsIMsgCloudFileProvider
ningfilespace long long readonly: the remaining storage space available for this account in bytes. if this value is not known, returns -1. filespaceused long long readonly: the total amount of space used by this account. if this value is not known, returns -1. lasterror acstring readonly: the last error message received from the server. constants the following constants are used for the status codes passed to the onstoprequest functions of the nsirequestobserver's used by the asynchronous methods of nsimsgcloudfileprovider. constant value description offlineerr 0x80550014 returned when it appears that there is no active network connection. autherr 0x8055001e returned when authorizing has failed. ...
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 client architecture overview
ement msgdb imap/nntp/pop3 necko (networking) sections in grey refer to modules outside of mail/news the base module the base module provides a generic interface to a set of protocol-independant messaging services. this includes management of accounts, folders and messages. the base module consists of the following basic building blocks account management - the account manager is the root object of the server/folder/message hierarchy. it manages individual accounts on mail servers and the identity of users as used to send mail. folders - mail folders contain messages and folders. all folders have folder indexes. messages - messages are always stored and streamed in rfc822 format. whenever multiple m...
Mailbox
the mailbox protocol is used to read messages from a local folder berkeley mailbox. it consists of nsmailboxservice, nsmailboxurl, and nsmailboxprotocol. this may seem like a lot of infrastructure just to read messages from a flat file, but it allows us to do it asynchronously, and to have reading local messages fit into the same kind of mechanisms that reading nntp and imap messages do - running urls, getting onstart/stoprunningurl notifications when the url starts/stops, etc. the mailbox protocol is also used to regenerate a summary file, in conjunction with nsmsgmailboxparser ...
Thunderbird Configuration Files
ck the hide extensions 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 doc...
Building a Thunderbird extension 1: introduction
del. similar to firefox, thunderbird functionality can be enhanced and customized via extensions. warning: this content is for older versions of thunderbird. much of it may no longer be relevant. see developer.thunderbird.net for newer information. this tutorial will introduce you to the components of a thunderbird extension and will show you how to build your own. ...
Demo Addon
. it shows how to achieve various goals in a working live example, such as working with gloda. you can download it at the bottom of the page. how to use after installing the demo add-on in thunderbird, right click on the toolbar and choose "customize". drag the "demo" button into the toolbar. afterwards, just click that button to show the demo overview. all three demos are explained in the following sections. only the interesting parts are shown, it's recommended that you download the add-on and have a look at its files. the basics the interesting parts covered in this article are in the content folder. the toolbar button and its functionality are defined in overlay.xul and overlay.js. we make use of fixiterator(). it is a handy library that keeps your code cleaner and simpler. it lets...
Access StringBundle from Overlay
sn't as easy as adding them to your xul overlay. ...
Get Thunderbird version
on thunderbird version 3.0b3pre and later, you can use the following snippet to get the thunderbird version. (version 3.0b3pre was the first build to include steel.) var versionchecker = components.classes["@mozilla.org/xpcom/version-comparator;1"].getservice(components.interfaces.nsiversioncomparator); if (versionchecker.compare(application.version, "3.0b4") >= 0) // code for >= 3.0b4 else // code for < 3.0b4 for versions prior to 3.0b3pre, you can use something like this: var version; if ( "@mozilla.org/xre/app-info;1" in components.classes ) version = components.classes["@mozilla.org/xre/app-info; 1"].getservice(components.interfaces.nsixulappinfo).version; else version = components.classes["@mozilla.org/preferences-service; 1"].getservice(components.interfaces.nsiprefbranch...
Tips and Tricks from the newsgroups
please feel free to add links to threads. we will add a categorization system as the link list grows. you can also help by creating how-tos from any of these topics. ...
Thunderbird extensions
there are similarities with firefox extensions, but there are also differences that may confound the starting thunderbird developer. this documention series focuses on thunderbird. need personalized help? see community / communications. warning: this content is for older versions of thunderbird. much of it may no longer be relevant. see developer.thunderbird.net for newer information. ...
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. ...
Using popup notifications
ctions from the drop-down menu, the corresponding callback is invoked. choosing the "not now" option dismisses the notification; it can be brought back by clicking on the notification icon again. implementing a timeout function for the popup notification you can use a timeout to make your notification automatically disappear after some amount of time, by calling notification.remove() as shown below. components.utils.import('resource://gre/modules/popupnotifications.jsm'); var notify = new popupnotifications(gbrowser, document.getelementbyid("notification-popup"), document.getelementbyid("notification-popup-box")); var notification = notify.show( // browser gbrowser.selectedbrowser, // popup id "pdes-popup", // message "hi, there!, i'm gonna show y...
Examples
ava from js-ctypes, by converting java code into c code. js-macosx an extension that demonstrates javascript-cocoa bridge for mac os x. lightweight bridge for calling cocoa frameworks from javascript, js-macosx transparently handles definition of cocoa api, both c and objective-c, and provides automatic declarations for framework functions, structures, constants and enumerations, as well as allows creating and subclassing cocoa classes. the js-macosx bridge has dependency on bridgesupport metadata: whenever a cocoa class, function, struct or const is encountered in the javascript code, js-macosx will replace it with the corresponding js-ctypes declaration based on the bridgesupport file from the framework that object belongs to. ...
Memory Management
ory will be valid as long as the js object stays alive. pointers to that memory must be carefully managed to make sure the underlying memory is still referenced. when binary code hands back a pointer/handle to allocated memory, the js code must make sure to free that memory with the correct allocator. it is usually best to expose a freeing function from the binary. keeping objects alive the following js-ctypes objects will hold references to objects, keeping them alive. this is not an exhaustive list, but will help you to understand memory management and how it affects your use of js-ctypes: a function or static data declared using the declare() method will hold that library alive. a ctype will hold referent ctype objects alive. a cdata will hold referent cdata objects alive, under s...
ctypes.open
ic -c mycfuntionsforunix.c gcc -shared -o mycfuntionsforunix.so mycfuntionsforunix.o a file named mycfuntionsforunix.so is successfully created. this native file can be placed in any folder of an addon and then loaded from js-ctypes. they can also be loaded from the system library path. loading the native file if your addon is restartless, you must set it to be unpacked. see: http://stackoverflow.com/questions/19382201/how-to-load-dll-from-sdk-addon-data-folder it is important to note that custom native files cannot be loaded through chrome:// or resource:// uris. they must be accessed through a local file path (file://) or a jar path (jar:). if the addon is an unpacked addon, such as bootstrap or add-on sdk addons, the jar path must be used. therefore, the path has to be converted and ...
ABI
http://en.wikipedia.org/wiki/x86_calling_conventions abi abi stands for "application binary interface". ...
CData
ions intended to represent the type of the cdata object and its value, respectively. string tosource() parameters none. return value a string that, ideally, should be able to be evaluated to produce a new cdata object containing a copy of the original object. however, this only works if the object's type happens to be bound to an appropriate name in scope. in theory, in other words, the following javascript expression should return a copy of the original cdata object: eval(dataobject.tosource()); tostring() returns a string identifying the data. 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,...
Library
ypes open() method. its methods let you declare symbols exported by the library, and to manage the library. method overview close(); cdata declare(name, [abi, ], returntype[, argtype1, ...]); methods close() closes the library. you need to call this once you're done using the library. close(); parameters none. declare() declares an api from the native library, allowing it to be used from javascript. this can be used both for exported data symbols and for functions. cdata declare( name[, abi, returntype argtype1, ...] ); parameters name the name of the symbol exported by the native library that is to be declared as usable from javascript abi the abi used by the exported function; this will be ctypes.default_abi for most libraries, except fo...
js-ctypes reference
.close(). calling conventions see abi. types and data to use js-ctypes effectively, it is important to understand the different kinds of objects that the module provides. there are three major categories: types these represent a type in c, and are thus represented by ctype objects. these objects have two main purposes. first, they provide a concrete representation of different data types, allowing the programmer to describe the arguments and return type of a native function (see library.declare()). second, they serve as constructors to create concrete instances of the given type, i.e. cdata objects. out of the box, js-ctypes supports a number of predefined types. type constructors these are functions that define new types, and thus return a ctype object. these include ctypes.poin...
Blocking By Domain - Plugins
and also cause many sites to show plugin activation prompts. sites in this category may include advertisers, social media sites, and other utilities. top sites many popular sites work properly without plugins, but still prompt users for activation. in order to improve site performance and reduce the number of plugin prompts that users see, popular sites that show unnecessary plugin prompts or slow the browser down with unnecessary plugins will be added to the plugin block list. list contents and updates the plugin block lists are freely-licensed lists maintained by mozilla in github. the initial contents of the third-party plugin block list are based on disconnect's open source blocklist. subsequent updates to the list will be made using telemetry from firefox experiments. in general, s...
Memory - Plugins
because it knows how much memory the plug-in is using at any given time. mac os the mac os browser frequently fills its memory partition with cached data that is purged only as necessary. since npn_memalloc automatically frees cached information if necessary to fulfill a request for memory, calls to npn_memalloc may succeed where direct calls to newptr fail. the npn_memalloc method has the following syntax: void *npn_memalloc (uint32 size); the size parameter is an unsigned long integer that represents the amount of memory, in bytes, to allocate in the browser's memory space. this function returns a pointer to the allocated memory or null if not enough memory is available. the npn_memfree method deallocates a block of memory that was allocated using npn_memalloc only. npn_memfree does...
Plug-in Side Plug-in API - Plugins
see the how plug-ins work and overview of plug-in structure sections in the introduction. plugin method summary npp_destroy deletes a specific instance of a plug-in. npp_destroystream tells the plug-in that a stream is about to be closed or destroyed. np_getentrypoints undocumented. np_getmimedescription registers the mime types supported by the plug-in (unix, mac os). npp_getvalue allows the browser to query the plug-in for information. np_getvalue allows the browser to query the plug-in for information. npp_handleevent delivers a platform-specific window event to the instance. np_initialize provides global initialization for a plug-in. npp_new creates a new instance of a plug-in. npp_newstream notifies a plug-in instance of a new data stream. npp_print requests a pl...
Scripting plugins - Plugins
be used to get and set properties, and to call methods on those browser objects. and as always when working with reference counted npobjects, the caller is responsible for calling npn_releaseobject on the npobject to drop the reference. ...
Version, UI, and Status Information - Plugins
displaying a status line message users are accustomed to checking the ui status line at the bottom of the browser window for updates on the progress of an operation or the url of a link on the page. you can also use the status line to notify the user of plug-in-related information. the user might appreciate seeing the percentage completed of the current operation or the url of a button or other link object when the cursor is over it, all of which the browser shows. ...
Plugins
x users. also from firefox 55 onwards, flash and other plugins can no longer be loaded from any url scheme except for http:// and https:// (bug 1335475). see also flash can now be loaded only from http/https for more useful information. starting with firefox 56 in september 2017, firefox for android will remove all support for plugins (bug 1381916). tutorials and references the articles below are developer information about the developing for click-to-play, and plugin blocking. flash activation: browser comparison each browser activates flash slightly differently, which can be confusing for users and web authors. plugin blocking by domain in order to improve security and performance for firefox users, firefox maintains a list of sites that are not able to use plugins. archived...
Preferences System
this document describes toolkit's preferences system. using this system it is possible to create preferences windows that display and operate appropriately on various platforms (windows, macos x and gnome). the system is implemented through a few xul elements and attributes. ...
Browser Toolbox - Firefox Developer Tools
d with a dialog like this (it can be removed by setting the devtools.debugger.prompt-connection property to false): click ok, and the browser toolbox will open in its own window: you'll be able to inspect the browser's chrome windows and see, and be able to debug, all the javascript files loaded by the browser itself and by any add-ons that are running. altogether you will have access to the following developer tools: debugger (note: if you want to debug a specific add-on that is restartless or sdk-based then try the add-on debugger.) console style editor performance network monitor page inspector accessibility inspector you can debug chrome: and about: pages using the normal debugger, just as if they were ordinary content pages. targeting a document in the normal toolbox, th...
Break on DOM mutation - Firefox Developer Tools
ist.add(), or setting element.id. node removal execution pauses if the element the option is set on is removed. examples for when this breakpoint is triggered are calling element.remove() or node.removechild() on its parent node. once you set the breakpoint, go to the debugger. you can see the breakpoint listed in the right-most panel under dom mutation breakpoints. click on the icon following the node name to go back to the page inspector with the node selected. when you execute the code, the debugger will pause execution when the dom mutation occurs. in the following example, the selected node (the unordered list) is modified by adding a new child node. the panel on the right shows that execution is "paused on dom mutation" and you, as with any other breakpoint, you can see th...
Debug worker threads - Firefox Developer Tools
the debugger shows the source code for all running worker threads — web workers, service workers, etc. — listed in the sources list. you can open the javascript file for the worker process and set breakpoints and logpoints just as you can with javascript code running on the main thread. inspecting worker code for example, see the selected item worker.js below — it is listed in a separate thread in the sources list, but appears in the source pane in the same way as main thread code when selected. setting breakpoints, etc. you can set a breakpoint (or logpoint) on any active worker thread: when execution is paused in a worker thread, the context of the debugger is updated to show the correct breakpoints, call stack, etc., just as you'd expect. ...
Access debugging in add-ons - Firefox Developer Tools
we are planning to deprecate the use by firefox add-ons of the techniques described in this document. don't write new add-ons that use these techniques. the following items are accessible in the context of chrome://browser/content/debugger.xul (or, in version 23 beta, chrome://browser/content/devtools/debugger.xul): window.addeventlistener("debugger:editorloaded") - called when the read-only script panel loaded. window.addeventlistener("debugger:editorunloaded") relevant files: chrome://browser/content/devtools/debugger-controller.js chrome://browser/content/devtools/debugger-toolbar.js chrome://browser/content/devtools/debugger-view.js chrome://browser/content/devtools/debugger-panes.js unfortunately there is not yet any api to evaluate watches/expressions within the...
Debug eval sources - Firefox Developer Tools
you can debug javascript code that is evaluated dynamically, either as a string passed to eval() or as a string passed to the function constructor. in the video below, we load a page containing a source like this: var script = `function foo() { console.log('called foo'); } //# sourceurl=my-foo.js`; eval(script); var button = document.getelementbyid("foo"); button.addeventlistener("click", foo, false); the evaluated string is given the name "my-foo.js" using the //# sourceurl directive. this source is then listed in the source list pane, and can be opened and debugged like any other source. the name of the source will also appear in stack traces appearing in the web console. the debugger will also stop at debugger; statements in unnamed eval ...
Search - Firefox Developer Tools
tab lists the functions in the current file. the default sort order is by the order in the file but you can simplify the search by click on "sort by name" at the bottom of the tab. you can further simplify the search by filtering the list. enter text into the text input above the list to limit the results in the outline. for example, if i enter "load" when viewing the above list, i get the following: only the functions with load in their name are shown. this feature may not seem terribly useful when searching a file with a handful of functions in it but when you are searching through a file with dozens of functions, it comes in handy. searching in all files you can also search for a string in all of the files included in the currently opened project. press shift + ctrl + f (windows ...
Set watch expressions - Firefox Developer Tools
ick "add watch expression." type the expression you'd like to watch into the text field. the debugger will save the expression and watch it as you step through your code. when the debugger reaches a breakpoint, it will display your watch expressions variables: you can step through your code, watching the value of the expression as it changes. each time it does, the box will flash briefly yellow. you can remove a watch expression by clicking the "x" icon next to it, and you can have more than one watch expression at a time. ...
Use watchpoints - Firefox Developer Tools
side of the debugger user interface, find an object you want to watch, and right-click it to open its context menu. choose break on, and then one of property set property get property get or set a watchpoint icon appears to the right of the property in the scopes pane. set watchpoint icons are blue, get watchpoint icons are reddish, and get or set watchpoint icons are dark yellow. click play or press f8 to resume execution. view a watchpoint when the watched property is accessed in the way specified by the watchpoint type (get or set), the debugger pauses, enabling you to see line of code responsible, and to inspect anything else you wish at that time. in the following screenshot, the debugger pauses at line 7, where obj.a is set. the message panel in the upper ri...
Set event listener breakpoints - Firefox Developer Tools
enu. now the logs will show where in your app jquery was called, rather than where in jquery the event was fired: filter by event type also added to firefox 71 is a new filter by event type... text input, which can also be found at the top of the event listener breakpoints list. when you click in this input and type a search term, the list of event listener types will filter by that term allowing you to find the events you want to break on more easily. inline variable preview new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through. see set a breakpoint > inline variable preview for more information. ...
Source map errors - Firefox Developer Tools
esource url, and the source map url: here, the resource url tells us that bundle.js mentions a source map, and the source map url tells us where to find the source map data (in this case, relative to the resource). the error tells us that the source map is not json data — so we're serving the wrong file. there are a few common ways that source maps can go wrong; they are detailed in the following sections. source map missing or inaccessible the source map resource can be missing or inaccessible. the fix here is to make sure the file is being served and is accessible to the browser invalid source map the source map data can be invalid — either simply not a json file at all, or with an incorrect structure. typical error messages here are: syntaxerror: json.parse: unexpected c...
The Firefox JavaScript Debugger - Firefox Developer Tools
fy 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 set a conditional breakpoint set an xhr breakpoint set event listener breakpoints b...
Measure a portion of the page - Firefox Developer Tools
e the mouse has a crosshair cursor with its current coordinates displayed beside it. when you hold the mouse button down and then drag, you'll start to draw a rectangle, with its x, y, and diagonal dimensions displayed. the units are in pixels. when you stop holding the mouse down, the rectangle that was displayed on screen when you released the button will stay there until you click again, allowing you time to take screenshots, note the information down, etc. the rectangle can also be resized later on by clicking one of the handles around it. ...
Performance Analysis - Firefox Developer Tools
rce and the total time it took to load them. the accompanying pie chart shows the relative size of each resource type. ...
Network Monitor - Firefox Developer Tools
g a page in, for example, the web console, then switch to the network monitor to see network activity without having to reload the page. ...
Edit CSS filters - Firefox Developer Tools
change will be apparent as soon as youpress enter. saving filter presets from firefox 42 onwards, you can also add filters to a list of presets. the list of presets will be preserved between browser sessions, making it easy to apply the settings in the future. you can save the current filter to the preset list: click to edit the filter, display the preset list by clicking the icon as shown below. type a name for your preset, and then click the plus sign to add it to the list of presets. you can then apply saved filters to new elements. to apply one of your saved presets, click its name in the list. ...
Animation inspector example: CSS transitions - Firefox Developer Tools
</div> css content .channel { padding: 2em; margin: 0.5em; box-shadow: 1px 1px 5px #808080; margin: 1.5em; } .channel > * { vertical-align: middle; line-height: normal; } .icon { width: 50px; height: 50px; filter: grayscale(100%); transition: transform 750ms ease-in, filter 750ms ease-in-out; } .note { margin-left: 1em; font: 1.5em "open sans",arial,sans-serif; overflow: hidden; white-space: nowrap; display: inline-block; opacity: 0; width: 0; transition: opacity 500ms 150ms, width 500ms 150ms; } .icon#selected { filter: grayscale(0%); transform: scale(1.5); } .icon#selected+span { opacity: 1; width: 300px; } javascript content function toggleselection(e) { if (e.button != 0) { return; } if (e.target.classlist.contains("icon")) ...
Animation inspector example: Web Animations API - Firefox Developer Tools
id="icon"/> <span id="note">firefox developer edition</span> </div> css content .channel { padding: 2em; margin: 0.5em; box-shadow: 1px 1px 5px #808080; margin: 1.5em; } .channel > * { vertical-align: middle; line-height: normal; } #icon { width: 50px; height: 50px; filter: grayscale(100%); } #note { margin-left: 1em; font: 1.5em "open sans",arial,sans-serif; overflow: hidden; white-space: nowrap; display: inline-block; opacity: 0; width: 0; } javascript content var iconkeyframeset = [ { transform: 'scale(1)', filter: 'grayscale(100%)'}, { filter: 'grayscale(100%)', offset: 0.333}, { transform: 'scale(1.5)', offset: 0.666 }, { transform: 'scale(1.5)', filter: 'grayscale(0%)'} ]; var notekeyframeset = [ { opacity: '0', width: '0'}, { op...
Page Inspector - Firefox Developer Tools
s 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. ...
Allocations - Firefox Developer Tools
ile. then record a profile as usual, and you will see a new tab labeled "allocations" in the toolbar: anatomy of the allocations view the allocations view looks something like this: the allocations view periodically samples allocations that are made over the recording. each row represents a function in which at least one allocation-sample was taken during the recording. it includes the following columns: self count: the number of allocation-samples that were taken in this function (also shown as a percentage of the total) self bytes: the total number of bytes allocated in the allocation-samples in this function (also shown as a percentage of the total) rows are sorted by the "self bytes" column. so in the example above: 8904 samples were taken in signallater(), which is 28.5...
Shader Editor - Firefox Developer Tools
o enable it, open the toolbox settings and check "shader editor" in the "default firefox developer tools" item. you'll now see "shader editor" appear in the toolbar. click it and the shader editor opens. at first you'll just see a blank window with a button asking you to reload the page: to get started, load a page which creates a webgl context and loads a program into it. the screenshots below are from the unreal engine demo. you'll now see a window divided into three panes: a list of all the glsl programs on the left, the vertex shader for the currently selected program in the middle, and the fragment shader for the currently selected program on the right: managing programs the left hand pane lists all programs currently in use by a webgl context. if you hover over an entry in th...
Extension Storage - Firefox Developer Tools
this storage type is only shown when debugging extensions. when selecting an extension id in the storage tree of the storage inspector, a table lists the details of all the extension storage present for the extension. this table contains the following columns: key — the name of the stored item. value — the value of the stored item. storage area — the name of the area where the item is stored. ...
Style Editor - Firefox Developer Tools
ressive syntax. if you do this, being able to see and edit the generated css is not so useful, because the code you maintain is the preprocessor syntax, not the generated css. so you'd need to edit the generated css, then manually work out how to reapply that to the original source. source maps enable the tools to map back from the generated css to the original syntax, so they can display, and allow you to edit, files in the original syntax. from firefox 29 onwards, the style editor can understand css source maps. this means that if you use, for example, sass, then the style editor will show you, and allow you to edit, sass files, rather than the css that is generated from them: for this to work, you must: use a css preprocessor that understands the source map revision 3 proposal. curre...
Tips - Firefox Developer Tools
"enable persistent logs" in the settings to keep requests from before even after navigation. hover the "js" icon within the "cause" column to see the javascript stack trace, which caused the request. check "disable http cache (when toolbox is open)" in the settings to disable the network cache while debugging network issues. storage inspector right-click the column headers to open a menu allowing to toggle the display of the columns. right-click an entry and click "delete name" to delete it or "delete all" to delete all entries. select an entry to see the parsed value of it in the sidebar. ...
Web Console UI Tour - Firefox Developer Tools
the web console's interface is split into three horizontal sections, detailed in the sections below. toolbar the toolbar across the top contains a number of features: garbage can: click this icon to clear the contents of the console. funnel: click this icon to filter the messages that are displayed in the console. filter categories: you can click a filter category (such as errors, warnings, css, or xhr) to display just those types of messages. settings ("gear" menu): new in firefox 71, you can click the gear icon to access the new settings menu, where you can toggle the following features on and off: persist logs: when enabled, the console doesn't clear on page reload, or new page load. show timestamps: when enabled, timestamps are shown on the left-hand side of each mess...
Firefox Developer Tools
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 access the page's accessibility tree, allowing you to check what's missing or otherwise needs attention. application panel provides tools for inspecting and debugging modern web apps (also known as progressive web apps). this includes inspection of service workers and web app manifests. note: the collective term for the ui inside which the devtools all live is the toolbox. more tools these developer tools are also built into f...
ANGLE_instanced_arrays - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is only available to webgl1 contexts. in webgl2, the functionality of this extension is available on the webgl2 context by default and the constants and methods are available without the "angle" suffix. ...
AbortController.AbortController() - Web APIs
the abortcontroller() constructor creates a new abortcontroller object instance. syntax var controller = new abortcontroller(); parameters none. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var...
AbortSignal: abort event - Web APIs
later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console. ...
AbortSignal.aborted - Web APIs
later on we check whether or not it the signal has been aborted using the aborted property, and send an appropriate log to the console. ...
AbortSignal.onabort - Web APIs
the onabort read-only property of the fetchsignal interface is an event handler invoked when an abort event fires, i.e. when the fetch request(s) the signal is communicating with is/are aborted. syntax abortsignal.onabort = function() { ... }; examples in the following snippet, we create a new abortcontroller object, and get its abortsignal (available in the signal property). later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console. var controller = new abortcontroller(); var signal = controller.signal; signal.onabort = function() { console.log('request aborted'); }; specifications specification status comment domthe definition of 'onabort' in that specification. livi...
AbsoluteOrientationSensor - Web APIs
th's reference coordinate system. 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. syntax var absoluteorientationsensor = new absoluteorientationsensor([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called. a whole number or decimal may be used, the latter for frequencies less than a second. the actual reading frequency depends device hardware and consequently may be less than requested. referenceframe: either 'device' or 'screen'. the defau...
AbsoluteOrientationSensor - Web APIs
absoluteorientationsensor() creates a new absoluteorientationsensor object. properties no specific properties; inherits methods from its ancestors orientationsensor and sensor. event handlers no specific event handlers; inherits methods from its ancestor, sensor. methods no specific methods; inherits methods from its ancestors orientationsensor and sensor. examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an absoluteorientationsensor with a frequency of 60 times a second. on each reading it uses orientationsensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceframe: 'device' }; const sensor = new absoluteorientationsensor(options); sensor.addeventlistener('reading', () ...
AbstractWorker.onerror - Web APIs
the abstractworker.onerror property of the abstractworker interface represents an eventhandler, that is a function to be called when the error event occurs and bubbles through the worker. syntax myworker.onerror = function() { ... }; example the following code snippet shows creation of a worker object using the worker() constructor and setting up of an onerror handler on the resulting object: var myworker = new worker('worker.js'); myworker.onerror = function() { console.log('there is an error with your worker!'); } specifications specification status comment html living standardthe definition of 'abstractworker.onerror' in that specification. living standard ...
Accelerometer.Accelerometer() - Web APIs
f the device along all three axes at the time it is read. 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. syntax var accelerometer = new accelerometer([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onerror will be called. a whole number or decimal may be used, the latter for frequencies less than a second. the actual reading frequency depends device hardware and consequently may be less than requested. referenceframe: either 'device' or 'screen'. the default...
Accelerometer.x - Web APIs
Web › API › Accelerometer › x
xis. 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. syntax var xacceleration = accelerometer.x value a number. example acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let accelerometer = new accelerometer({frequency: 60}); accelerometer.addeventlistener('reading', e => { console.log("acceleration along the x-axis " + accelerometer.x); console.log("acceleration along the y-axis " + accelerometer.y); console.log("acceleration along the z-axis " + accelerometer.z); }); accelerometer.start(); specifications spec...
Accelerometer.y - Web APIs
Web › API › Accelerometer › y
xis. 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. syntax var yacceleration = accelerometer.y value a number. example acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let accelerometer = new accelerometer({frequency: 60}); accelerometer.addeventlistener('reading', e => { console.log("acceleration along the x-axis " + accelerometer.x); console.log("acceleration along the y-axis " + accelerometer.y); console.log("acceleration along the z-axis " + accelerometer.z); }); accelerometer.start(); specifications spec...
Accelerometer.z - Web APIs
Web › API › Accelerometer › z
xis. 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. syntax var zacceleration = accelerometer.z value a number. example acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let accelerometer = new accelerometer({frequency: 60}); accelerometer.addeventlistener('reading', e => { console.log("acceleration along the x-axis " + accelerometer.x); console.log("acceleration along the y-axis " + accelerometer.y); console.log("acceleration along the z-axis " + accelerometer.z); }); accelerometer.start(); specifications spec...
Accelerometer - Web APIs
e containing the acceleration of the device along the device's x axis. accelerometer.y read only returns a double containing the acceleration of the device along the device's y axis. accelerometer.z read only returns a double containing the acceleration of the device along the device's z axis. example acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let acl = new accelerometer({frequency: 60}); acl.addeventlistener('reading', () => { console.log("acceleration along the x-axis " + acl.x); console.log("acceleration along the y-axis " + acl.y); console.log("acceleration along the z-axis " + acl.z); }); acl.start(); specifications specification status comment generic sensor api...
AesCtrParams - Web APIs
the counter, and the rest is used for the nonce. for example, if length is set to 64, then the first half of counter is the nonce and the second half is used for the counter. length a number — the number of bits in the counter block that are used for the actual counter. the counter must be big enough that it doesn't wrap: if the message is n blocks and the counter is m bits long, then the following must be true: n <= 2m. the nist sp800-38a standard, which defines ctr, suggests that the counter should occupy half of the counter block (see appendix b.2), so for aes it would be 64. examples see the examples for subtlecrypto.encrypt() and subtlecrypto.decrypt(). specifications specification status comment web cryptography apithe definition of 'subtlecrypto.aesctr...
AesGcmParams - Web APIs
...
Ambient Light Events - Web APIs
light events when the light sensor of a device detects a change in the light level, it notifies the browser of that change. when the browser gets such a notification, it fires a devicelightevent event that provides information about the exact light intensity (in lux units). ...
AnalyserNode.fftSize - Web APIs
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. note: if its value is not a power of 2, or it is outside the specified range, a domexception with the name indexsizeerror is thrown. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. 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 ...
AnalyserNode.frequencyBinCount - Web APIs
igned integer, equal to the number of values that analysernode.getbytefrequencydata() and analysernode.getfloatfrequencydata() copy into the provided typedarray. for technical reasons related to how the fast fourier transform is defined, it is always half the value of analysernode.fftsize. therefore, it will be one of 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, and 16384. 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 lines 128–205 for relevant code). var audioctx = new (window.audiocontext ...
AnalyserNode.getByteFrequencyData() - Web APIs
h data returned from getbytefrequencydata() parameters array the uint8array that the frequency domain data will be copied to. for any sample which is silent, the value is -infinity. if the array has fewer elements than the analysernode.frequencybincount, excess elements are dropped. if it has more elements than needed, excess elements are ignored. return value none. 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 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.webkita...
AnalyserNode.getByteTimeDomainData() - Web APIs
nalyser.getbytetimedomaindata(dataarray); // fill the uint8array with data returned from getbytetimedomaindata() parameters array the uint8array that the time domain data will be copied to. if the array has fewer elements than the analysernode.fftsize, excess elements are dropped. if it has more elements than needed, excess elements are ignored. return value void | none example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). const audioctx = new (window.audiocontex...
AnalyserNode.getFloatFrequencyData() - Web APIs
nored. return value none. example const audioctx = new audiocontext(); const analyser = audioctx.createanalyser(); // float32array should be the same length as the frequencybincount const mydataarray = new float32array(analyser.frequencybincount); // fill the float32array with data returned from getfloatfrequencydata() analyser.getfloatfrequencydata(mydataarray); drawing a spectrum the following example shows basic usage of an audiocontext to connect a mediaelementaudiosourcenode to an analysernode. while the audio is playing, we collect the frequency data repeatedly with requestanimationframe() and draw a "winamp bargraph style" to a <canvas> element. for more complete applied examples/information, check out our voice-change-o-matic-float-data demo (see the source code too). <!doct...
AnalyserNode.getFloatTimeDomainData() - Web APIs
loattimedomaindata(dataarray); // fill the float32array with data returned from getfloattimedomaindata() parameters array the float32array that the time domain data will be copied to. if the array has fewer elements than the analysernode.frequencybincount, excess elements are dropped. if it has more elements than needed, excess elements are ignored. return value none. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic-float-data demo (see the source code too). var audioctx = new (window.audiocontext || window.
AnalyserNode.maxDecibels - Web APIs
s 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 lines 128–205 for relevant code). var audioctx = new (window.audiocontext ...
AnalyserNode.minDecibels - Web APIs
ar 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. note: if a value greater than analysernode.maxdecibels is set, an index_size_err 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 m...
AnalyserNode.smoothingTimeConstant - Web APIs
uite a lot while computing the value", which essentially smoothes the changes across analysernode.getfloatfrequencydata/analysernode.getbytefrequencydata calls. in technical terms, we apply a blackman window and smooth the values over time. the default value is good enough for most cases. note: if a value outside the range 0–1 is set, an index_size_err 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 lines 128–205 for relevant code). if you are curious about the effect the ...
Animation() - Web APIs
imeline optional specifies the timeline with which to associate the animation, as an object of a type based on the animationtimeline interface. currently the only timeline type available is documenttimeline, but in the future there my be timelines associated with gestures or scrolling, for example. the default value is document.timeline, but this can be set to null as well. examples in the follow the white rabbit example, the animation() constructor is used to create an animation for the rabbitdownkeyframes using the document's timeline: var rabbitdownanimation = new animation(rabbitdownkeyframes, document.timeline); specifications specification status comment web animationsthe definition of 'animation()' in that specification. working draft editor's draf...
Animation.finished - Web APIs
has finished playing. every time the animation leaves the finished play state (that is, when it starts playing again), a new promise is created for this property. the new promise will resolve once the new animation sequence has completed. syntax var animationspromise = animation.finished; value a promise object which will resolve once the animation has finished running. ...
Animation.id - Web APIs
Web › API › Animation › id
the animation.id property of the web animations api returns or sets a string used to identify the animation. syntax var animationsid = animation.id; animation.id = newidstring; value a domstring which can be used to identify the animation, or null if the animation has no id. examples in the follow the white rabbit example, you can assign the rabbitdownanimation an id like so: rabbitdownanimation.effect.id = "rabbitgo"; specifications specification status comment web animationsthe definition of 'animation.id' in that specification. working draft editor's draft. ...
Animation.onremove - Web APIs
the event handler for the remove event. this event is sent when the animation is removed (i.e., put into an active replace state). syntax var removehandler = animation.onremove; animation.onremove = removehandler; value a function to be called to handle the remove event, or null if no remove event handler is set. ...
Animation.pause() - Web APIs
Web › API › Animation › pause
solved (perhaps it hasn't started playing yet) and the end time of the animation is positive infinity. ...
Animation.persist() - Web APIs
Web › API › Animation › persist
the persist() method of the web animations api's animation interface explicitly persists an animation, when it would otherwise be removed due to the browser's automatically removing filling animations behavior. syntax animation.persist(); parameters none. return value none. ...
Animation.ready - Web APIs
Web › API › Animation › ready
to check the state of the animation when the promise is resolved. syntax var readypromise = animation.ready; value a promise which resolves when the animation is ready to be played. you'll typically use a construct similar to this when using the ready promise: animation.ready.then(function() { // do whatever needs to be done when // the animation is ready to run }); example in the following example, the state of the animation will be running when the current ready promise is resolved because the animation does not leave the pending play state in between the calls to pause and play and hence the current ready promise does not change. animation.pause(); animation.ready.then(function() { // displays 'running' alert(animation.playstate); }); animation.play(); specifications ...
Animation.replaceState - Web APIs
f: active: the initial value of the animation's replace state; when the animation has been removed by the browser's automatically removing filling animations behavior. persisted: the animation has been explicitly persisted by invoking animation.persist() on it. removed: the animation has been explicitly removed. ...
Animation - Web APIs
Web › API › Animation
) has been invoked on it. animation.starttime gets or sets the scheduled time when an animation's playback should begin. animation.timeline gets or sets the timeline associated with this animation. event handlers animation.oncancel gets and sets the event handler for the cancel event. animation.onfinish gets and sets the event handler for the finish event. animation.onremove allows you to set and run an event handler that fires when the animation is removed (i.e., put into an active replace state). methods animation.cancel() clears all keyframeeffects caused by this animation and aborts its playback. animation.commitstyles() commits the end styling state of an animation to the element being animated, even after that animation has been removed. it will cause the end...
AnimationEvent.initAnimationEvent() - Web APIs
the progress of being removed from most implementations. do not use this method; instead, use the standard constructor, animationevent(), to create a synthetic animationevent. syntax animationevent.initanimationevent(typearg, canbubblearg, cancelablearg, animationnamearg, elapsedtimearg); parameters typearg a domstring identifying the specific type of animation event that occurred. the following values are allowed: value meaning animationstart the animation has started. animationend the animation completed. animationiteration the current iteration just completed. canbubblearg a boolean flag indicating if the event can bubble (true) or not (false). cancelablearg a boolean flag indicating if the event ...
AnimationEvent - Web APIs
the animationevent interface represents events providing information related to animations. ...
AnimationPlaybackEvent.AnimationPlaybackEvent() - Web APIs
the animationplaybackevent() constructor of the web animations api returns a new animationplaybackevent object instance. syntax var animationplaybackevent = new animationplaybackevent(type, eventinitdict); parameters type a domstring representing the name of the event. eventinitdict optional an optional eventinit dictionary object containing the following fields: bubbles optional defaults to false, of type boolean, indicating if the event bubbles or not. cancelable optional defaults to false, of type boolean, indicating if the event can be canceled or not. detail optional defaults to null, of type any — an event-dependent value associated with the event. specifications specification status comment web animationsthe definition of 'an...
ArrayBufferView - Web APIs
this is a helper type to simplify the specification; it isn't an interface, and there are no objects implementing it. specifications specification status comment web idlthe definition of 'arraybufferview' in that specification. ...
Attr.prefix - Web APIs
Web › API › Attr › prefix
<div x:id="example" onclick="console.log(this.attributes[0].prefix)"/> notes this will only work when a namespace-aware parser is used, i.e. when a document is served with an xml mime type. this will not work for html documents. ...
AudioBuffer.getChannelData() - Web APIs
r nowbuffering = myarraybuffer.getchanneldata(channel); parameters channel the channel property is an index representing the particular channel to get data for. an index value of 0 represents the first channel. if the channel index value is greater than of equal to audiobuffer.numberofchannels, an index_size_err exception will be thrown. return value a float32array. example in the following example we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. you can also run the code live, or view the source. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var button = document.queryselector('button'); var pre = document.queryselector('pre'); var myscript = d...
AudioBufferSourceNode.AudioBufferSourceNode() - Web APIs
detune: a value in cents to modulate the speed of audio stream rendering. ...
AudioBufferSourceNode.playbackRate - Web APIs
the default value is 1.0. when set to another value, the audiobuffersourcenode resamples the audio before sending it to the output. ...
AudioContext() - Web APIs
ich represents an audio-processing graph, built from audio modules linked together, each represented by an audionode. syntax var audioctx = new audiocontext(); var audioctx = new audiocontext(options); parameters options optional an object based on the audiocontextoptions dictionary that contains zero or more optional properties to configure the new context. 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 c...
AudioContext.close() - Web APIs
ntext, and stop processing audio data. the returned promise resolves when all audiocontext-creation-blocking resources have been released. this method throws an invalid_state_err exception if called on an offlineaudiocontext. syntax var audioctx = new audiocontext(); audioctx.close().then(function() { ... }); await audioctx.close(); returns a promise that resolves with void. example the following snippet is taken from our audiocontext states demo (see it running live.) when the stop button is clicked, close() is called. when the promise resolves, the example is reset to its beginning state. stopbtn.onclick = function() { audioctx.close().then(function() { startbtn.removeattribute('disabled'); susresbtn.setattribute('disabled', 'disabled'); stopbtn.setattribute('disabled'...
AudioContext.createMediaStreamDestination() - Web APIs
r.getusermedia — it can, for example, be sent to a remote peer using the rtcpeerconnection addstream() method. for more details about media stream destination nodes, check out the mediastreamaudiodestinationnode reference page. syntax var audioctx = new audiocontext(); var destination = audioctx.createmediastreamdestination(); returns a mediastreamaudiodestinationnode. examples in the following simple example, we create a mediastreamaudiodestinationnode, an oscillatornode and a mediarecorder (the example will therefore only work in firefox and chrome at this time.) the mediarecorder is set up to record information from the mediastreamdestinationnode. when the button is clicked, the oscillator starts, and the mediarecorder is started. when the button is stopped, the oscillator and me...
AudioContext.resume() - Web APIs
rogression of time in an audio context that has previously been suspended. this method will cause an invalid_state_err exception to be thrown if called on an offlineaudiocontext. syntax completepromise = audiocontext.resume(); parameters none. return value a promise that resolves when the context has resumed. the promise is rejected if the context has already been closed. example the following snippet is taken from our audiocontext states demo (see it running live.) when the suspend/resume button is clicked, the audiocontext.state is queried — if it is running, suspend() is called; if it is suspended, resume() is called. in each case, the text label of the button is updated as appropriate once the promise resolves. susresbtn.onclick = function() { if(audioctx.state === 'running...
AudioContext.suspend() - Web APIs
own the audio hardware when it will not be using an audio context for a while. this method will cause an invalid_state_err exception to be thrown if called on an offlineaudiocontext. syntax var audioctx = new audiocontext(); audioctx.suspend().then(function() { ... }); returns a promise that resolves with void. the promise is rejected if the context has already been closed. example the following snippet is taken from our audiocontext states demo (see it running live.) when the suspend/resume button is clicked, the audiocontext.state is queried — if it is running, suspend() is called; if it is suspended, resume() is called. in each case, the text label of the button is updated as appropriate once the promise resolves. susresbtn.onclick = function() { if(audioctx.state === 'running...
AudioContext - Web APIs
rything happens inside a context. it's recommended to create one audiocontext and reuse it instead of initializing a new one each time, and it's ok to use a single audiocontext for several different audio source and pipeline concurrently. ...
AudioContextOptions.latencyHint - Web APIs
ons.latencyhint = 0.2; var latencyhint = audiocontextoptions.latencyhint; value the preferred maximum latency for the audiocontext. there are two ways this value can be specified. the best way to specify the preferred latency is to use a value form the string enum audiocontextlatencycategory. 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. speci...
AudioContextOptions - Web APIs
given type of audio usage: value description "balanced" the user agent should balance audio output latency and power consumption when selecting a latency value. "interactive" the audio is involved in interactive 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...
AudioDestinationNode.maxChannelCount - Web APIs
unt of channels that the physical device can handle. the audionode.channelcount property can be set between 0 and this value (both included). if maxchannelcount is 0, like in offlineaudiocontext, the channel count cannot be changed. syntax var audioctx = new audiocontext(); var mydestination = audioctx.destination; mydestination.maxchannelcount = 2; value an unsigned long. ...
AudioListener.dopplerFactor - Web APIs
esenting the amount of pitch shift to use when rendering a doppler effect. the dopplerfactor property's default value is 1, which is a sensible default for most situations. syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.dopplerfactor = 1; value a double indicating the doppler effect's pitch shift value. the value is 1 by default. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
AudioListener.forwardX - Web APIs
d direction the listener is pointing in. note: the parameter is a-rate when used with a pannernode whose panningmodel is set to equalpower, or k-rate otherwise. syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.forwardx.value = 0; value an audioparam. its default value is 0, and it can range between positive and negative infinity. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
AudioListener.forwardY - Web APIs
d direction the listener is pointing in. note: the parameter is a-rate when used with a pannernode whose panningmodel is set to equalpower, or k-rate otherwise. syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.forwardy.value = 0; value an audioparam. its default value is 0, and it can range between positive and negative infinity. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
AudioListener.forwardZ - Web APIs
direction the listener is pointing in. note: the parameter is a-rate when used with a pannernode whose panningmodel is set to equalpower, or k-rate otherwise. syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.forwardz.value = 0; value an audioparam. its default value is -1, and it can range between positive and negative infinity. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
AudioListener.positionX - Web APIs
on of the listener in 3d cartesian space. note: the parameter is a-rate when used with a pannernode whose pannernode is set to equalpower, or k-rate otherwise. syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.positionx.value = 1; value an audioparam. its default value is 0, and it can range between positive and negative infinity. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
AudioListener.positionY - Web APIs
on of the listener in 3d cartesian space. note: the parameter is a-rate when used with a pannernode whose pannernode is set to equalpower, or k-rate otherwise. syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.positiony.value = 1; value an audioparam. its default value is 0, and it can range between positive and negative infinity. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
AudioListener.positionZ - Web APIs
on of the listener in 3d cartesian space. note: the parameter is a-rate when used with a pannernode whose pannernode is set to equalpower, or k-rate otherwise. syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.positionz.value = 1; value an audioparam. its default value is 0, and it can range between positive and negative infinity. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
AudioListener.setOrientation() - Web APIs
p and zup, describes the direction of the top of the listener's head. the up vector's default value is (0, 1, 0). the two vectors must be separated by an angle of 90° — in linear analysis terms, they must be perpendicular to each other. syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.setorientation(0,0,-1,0,1,0); returns void. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
AudioListener.setPosition() - Web APIs
describe the listener's position in 3d space according to the right-hand cartesian coordinate system. pannernode objects use this position relative to individual audio sources for spatialisation. the default value of the position vector is (0, 0, 0). syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.setposition(1,1,1); returns void. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
AudioListener.speedOfSound - Web APIs
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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
AudioListener.upX - Web APIs
Web › API › AudioListener › upX
g the up direction the listener is pointing in. note: the parameter is a-rate when used with a pannernode whose pannernode is set to equalpower, or k-rate otherwise. syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.upx.value = 0; value an audioparam. its default value is 0, and it can range between positive and negative infinity. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
AudioListener.upY - Web APIs
Web › API › AudioListener › upY
g the up direction the listener is pointing in. note: the parameter is a-rate when used with a pannernode whose pannernode is set to equalpower, or k-rate otherwise. syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.upy.value = 0; value an audioparam. its default value is 1, and it can range between positive and negative infinity. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
AudioListener.upZ - Web APIs
Web › API › AudioListener › upZ
g the up direction the listener is pointing in. note: the parameter is a-rate when used with a pannernode whose pannernode is set to equalpower, or k-rate otherwise. syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.upz.value = 0; value an audioparam. its default value is 0, and it can range between positive and negative infinity. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
AudioListener - Web APIs
n could not be smoothly applied, resulting in audio glitches. because of these issues, these properties and methods have been removed. the setorientation() and setposition() methods have been replaced by setting their property value equivilents. for example setposition(x, y, z) can be achieved by setting positionx.value, positiony.value, and positionz.value respectively. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
AudioNode.channelCountMode - Web APIs
in this case, channelcount is ignored and only up-mixing happens. ...
AudioParam.exponentialRampToValueAtTime() - Web APIs
note: exponential ramps are considered more useful when changing frequencies or playback rates than linear ramps because of the way the human ear works. ...
AudioParam.linearRampToValueAtTime() - Web APIs
syntax var audioparam = audioparam.linearramptovalueattime(value, endtime) parameters value a floating point number representing the value the audioparam will ramp to by the given time. ...
AudioParam.value - Web APIs
Web › API › AudioParam › value
d given the current time and any established time-based parameter value changes. upon first creating the parameter, its value is set to its default value, given by audioparam.defaultvalue. this is the parameter's value at a time of 0.0 seconds, and will remain the parameter's value until the first render quantum in which the value is altered. during each render quantum, the browser does the following things related to managing the value of a parameter: if the value setter has been used, the parameter's value is changed to the value given. if the current time equals or exceeds the time specified by a previous call to setvalueattime(), the value is changed to the value passed into setvalueattime(). if any gradiated or ramped value changing methods have been called and the current time i...
AudioParamMap - Web APIs
methods entries() ? foreach() ? has() ? keys() ? values() ? ...
AudioScheduledSourceNode - Web APIs
unless stated otherwise, nodes based upon audioscheduledsourcenode output silence when not playing (that is, before start() is called and after stop() is called). silence is represented, as always, by a stream of samples with the value zero (0). properties inherits properties from its parent interface, audionode. methods inherits methods from its parent interface, audionode, and adds the following methods: start() schedules the node to begin playing the constant sound at the specified time. if no time is specified, 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 ...
AudioTrack.kind - Web APIs
Web › API › AudioTrack › kind
f audio contained in the audiotrack. the kind can be used to determine the scenarios in which specific tracks should be enabled or disabled. 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. audio track kind strings the kinds available for audio tracks are: "alternative" a potential alternative to the main track, such as a different audio take or a version of the soundtrack with only the music and no dialogue. "descriptions" an audio track providing audible descriptions of the action depicted in a video track. "main" the primary audio track. "main-desc" the primary audio...
AudioTrack.label - Web APIs
Web › API › AudioTrack › label
track metadata. otherwise, an empty string ("") is returned. for example, a track whose kind is "commentary" might have a label such as "commentary with director mark markmarkimark and star donna donnalidon". example this example returns an array of track kinds and labels for potential use in a user interface to select audio tracks for a specified media element. the list is filtered to only allow certain track kinds through. function gettracklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "main-desc", "translation", "commentary" ]; el.audiotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, label: track.label }); } }); return track...
AudioTrack - Web APIs
f (track.language === userlanguage) { track.enabled = true; } else { track.enabled = false; } }); the language is in standard (rfc 5646) format. for us english, this would be "en-us", for example. example this example returns an array of track kinds and labels for potential use in a user interface to select audio tracks for a specified media element. the list is filtered to only allow certain track kinds through. function gettracklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "main-desc", "translation", "commentary" ]; el.audiotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, label: track.label }); } }); return track...
AudioTrackList.getTrackById() - Web APIs
edia resource itself, or, if the resource doesn't define an order, the relative order in which the tracks are declared by the media resource. example this example suggests a hypothetical game in which movies are used as cut-scenes or other key set pieces within the game. each movie has one audio track for each character, as well as one for the music, sound effects, and so forth. this function allows the game to disable a specific character's audio in order to adjust the movie's performance based on occurrences within the game; if the character's dialog isn't relevant, it gets left out. obviously that would require some clever graphic design to make work, but... it's a hypothetical game. function disablecharacter(videoelem, charactername) { videoelem.audiotracks.gettrackbyid(charactername...
AudioWorklet - Web APIs
the worklet's code is run in the audioworkletglobalscope global execution context, using a separate web audio thread which is shared by the worklet and other audio nodes. access the audio context's instance of audioworklet through the baseaudiocontext.audioworklet property. properties the audioworklet interface does not define any properties of its own, but does inherit properties of worklet. methods this interface inherits methods from worklet. ...
AudioWorkletGlobalScope.registerProcessor - Web APIs
registered. the name is to be referred to when creating an audioworkletnode based on the registered processor. a new processor by the given name is internally created and associated with the new node. return value undefined exceptions notsupportederror the name is an empty string, or a constructor under the given name is already registered. registering the same name twice is not allowed. typeerror the processorctor is not a callable constructor, or the parameterdescriptors property of the constructor exists and doesn't return an array of audioparamdescriptor-based objects. examples in this example we create a custom audioworkletnode that outputs silence. first, we need to define a custom audioworkletprocessor and register it. note that this should be done ...
AudioWorkletGlobalScope - Web APIs
execution context for user-supplied code, which defines custom audioworkletprocessor-derived classes. each baseaudiocontext has a single audioworklet available under the audioworklet property, which runs its code in a single audioworkletglobalscope. as the global execution context is shared across the current baseaudiocontext, it's possible to define any other variables and perform any actions allowed in worklets — apart from defining audioworkletprocessor-derived classes. properties currentframe read only returns an integer that represents the ever-increasing current sample-frame of the audio block being processed. it is incremented by 128 (the size of a render quantum) after the processing of each audio block. currenttime read only returns a double that represents the ever-incre...
AudioWorkletNode() - Web APIs
must first be registered using the audioworkletglobalscope.registerprocessor() method. options optional an object based on the audioworkletnodeoptions dictionary, which contains zero or more optional properties to configure the new node. the result of the structured clone algorithm applied to the object is also internally passed into the associated audioworkletprocessor() constructor — this allows custom initialization of an underlying user-defined audioworkletprocessor. available properties are as follows: numberofinputs optional the value to initialize the numberofinputs property to. defaults to 1. numberofoutputs optional the value to initialize the numberofoutputs property to. defaults to 1. outputchannelcount optional an array defining the number of channels for each output. f...
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
r interface, but, if defined, it is called internally by the audioworkletprocessor constructor to create a list of custom audioparam objects in the parameters property of the associated audioworkletnode. defining the getter is optional. syntax audioworkletprocessorsubclass.parameterdescriptors; value an iterable of audioparamdescriptor-based objects. the properties of these objects are as follows: name the domstring 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. default...
AudioWorkletProcessor - Web APIs
ocess() method in it; register the processor using audioworkletglobalscope.registerprocessor() method; load the file using addmodule() method on your audio context's audioworklet property; create an audioworkletnode based on the processor. the processor will be instantiated internally by the audioworkletnode constructor. connect the node to the other nodes. examples in the example below we create a custom audioworkletnode that outputs white noise. first, we need to define a custom audioworkletprocessor, which will output white noise, and register it. note that this should be done in a separate file. // white-noise-processor.js class whitenoiseprocessor extends audioworkletprocessor { process (inputs, outputs, parameters) { const output = outputs[0] output.foreach(cha...
AuthenticatorAttestationResponse.attestationObject - Web APIs
nds to the private key that has created the attestation signature is well known; however, there are various well known attestation public key chains for different ecosystems (for example, android or tpm attestations). syntax attestobj = authenticatorattestationresponse.attestationobject properties after decoding the cbor encoded arraybuffer, the resulting javascript object will contain the following properties: authdata the same as authenticatorassertionresponse.authenticatordata. note that in authenticatorassertionresponse, the authenticatordata is exposed as a property in a javascript object while in authenticatorattestationresponse, the authenticatordata is a property in a cbor map. the same authenticatorassertionresponse.authenticatordata field is used by both authenticatorattest...
AuthenticatorAttestationResponse.getTransports() - Web APIs
thing if this information is not available.of the processing of the different extensions by the client. the elements of this array are supposed to be in lexicographical order. their values may be : "usb": the authenticator can be contacted via a removable usb link "nfc": the authenticator may be used over nfc (near field communication) "ble": the authenticator may be used over ble (bluetooth low energy) "internal": the authenticator is specifically bound to the client device (cannot be removed). examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", ...
AuthenticatorResponse.clientDataJSON - Web APIs
ects of authenticatorresponse, specifically authenticatorattestationresponse or authenticatorassertionresponse. syntax var arraybuffer = authenticatorattestationresponse.clientdatajson; var arraybuffer = authenticatorassertionresponse.clientdatajson; value an arraybuffer. properties after the clientdatajson object is converted from an arraybuffer to a javascript object, it will have the following properties: type a string which is either "webauthn.get" when an existing credential is retrieved or "webauthn.create" when a new credential is created. challenge the base64url encoded version of the cryptographic challenge sent from the relying party's server. the original value is passed via publickeycredentialrequestoptions.challenge or publickeycredentialcreationoptions.challenge. o...
AuthenticatorResponse - Web APIs
the authenticatorresponse interface of the web authentication api is the base interface for interfaces that provide a cryptographic root of trust for a key pair. the child interfaces include information from the browser such as the challenge origin and either may be returned from publickeycredential.response. interfaces based on authenticatorresponse below is a list of interfaces based on the authenticatorresponse interface. authenticatorassertionresponse authenticatorattestationresponse properties authenticatorresponse.clientdatajson a json string in an arraybuffer, representing the client data that was passed to credentialscontainer.create() or credentialscontainer.get(). methods none. examples getting an authenticatorassertionresponse var options = { challe...
BaseAudioContext.createAnalyser() - Web APIs
the createanalyser() method of the baseaudiocontext interface creates an analysernode, which can be used to expose audio time and frequency data and create data visualisations. note: for more on using this node, see the analysernode page. syntax var analysernode = baseaudiocontext.createanalyser(); returns an analysernode. example the following example shows basic usage of an audiocontext to create an analyser node, then use requestanimationframe() to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. 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...
BaseAudioContext.createChannelMerger() - Web APIs
face creates a channelmergernode, which combines channels from multiple audio streams into a single audio stream. syntax baseaudiocontext.createchannelmerger(numberofinputs); parameters numberofinputs the number of channels in the input audio streams, which the output stream will contain; the default is 6 if this parameter is not specified. returns a channelmergernode. example the following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third parameters of the audionode.connect(audionode) method, which allow you to specify both the index of the channel to connect from and the index of the channel to connect to. var ac = new audiocontext(); ac.decodeaudiod...
BaseAudioContext.createChannelSplitter() - Web APIs
elsplitternode, which is used to access the individual channels of an audio stream and process them separately. syntax baseaudiocontext.createchannelsplitter(numberofoutputs); parameters numberofoutputs the number of channels in the input audio stream that you want to output separately; the default is 6 if this parameter is not specified. returns a channelsplitternode. example the following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third parameters of the audionode.connect(audionode) method, which allow you to specify the index of the channel to connect from and the index of the channel to connect to. var ac = new audiocontext(); ac.decodeaudi...
BaseAudioContext.createConvolver() - Web APIs
the createconvolver() method of the baseaudiocontext interface creates a convolvernode, which is commonly used to apply reverb effects to your audio. see the spec definition of convolution for more information. syntax baseaudiocontext.createconvolver(); returns a convolvernode. example the following example shows basic usage of an audiocontext to create a convolver node. the basic premise is that you create an audiobuffer containing a sound sample to be used as an ambience to shape the convolution (called the impulse response,) and apply that to the convolver. the example below uses a short sample of a concert hall crowd, so the reverb effect applied is really deep and echoey. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). ...
BaseAudioContext.createDelay() - Web APIs
a certain amount of time. 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). if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || win...
BaseAudioContext.createDynamicsCompressor() - Web APIs
the createdynamicscompressor() method of the baseaudiocontext interface is used to create a dynamicscompressornode, which can be used to apply compression to an audio signal. compression lowers the volume of the loudest parts of the signal and raises the volume of the softest parts. overall, a louder, richer, and fuller sound can be achieved. it is especially important in games and musical applications where large numbers of individual sounds are played simultaneously, where you want to control the overall signal level and help avoid clipping (distorting) of the audio output. syntax baseaudioctx.createdynamicscompressor(); returns a dynamicscompressornode. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a mor...
BaseAudioContext.createOscillator() - Web APIs
for applied examples/information, check out our violent theremin demo (see app.js for relevant code); also see our oscillatornode page for more information. ...
BaseAudioContext.createPanner() - Web APIs
is used to create a new pannernode, which is used to spatialize an incoming audio stream in 3d space. 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. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
BaseAudioContext.createPeriodicWave() - Web APIs
constraints optional an dictionary object that specifies whether normalization should be disabled (if not specified, normalization is enabled by default.) it takes one property: disablenormalization: if set to true, normalization is disabled for the periodic wave. the default is false. if normalized, the resulting wave will have a maximum absolute peak value of 1. example the following example illustrates simple usage of createperiodicwave(), to create a periodicwave object containing a simple sine wave. var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); var osc = ac.createoscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createperiodicwave(real, imag, {disablenormalization: true}); osc.setperiodicwa...
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.createWaveShaper() - Web APIs
the createwaveshaper() method of the baseaudiocontext interface creates a waveshapernode, which represents a non-linear distortion. it is used to apply distortion effects to your audio. syntax baseaudioctx.createwaveshaper(); returns a waveshapernode. example the following example shows basic usage of an audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.creat...
BaseAudioContext.onstatechange - Web APIs
the onstatechange property of the baseaudiocontext interface defines an event handler function to be called when the statechange event fires: this occurs when the audio context's state changes. syntax baseaudiocontext.onstatechange = function() { ... }; example the following snippet is taken from our audiocontext states demo (see it running live.) the onstatechange hander is used to log the current state to the console every time it changes. audioctx.onstatechange = function() { console.log(audioctx.state); } specifications specification status comment web audio apithe definition of 'onstatechange' in that specification. working draft ...
BaseAudioContext.state - Web APIs
of the baseaudiocontext interface returns the current state of the audiocontext. syntax baseaudiocontext.state; value a domstring. possible values are: suspended: the audio context has been suspended (with the audiocontext.suspend() method.) running: the audio context is running normally. closed: the audio context has been closed (with the audiocontext.close() method.) example the following snippet is taken from our audiocontext states demo (see it running live.) the audiocontext.onstatechange hander is used to log the current state to the console every time it changes. audioctx.onstatechange = function() { console.log(audioctx.state); } specifications specification status comment web audio apithe definition of 'state' in that specification. worki...
BasicCardRequest.supportedNetworks - Web APIs
tercard). syntax supportednetworks : [value [, ... value]] value an array containing one or more domstrings, which describe the card networks the retailer supports. legal values are defined in the w3c's document card network identifiers approved for use with payment request api, and are currently: amex cartebancaire diners discover jcb mastercard mir unionpay visa example the following example shows a sample definition of the first parameter of the paymentrequest() constructor, the data property of which contains supportednetworks and supportedtypes properties. var supportedinstruments = [{ supportedmethods: 'basic-card', data: { supportednetworks: ['visa', 'mastercard', 'amex', 'jcb', 'diners', 'discover', 'mir', 'unionpay'], supportedty...
BasicCardRequest.supportedTypes - Web APIs
ed. instead of making the web app or site worry about this, the onus has been transferred to the payment processor. syntax basiccardrequest.supportedtypes = [cardtype1...cardtypen]; value an array containing one or more domstrings, which describe the card types the retailer supports. legal values are defined in basiccardtype enum, and are currently: credit debit prepaid example the following example shows a sample definition of the first parameter of the paymentrequest() constructor, the data property of which contains supportednetworks and supportedtypes properties. var supportedinstruments = [{ supportedmethods: 'basic-card', data: { supportednetworks: ['visa', 'mastercard', 'amex', 'jcb', 'diners', 'discover', 'mir', 'unionpay'], supportedty...
Battery Status API - Web APIs
the battery status api, more often referred to as the battery api, provides information about the system's battery charge level and lets you be notified by events that are sent when the battery level or charging status change. this can be used to adjust your app's resource usage to reduce battery drain when the battery is low, or to save changes before the battery runs out in order to prevent data loss. the 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 le...
Beacon API - Web APIs
icult for developers. user agents will typically ignore asynchronous xmlhttprequests made in an unload handler. to solve this problem, analytics and diagnostics code will typically make a synchronous xmlhttprequest in an unload or beforeunload handler to submit the data. the synchronous xmlhttprequest forces the browser to delay unloading the document, and makes the next navigation appear to be slower. there is nothing the next page can do to avoid this perception of poor page load performance. there are other techniques used to ensure that data is submitted. one such technique is to delay the unload to submit data by creating an image element and setting its src attribute within the unload handler. as most user agents will delay the unload to complete the pending image load, data can be su...
BeforeInstallPromptEvent.prompt() - Web APIs
syntax beforeinstallpromptevent.prompt() parameters none. returns an empty promise. ...
Blob() - Web APIs
Web › API › Blob › Blob
concatenation of the values given in the parameter array. syntax var newblob = new blob(array, options); parameters array an array of arraybuffer, arraybufferview, blob, usvstring objects, or a mix of any of such objects, that will be put inside the blob. usvstring objects are encoded as utf-8. options optional an optional object of type blobpropertybag which may specify any of the following properties: type optional the mime type of the data that will be stored into the blob. the default value is the empty string, (""). endings optional how to interpret newline characters (\n) within the contents, if the data is text. the default value, transparent, copies newline characters into the blob without changing them. to convert newlines to the host system's native conventi...
Bluetooth.getDevices() - Web APIs
the program can detect when a device comes online or into range by watching for bluetooth advertisements by calling bluetoothdevice.watchadvertisements() on that device. syntax var readerpromise = bluetooth.getdevices(); parameters none. return value a promise that resolves with an array of bluetoothdevices. ...
Bluetooth - Web APIs
Web › API › Bluetooth
includes bluetoothdeviceeventhandlers; bluetooth includes characteristiceventhandlers; bluetooth includes serviceeventhandlers; properties inherits properties from its parent eventtarget. bluetooth.referringdevice read only returns a reference to the device, if any, from which the user opened the current page. for example, an eddystone beacon might advertise a url, which the user agent allows the user to open. a bluetoothdevice representing the beacon would be available through navigator.bluetooth.referringdevice. events bluetooth.onavailabilitychanged an event handler that runs when an event of type availabilitychanged has fired. methods bluetooth.getavailability() returns a promise that resolved to a boolean indicating whether the user-agent has the ability to support b...
BluetoothCharacteristicProperties - Web APIs
tted. writableauxiliariesread only returns a boolean that is true if reliable writes to the characteristic descriptor is permitted. writeread only returns a boolean that is true if the writing to the characteristic with response is permitted. writewithoutresponseread only returns a boolean that is true if the writing to the characteristic without response is permitted. examples the following example shows how tell if a gatt characteristic supports value change notifications. let device = await navigator.bluetooth.requestdevice({ filters: [{services: ['heart_rate']}] }); let gatt = await device.gatt.connect(); let service = await gatt.getprimaryservice('heart_rate'); let characteristic = await service.getcharacteristic('heart_rate_measurement'); if (characteristic.properties.not...
BluetoothDevice.uuids - Web APIs
use bluetoothremotegattserver.getprimaryservices instead. the bluetoothdevice.uuids read-only property lists the uuids of gatt services provided by the device, that the current origin is allowed to access. syntax var uuids[] =​ instanceofbluetoothdevice.uuids returns an array. ...
Body.blob() - Web APIs
Web › API › Body › blob
e (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg. when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest) .then(response => response.blob()) .then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'blob()' in that specification. living standard ...
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. ...
CSS.paintWorklet (Static property) - Web APIs
Web › API › CSS › paintWorklet
paintworklet is a static, read-only property of the css interface that provides access to the paintworklet, which programmatically generates an image where a css property expects a file. syntax var worklet = css.paintworklet; value the paintworklet object. examples the following example demonstrates loading a paintworklet from its js file and does so by feature detection. <script> if ('paintworklet' in css) { css.paintworklet.addmodule('checkerboard.js'); } </script> specifications specification status comment css painting api level 1the definition of 'paintworklet' in that specification. working draft initial definition. ...
CSS.supports() - Web APIs
Web › API › CSS › supports
value a domstring containing the value of the css property to check. ...
CSS - Web APIs
Web › API › CSS
es are defined on it. static properties css.paintworklet secure context provides access to the worklet responsible for all the classes related to painting. methods the css interface is a utility interface and no object of this type can be created: only static methods are defined on it. static methods no inherited static methods. css.registerproperty() registers custom properties, allowing for property type checking, default values, and properties that do or do not inherit their value. css.supports() returns a boolean indicating if the pair property-value, or the condition, given in parameter is supported. css.escape() can be used to escape a string mostly for use as part of a css selector. css factory functions can be used to return a new cssunitvalue with a value of the ...
CSSKeywordValue.CSSKeywordValue() - Web APIs
the csskeywordvalue constructor creates a new csskeywordvalue object which represents css keywords and other identifiers. syntax var csskeywordvalue = new csskeywordvalue(val) parameters value sets or returns the value of the new csskeywordvalue. examples the following example resets the css display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector. #myelement { display: flex; } <div id="myelement">check the developer tools to see the log in the console and to inspect the style attribute on this div.</div> let keyword = new csskeywordvalue('initial'); let myelement = document.getelementbyid('myelement').attributestylemap; myelement.set('display', keyword); console.log( myelement.ge...
CSSKeywordValue.value - Web APIs
the value property of the csskeywordvalue interface returns or sets the value of the csskeywordvalue. syntax var val = csskeywordvalue.value csskeywordvalue.value = val value a usvstring. examples the following example resets the css display property to its defaults. let indicator = document.getelementbyid('indicator'); indicator.attributestylemap.set('display', new csskeywordvalue('initial')); indicator.attributestylemap.get('display').value // 'initial' specifications specification status comment css typed om level 1the definition of 'undefined' in that specification. working draft initial definition. ...
CSSKeywordValue - Web APIs
entifiers. the interface instance name is a stringifier meaning that when used anywhere a string is expected it will return the value of csskeyword.value. constructor csskeywordvalue.csskeywordvalue() creates a new csskeywordvalue object. properties csskeywordvalue.value returns or sets the value of the csskeywordvalue. methods inherits methods from cssstylevalue. examples the following example resets the css display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector. #myelement { display: flex; } <div id="myelement">check the developer tools to see the log in the console and to inspect the style attribute on this div.</div> let myelement = document.getelementbyid('myelement').attributestyle...
CSSMathValue - Web APIs
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. ...
CSSMediaRule - Web APIs
cssgroupingrule and the cssrule interface with a type value of 4 (cssrule.media_rule). syntax the syntax is described using the webidl format. interface cssmediarule : cssconditionrule { readonly attribute medialist media; } properties as a cssconditionrule, and therefore both a cssgroupingrule and a cssrule, cssmediarule also implements the properties of these interfaces. it has the following specific property: cssmediarule.media read only specifies a medialist representing the intended destination medium for style information. methods as a cssconditionrule, and therefore both a cssgroupingrule and a cssrule, cssmediarule also implements the methods of that interface. it has no specific methods. specifications specification status comment css c...
CSSNumericValue.equals() - Web APIs
the equals() method of the cssnumericvalue interface returns a boolean indicating whether the passed value are strictly equal. to return a value of true, all passed values must be of the same type and value and must be in the same order. this allows structural equality to be tested quickly. syntax var boolean = cssnumericvalue.equals(number); parameters number either a number or a cssnumericvalue. return value a boolean. exceptions none. examples as stated earlier, all passed values must be of the same type and value and must be in the same order. some of the following examples illustrate what happens when they are not. let cssmathsum = new cssmathsum(css.px(1), css.px(2)); let matchingcssmathsum = new cssmathsum(css.px(1), css.px(2)); // prints true console.log(cssmathsum.
CSSNumericValue.max() - Web APIs
s passed. the passed values must be of the same type. syntax var cssunitvalue = cssnumericvalue.man(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 "2cm" console.log(css.cm("1").max(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 'max' in that specification. working draft initial definition. ...
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. // 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 typ...
CSSNumericValue.parse() - Web APIs
the parse() method of the cssnumericvalue interface converts a value string into an object whose members are value and the units. syntax var cssnumericvalue = cssnumericvalue.parse(csstext); parameters csstext a string containing numeric and unit parts. return value a cssnumericvalue. exceptions syntaxerror tbd examples the following returns a cssunitvalue object with a unit property equal to "px" and a value property equal to 42. let numvalue = cssnumericvalue.parse("42.0px"); specifications specification status comment css typed om level 1the definition of 'parse' in that specification. working draft initial definition. ...
CSSPageRule - Web APIs
presenting a single css @page rule. it implements the cssrule interface with a type value of 6 (cssrule.page_rule). syntax the syntax is described using the webidl format. interface csspagerule : cssrule { attribute domstring selectortext; readonly attribute cssstyledeclaration style; }; properties as a cssrule, csspagerule also implements the properties of this interface. it has the following specific properties: csspagerule.selectortext represents the text of the page selector associated with the at-rule. csspagerule.style read only returns the declaration block associated with the at-rule. methods as a cssrule, csspagerule also implements the methods of that interface. it has no specific methods. specifications specification status comment ...
CSSPositionValue.CSSPositionValue() - Web APIs
the csspositionvalue constructor creates a new csspositionvalue object which represents values for properties that take a position, for example object-position. syntax cvar csspositionvalue = new csspositionvalue(x, y) parameters x a position along the web page's horizontal axis. y a position along the web page's vertical axix. examples the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page. let somediv = document.getelementbyid('container'); let position = new csspositionvalue(css.px(5), css.px(10)); somediv.attributestylemap.set('object-position', position); console.log(position.x.value, position.y.value); // 5 10 ...
CSSPositionValue.x - Web APIs
the x property of the csspositionvalue interface returns returns the item's position along the web page's horizontal axis. syntax var x = csspositionvalue.x value a cssnumericvalue. example the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page. let somediv = document.getelementbyid('container'); let position = new csspositionvalue(css.px(5), css.px(10)); somediv.attributestylemap.set('object-position', position); console.log(position.x.value, position.y.value); ...
CSSPositionValue.y - Web APIs
the y property of the csspositionvalue interface returns the item's position along the vertical axis. syntax var y = csspositionvalue.y value a cssnumericvalue. example the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page. let replaceel = document.getelementbyid('container'); let position = new csspositionvalue(css.px(5), css.px(10)); somediv.attributestylemap.set('object-position', position); console.log(position.x.value, position.y.value); ...
CSSPositionValue - Web APIs
t model api represents values for properties that take a position, for example object-position. constructor csspositionvalue.csspositionvalue() creates a new csspositionvalue object. properties csspositionvalue.x returns the item's position along the web page's horizontal axis. csspositionvalue.y returns the item's position along the vertical axis. methods none. examples the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page. let replacedel = document.getelementbyid( 'image' ); let position = new csspositionvalue( css.px(35), css.px(40) ); replacedel.attributestylemap.set( 'object-position', position ); console.log( position.x.value, position.y.value ); console.log( replacedel.computedstylemap().get('object-positio...
CSSPrimitiveValue.setFloatValue() - Web APIs
> in radians. css_s the value is a <time> in seconds. floatvalue a float representing the new float value. return value void. exceptions type description domexception an invalid_access_err is raised if the css value doesn't contain a float value or if the string value can't be converted into the specified unit. an no_modification_allowed_err is raised if this property is read-only. specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssprimitivevalue.setfloatvalue' in that specification. obsolete initial definition ...
CSSPrimitiveValue.setStringValue() - Web APIs
e is a <string>. css_uri the value is a <uri>. stringvalue a domstring representing the new string value. return value void. exceptions type description domexception an invalid_access_err is raised if the css value doesn't contain a string value or if the string value can't be converted into the specified unit. an no_modification_allowed_err is raised if this property is read-only. specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssprimitivevalue.setstringvalue' in that specification. obsolete initial definition ...
CSSPseudoElement.element - Web APIs
the element read-only property of the csspseudoelement interface returns a reference to the originating element of the pseudo-element, in other words its parent element. syntax var originatingelement = csspseudoelement.element; value an element representing the pseudo-element's originating element. ...
CSSRule - Web APIs
Web › API › CSSRule
the cssrule interface specifies the properties common to all rules, while properties unique to specific rule types are specified in the more specialized interfaces for those rules' respective types. references to a cssrule may be obtained by looking at a cssstylesheet's cssrules list. properties common to all cssrule instances cssrule.csstext represents the textual representation of the rule, e.g. "h1,h2 { font-size: 16pt }" or "@import 'url'". to access or modify parts of the rule (e.g. ...
CSSStyleDeclaration.getPropertyCSSValue() - Web APIs
t it returns null if the property name is a shorthand property. you should use cssstyledeclaration.getpropertyvalue() instead. syntax var value = style.getpropertycssvalue(property); parameters property is a domstring representing the property name to be retrieved. return value value is a cssvalue containing the css value for a property. if none exists, returns null. ...
CSSStyleDeclaration.getPropertyPriority() - Web APIs
ace returns a domstring that provides all explicitly set priorities on the css property. syntax var priority = style.getpropertypriority(property); parameters property is a domstring representing the property name to be checked. return value priority is a domstring that represents the priority (e.g. "important") if one exists. if none exists, returns the empty string. ...
CSSStyleDeclaration.getPropertyValue() - Web APIs
cssstyledeclaration.getpropertyvalue() method interface returns a domstring containing the value of a specified css property. syntax var value = style.getpropertyvalue(property); parameters property is a domstring representing the property name to be checked. return value value is a domstring containing the value of the property. if not set, returns the empty string. example the following javascript code queries the value of the margin property in a css selector rule: var declaration = document.stylesheets[0].cssrules[0].style; var value = declaration.getpropertyvalue('margin'); // "1px 2px" specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.getpropertyvalue()' in that specification. work...
CSSStyleDeclaration.length - Web APIs
the read-only property returns an integer that represents the number of style declarations in this css declaration block. syntax var num = styles.length; value an integer that provides the number of styles explictly set on the parent of the instance. example the following gets the number of explicitly set styles on the following html element: <div id="div1" style="margin: 0 10px; background-color: #ca1; font-family: monospace"></div> javascript code: var mydiv = document.getelementbyid('div1'); var divstyle = mydiv.style; var len = divstyle.length; // 6 specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.length' in that specification. working draft document object model (dom) level 2...
CSSStyleDeclaration.parentRule - Web APIs
the cssstyledeclaration.parentrule read-only property returns a cssrule that is the parent of this style block, e.g. a cssstylerule representing the style for a css selector. syntax var rule = styles.parentrule; value the css rule that contains this declaration block or null if this cssstyledeclaration is not attached to a cssrule. example the following javascript code gets the parent css style rule from a cssstyledeclaration: var declaration = document.stylesheets[0].rules[0].style; var rule = declaration.parentrule; specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.parentrule' in that specification. working draft document object model (dom) level 2 style specificationthe definiti...
CSSStyleDeclaration.setProperty() - Web APIs
perty(propertyname, value, priority); parameters propertyname is a domstring representing the css property name (hyphen case) to be modified. value optional is a domstring containing the new property value. if not specified, treated as the empty string. note: value must not contain "!important" -- that should be set using the priority parameter. priority optional is a domstring allowing the "important" css priority to be set. if not specified, treated as the empty string. the following values are accepted: string value "important" keyword undefined string empty value "" return value undefined exceptions domexception (nomodificationallowederror): if the property or declaration block is read only. if priority can be omitted, javascript has a special...
CSSStyleDeclaration - Web APIs
ration object on the first css rule in the document's first stylesheet. via window.getcomputedstyle(), which exposes the cssstyledeclaration object as a read-only interface. attributes cssstyledeclaration.csstext textual representation of the declaration block. setting this attribute changes the style. cssstyledeclaration.lengthread only the number of properties. see the item() method below. cssstyledeclaration.parentruleread only the containing cssrule. css properties cssstyledeclaration.cssfloat special alias for the float css property. cssstyledeclaration named properties dashed and camel-cased attributes for all supported css properties. methods cssstyledeclaration.getpropertypriority() returns the optional priority, "important". cssstyledeclaration.getproperty...
CSSStyleSheet.addRule() - Web APIs
at due to somewhat estoteric rules about where you can legally insert rules, it's possible that an exception may be thrown. see insertrule() for more information. usage notes this method is implemented by browsers by constructing a string using the template literal `${selector}{${styleblock}}`, then passing it into the standard insertrule() method. therefore, given existing code such as the following: cssstylesheet.addrule(selector, styles, 0); you can rewrite this to use the more standard insertrule() like this: cssstylesheet.insertrule(`${selector} {${styles}}`, 0); specifications specification status comment css object model (cssom)the definition of 'cssstylesheet.addrule()' in that specification. working draft ...
CSSStyleSheet - Web APIs
he 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 style sheet object the interface for the owner object getting the cssstylesheet object from the owner <style> and <link> elements in the document yes .ownernode htmllinkelement, htmlstyleelement, or s...
CSSStyleValue.parse() - Web APIs
ets a specific css property to the specified values and returns the first value as a cssstylevalue object. syntax cssstylevalue.parse(property, csstext) parameters property a css property to set. csstext a comma-separated string containing one or more values to apply to the provided property. return value a cssstylevalue object containing the first supplied value. example the code below parses a set of declarations for the transform property. the second code block shows the structure of the returned object as it would be rendered in a developer tools console. const css = cssstylevalue.parse( 'transform', 'translate3d(10px,10px,0) scale(0.5)'); csstransformvalue {0: csstranslate, 1: cssscale, length: 2, is2d: false} specifications specification status comme...
CSSStyleValue - Web APIs
the cssstylevalue interface of the the css typed object model api is the base class of all css values accessible through the typed om api. an instance of this class may be used anywhere a string is expected. interfaces based on cssstylevalue below is a list of interfaces based on the cssstylevalue interface. cssimagevalue csskeywordvalue cssnumericvalue csspositionvalue csstransformvalue cssunparsedvalue methods cssstylevalue.parse() sets a specific css property to the specified values and returns the first value as a cssstylevalue object. cssstylevalue.parseall() sets all occurences of a specific css property to the specified valueand returns an array of cssstylevalue objects, each containing one of the supplied values. specifications specification statu...
CSSUnitValue.CSSUnitValue() - Web APIs
constructor creates a new cssunitvalue object which returns a new cssunitvalue object which represents values that contain a single unit type. for example, "42px" would be represented by a cssnumericvalue. syntax var cssunitvalue = new cssunitvalue() parameters value returns a double indicating the number of units. unit returns a usvstring indicating the type of unit. examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors. let pos = new csspositionvalue( new cssunitvalue(5, "px"), new cssunitvalue(10, "px")); specifications specification status comment css typed om level 1the definition of 'cssunitvalue' in that specification. working draft initial definition. ...
CSSUnitValue.unit - Web APIs
Web › API › CSSUnitValue › unit
the cssunitvalue.unit read-only property of the cssunitvalue interface returns a usvstring indicating the type of unit. syntax var astring = cssunitvalue.unit; value a usvstring. examples the following creates a csspositionvalue from individual cssunitvalue constructors, then queries the cssunitvalue.unit. let pos = new csspositionvalue( new cssunitvalue( 5, "px" ), new cssunitvalue( 10, "em" )); console.log( pos.x.unit ); // "px" console.log( pos.y.unit ); // "em" specifications specification status comment css typed om level 1the definition of 'cssunitvalue.unit' in that specification. working draft initial definition. ...
CSSUnitValue.value - Web APIs
the cssunitvalue.value property of the cssunitvalue interface returns a double indicating the number of units. syntax var cssunitvalue = cssunitvalue.value; cssunitvalue.value = cssunitvalue; value a double. examples the following creates a csspositionvalue from individual cssunitvalue constructors, then queries the cssunitvalue.value. let pos = new csspositionvalue( new cssunitvalue( 5, "px" ), new cssunitvalue( 10, "px" )); console.log( pos.x.value ); // 5 console.log( pos.y.value ); // 10 specifications specification status comment css typed om level 1the definition of 'cssunitvalue.value' in that specification. working draft initial definition. ...
CSSUnitValue - Web APIs
nts values that contain a single unit type. for example, "42px" would be represented by a cssnumericvalue. constructor cssstylevalue.cssunitvalue() creates a new cssunitvalue object. properties cssunitvalue.value returns a double indicating the number of units. cssunitvalue.unit returns a usvstring indicating the type of unit. event handlers none. methods none. examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors. let pos = new csspositionvalue( new cssunitvalue(5, "px"), new cssunitvalue(10, "px")); specifications specification status comment css typed om level 1the definition of 'cssunitvalue' in that specification. working draft initial definition. ...
CSSVariableReferenceValue - Web APIs
this object functionality is sometimes called a "css variable" and serves the same purpose as the var() function. the custom name must begin with two dashes. constructor cssvariablereferencevalue.cssvariablereferencevalue() creates a new cssvariablereferencevalue object. properties cssvariablereferencevalue.variable returns the custom name passed to the constructor. cssvariablereferencevalue.fallback read only returns the built-in css value for the custom name. methods none. ...
CSS Counter Styles - Web APIs
interfaces csscounterstylerule represents an @counter-style rule. ...
Managing screen orientation - Web APIs
adjusting layout based on the orientation one of the most common cases for orientation changes is when you want to revise the layout of your content based on the orientation of the device. for example, perhaps you want a button bar to stretch along the longest dimension of the device's display. by using a media query, you can do this easily and automatically. let's have an example with the following html code <ul id="toolbar"> <li>a</li> <li>b</li> <li>c</li> </ul> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit. duis lacinia nisi nec sem viverra vitae fringilla nulla ultricies. in ac est dolor, quis tincidunt leo. cras commodo quam non tortor consectetur eget rutrum dolor ultricies. ut interdum tristique dapibus. nullam quis malesuada est.</p> css relies on the orien...
CSS Object Model (CSSOM) - Web APIs
the css object model is a set of apis allowing the manipulation of css from javascript. it is much like the dom, but for the css rather than the html. it allows users to read and modify css style dynamically. reference animationevent caretposition css csscharsetrule cssconditionrule csscounterstylerule cssfontfacerule cssfontfeaturevaluesmap cssfontfeaturevaluesrule cssgroupingrule cssimportrule csskeyframerule csskeyframesrule cssmarginrule cssmediarule cssnamespacerule csspagerule cssrule cssrulelist cssstyledeclaration cssstylesheet cssstylerule csssupportsrule cssvariablesmap cssviewportrule elementcssinlinestyle fontface fontfaceset fontfacesetloadevent geometryutils getstyleutils linkstyle medialist mediaquerylist mediaquerylistevent mediaqueryli...
Cache.add() - Web APIs
Web › API › Cache › add
note: add() will overwrite any key/value pair previously stored in the cache that matches the request. ...
Cache.delete() - Web APIs
Web › API › Cache › delete
: 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 whether the response object has a vary header. it defaults to false. cachename: a domstring that represents a specific cache to search within. note that this option is ignored by cache.
Cache.keys() - Web APIs
Web › API › Cache › keys
: 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 whether the response object has a vary header. it defaults to false. cachename: a domstring that represents a specific cache to search within. note that this option is ignored by cache.
Cache.match() - Web APIs
Web › API › Cache › match
e 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 the response object has a vary header. it defaults to false. return value a promise that resolves to the first response that matches the request or to undefined if no match is found. ...
Cache.put() - Web APIs
Web › API › Cache › put
often, you will just want to fetch() one or more requests, then add the result straight to your cache. in such cases you are better off using cache.add()/cache.addall(), as they are shorthand functions for one or more of these operations. fetch(url).then(function(response) { if (!response.ok) { throw new typeerror('bad response status'); } return cache.put(url, response); }) note: put() will overwrite any key/value pair previously stored in the cache that matches the request. ...
Cache - Web APIs
Web › API › Cache
ache name. the code also deletes all caches that aren't named in current_caches. in the code example, caches is a property 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 ...
CacheStorage.has() - Web APIs
Web › API › CacheStorage › has
ches the cachename. you can access cachestorage through the global caches property. syntax caches.has(cachename).then(function(boolean) { // true: your cache exists! }); parameters cachename a domstring representing the name of the cache object you are looking for in the cachestorage. return value a promise that resolves to true if the cache exists or false if not. examples the following example first checks whether a cache called 'v1' exists. if so, we add a list of assets to it. if not then we run some kind of cache set-up function. caches.has('v1').then(function(hascache) { if (!hascache) { somecachesetupfunction(); } else { caches.open('v1').then(function(cache) { return cache.addall(myassets); }); } }).catch(function() { // handle exception here...
CacheStorage.match() - Web APIs
earch: 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 whether the response object has a vary header or not. it defaults to false. cachename: a domstring that represents a specific cache to search within. return value a promise that re...
CanvasCaptureMediaStreamTrack - Web APIs
part of the media capture and streams api. properties this interface inherits the properties of its parent, mediastreamtrack. canvascapturemediastreamtrack.canvas read only returns the htmlcanvaselement object whose surface is captured in real-time. methods this interface inherits the methods of its parent, mediastreamtrack. canvascapturemediastreamtrack.requestframe() manually forces a frame to be captured and sent to the stream. ...
CanvasImageSource - Web APIs
canvasimagesource provides a mechanism for other interfaces to be used as image sources for some methods of the canvasdrawimage and canvasfillstrokestyles interfaces. it’s just an internal helper type to simplify the specification. it’s not an interface and there are no objects implementing it. the interfaces that it allows to be used as image sources are the following: htmlimageelement svgimageelement htmlvideoelement htmlcanvaselement imagebitmap offscreencanvas specifications specification status comment html living standardthe definition of 'canvasimagesource' in that specification. living standard initial definition. ...
CanvasPattern.setTransform() - Web APIs
222/canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); pattern.settransform(matrix.rotate(-45).scale(1.5)); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 400, 400); }; note that newer browser versions started to support dommatrix as an input to settransform(), so for example you could replace the svgmatrix in the above example with the following: const matrix = new dommatrix([1, .2, .8, 1, 0, 0]); edit the code below and see your changes update live in the canvas: playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <svg id="svg1" style="display:none"></svg> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </d...
CanvasRenderingContext2D.arcTo() - Web APIs
')', p.x + offset, p.y + offset); } ctx.beginpath(); ctx.moveto(p0.x, p0.y); ctx.arcto(p1.x, p1.y, p2.x, p2.y, 50); ctx.lineto(p2.x, p2.y); labelpoint(p0); labelpoint(p1); labelpoint(p2); ctx.stroke(); result result of a large radius if you use a relatively large radius, the arc may appear in a place you didn't expect. in this example, the arc's connecting line goes above, instead of below, the coordinate specified by moveto(). this happens because the radius is too large for the arc to fit entirely below the starting point. html <canvas id="canvas"></canvas> javascript const canvas = document.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 li...
CanvasRenderingContext2D.clip() - Web APIs
only those parts of the checkerboard pattern that are within the clipping region get drawn. note: 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(). ...
CanvasRenderingContext2D.createPattern() - Web APIs
hod doesn't draw anything to the canvas directly. the pattern it creates must be assigned to the canvasrenderingcontext2d.fillstyle or canvasrenderingcontext2d.strokestyle properties, after which it is applied to any subsequent drawing. syntax canvaspattern ctx.createpattern(image, repetition); parameters image a canvasimagesource to be used as the pattern's image. it can be any of the following: htmlimageelement (<img>) svgimageelement (<image>) htmlvideoelement (<video>, by using the capture of the video) htmlcanvaselement (<canvas>) imagebitmap offscreencanvas repetition a domstring indicating how to repeat the pattern's image. possible values are: "repeat" (both directions) "repeat-x" (horizontal only) "repeat-y" (vertical only) "no-repeat" (neither d...
CanvasRenderingContext2D.drawImage() - Web APIs
onal the height of the sub-rectangle of the source image to draw into the destination context. dx the x-axis coordinate in the destination canvas at which to place the top-left corner of the source image. dy the y-axis coordinate in the destination canvas at which to place the top-left corner of the source image. dwidth optional the width to draw the image in the destination canvas. this allows scaling of the drawn image. if not specified, the image is not scaled in width when drawn. dheight optional the height to draw the image in the destination canvas. this allows scaling 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 ...
CanvasRenderingContext2D.getImageData() - Web APIs
angle's top-left corner are (sx, sy), while the coordinates of the bottom corner are (sx + sw, sy + sh). exceptions indexsizeerror thrown if either sw or sh are zero. securityerror the canvas contains or may contain pixels which were loaded from an origin other than the one from which the document itself was loaded. to avoid securityerror being thrown in this situation, configure cors to allow the source image to be used in this way. see allowing cross-origin use of images and canvas. example getting image data from a canvas this example draws a rectangle, and then uses getimagedata() to grab a portion of the canvas. html <canvas id="canvas"></canvas> javascript the object retrieved by getimagedata() has a width of 200 and a height of 100, for a total of 20,000 pixels. of thos...
CanvasRenderingContext2D.getTransform() - Web APIs
one. return value a dommatrix object. the transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] note: the returned object is not live, so updating it will not affect the current transformation matrix, and updating the current transformation matrix will not affect an already returned dommatrix. examples in the following example, we have two <canvas> elements. we apply a transform to the first one's context using canvasrenderingcontext2d.settransform() and draw a square on it, then retrieve the matrix from it using gettransform(). we then apply the retrieved matrix directly to the second canvas context by passing the dommatrix object directly to settransform(), and draw a circle on it. html <canvas width="2...
CanvasRenderingContext2D.lineJoin - Web APIs
is example applies rounded line joins to a path. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.linewidth = 20; ctx.linejoin = 'round'; ctx.beginpath(); ctx.moveto(20, 20); ctx.lineto(190, 100); ctx.lineto(280, 20); ctx.lineto(280, 150); ctx.stroke(); result comparison of line joins the example below draws three different paths, demonstrating each of the three linejoin options. <canvas id="canvas" width="150" height="150"></canvas> var ctx = document.getelementbyid('canvas').getcontext('2d'); var linejoin = ['round', 'bevel', 'miter']; ctx.linewidth = 10; for (let i = 0; i < linejoin.length; i++) { ctx.linejoin = linejoin[i]; ctx.beginpath(); ctx.moveto(-5, 5 + i * 40); ctx.linet...
CanvasRenderingContext2D.measureText() - Web APIs
canvasrenderingcontext2d.measuretext() method returns a textmetrics object that contains information about the measured text (such as its width, for example). syntax ctx.measuretext(text); parameters text the text string to measure. return value a textmetrics object. example given this <canvas> element: <canvas id="canvas"></canvas> ... you can get a textmetrics object using the following code: const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let text = ctx.measuretext('hello world'); console.log(text.width); // 56; specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.measuretext' in that specification. living standard ...
CanvasRenderingContext2D.rotate() - Web APIs
ctx.rotate(45 * math.pi / 180); ctx.fillstyle = 'red'; ctx.fillrect(100, 0, 80, 20); // reset transformation matrix to the identity matrix ctx.settransform(1, 0, 0, 1, 0, 0); result the center of rotation is blue. the non-rotated rectangle is gray, and the rotated rectangle is red. rotating a shape around its center this example rotates a shape around its center point. to do this, the following steps are applied to the matrix: first, translate() moves the matrix's origin to the shape's center. rotate() rotates the matrix by the desired amount. finally, translate() moves the matrix's origin back to its starting point. this is done by applying the values of the shape's center coordinates in a negative direction. html <canvas id="canvas"></canvas> javascript the shape is a re...
CanvasRenderingContext2D.save() - Web APIs
the canvasrenderingcontext2d.save() method of the canvas 2d api saves the entire state of the canvas by pushing the current state onto a stack. the drawing state the drawing state that gets saved onto a stack consists of: the current transformation matrix. the current clipping region. the current dash list. the current values of the following attributes: strokestyle, fillstyle, globalalpha, linewidth, linecap, linejoin, miterlimit, linedashoffset, shadowoffsetx, shadowoffsety, shadowblur, shadowcolor, globalcompositeoperation, font, textalign, textbaseline, direction, imagesmoothingenabled. syntax void ctx.save(); examples saving the drawing state this example uses the save() method to save the default state and restore() to restore it later, so that you are able to draw a rect...
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
thintoview(path); parameters path a path2d path to use. examples using the scrollpathintoview method this example demonstrates the scrollpathintoview() method. ...
CanvasRenderingContext2D.setLineDash() - Web APIs
ine ctx.beginpath(); ctx.setlinedash([5, 15]); ctx.moveto(0, 50); ctx.lineto(300, 50); ctx.stroke(); // solid line ctx.beginpath(); ctx.setlinedash([]); ctx.moveto(0, 100); ctx.lineto(300, 100); ctx.stroke(); result some common patterns this example illustrates a variety of common line dash patterns. html <canvas id="canvas"></canvas> javascript the drawdashedline() function created below makes the drawing of multiple dashed lines simple. it receives a pattern array as its only parameter. function drawdashedline(pattern) { ctx.beginpath(); ctx.setlinedash(pattern); ctx.moveto(0, y); ctx.lineto(300, y); ctx.stroke(); y += 20; } const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let y = 15; drawdashedline([]); drawdashedline([1, 1])...
CanvasRenderingContext2D.setTransform() - Web APIs
g a shape this example skews a rectangle both vertically (.2) and horizontally (.8). scaling and translation remain unchanged. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.settransform(1, .2, .8, 1, 0, 0); ctx.fillrect(0, 0, 100, 100); result retrieving and passing a dommatrix object in the following example, we have two <canvas> elements. we apply a transform to the first one's context using the first type of settransform() and draw a square on it, then retrieve the matrix from it using canvasrenderingcontext2d.gettransform(). we then apply the retrieved matrix directly to the second canvas context by passing the dommatrix object directly to settransform() (i.e. the second type), and dra...
A basic ray-caster - Web APIs
y confident all those things could be added given enough time. the canvas api supports pixel copying of images, so textures seem feasible. i'll leave that for another article, probably from another person. =) the ray-caster the nice people here have manually copied my files up so you can take a look, and for your hacking enjoyment i've posted the individual file contents as code listings (see below). so there you are, fire up safari 1.3+ or firefox 1.5+ or some other browser that supports the <canvas> element and enjoy! input.js | level.js | player.js | raycaster.html | raycaster.js | trace.css | trace.js see also canvas tutorial ...
Compositing example - Web APIs
vides the inverted bottom layer by the top layer, and then inverts the result.', 'a combination of multiply and screen like overlay, but with top and bottom layer swapped.', 'a softer version of hard-light. ...
Finale - Web APIs
Web › API › Canvas API › Tutorial › Finale
ntly 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 let you describe images as sets of vectors (lines) and shapes in order to allow them to scale smoothly regardless of the size at which they're drawn. web audio the web audio api provides a powerful and versatile system for controlling audio on the web, allowing developers to choose audio sources, add effects to audio, create audio visualizations, apply spatial effects (such as panning) and much more. questions stack overflow questions tagged with "canvas". comments...
Optimizing canvas - Web APIs
« previousnext » the <canvas> element is one of the most widely used tools for rendering 2d graphics on the web. however, when websites and apps push the canvas api to its limits, performance begins to suffer. this article provides suggestions for optimizing your use of the canvas element to ensure that your graphics perform well. performance tips the following is a collection of tips to improve canvas performance. pre-render similar primitives or repeating objects on an offscreen canvas if you find yourself repeating some of the same drawing operations on each animation frame, consider offloading them to an offscreen canvas. you can then render the offscreen image to your primary canvas as often as needed, without unnecessarily repeating the steps needed to generate ...
Canvas API - Web APIs
ands-on, book-length introduction to the canvas api and webgl. canvas handbook a handy reference for the canvas api. demo: a basic ray-caster a demo of ray-tracing animation using canvas. manipulating video using canvas combining <video> and <canvas> to manipulate video data in real time. libraries the canvas api is extremely powerful, but not always simple to use. the libraries listed below can make the creation of canvas-based projects faster and easier. easeljs is an open-source canvas library that makes creating games, generative art, and other highly graphical experiences easy. fabric.js is an open-source canvas library with svg parsing capabilities. heatmap.js is an open-source library for creating canvas-based data heat maps. javascript infovis toolkit creates interactiv...
ChannelMergerNode - Web APIs
count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor channelmergernode() creates a new channelmergernode object instance. properties no specific property; inherits properties from its parent, audionode. methods no specific method; inherits methods from its parent, audionode. example the following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third parameters of the audionode.connect(audionode) method, which allow you to specify both the index of the channel to connect from and the index of the channel to connect to. var ac = new audiocontext(); ac.decodeaudiod...
ChannelSplitterNode - Web APIs
, as per earlier versions of the spec use 2 (not used in the default count mode). channel interpretation "discrete" constructor channelsplitternode() creates a new channelsplitternode object instance. properties no specific property; inherits properties from its parent, audionode. methods no specific method; inherits methods from its parent, audionode. example the following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third parameters of the audionode.connect(audionode) method, which allow you to specify the index of the channel to connect from and the index of the channel to connect to. var ac = new audiocontext(); ac.decodeaudi...
ChildNode.after() - Web APIs
Web › API › ChildNode › after
ld.after(span, "text"); console.log(parent.outerhtml); // "<div><p></p><span></span>text</div>" childnode.after() is unscopable the after() method is not scoped into the with statement. see symbol.unscopables for more information. ...
ChildNode.before() - Web APIs
Web › API › ChildNode › before
ore(span, "text"); console.log(parent.outerhtml); // "<div><span></span>text<p></p></div>" childnode.before() is unscopable the before() method is not scoped into the with statement. see symbol.unscopables for more information. ...
ChildNode.remove() - Web APIs
Web › API › ChildNode › remove
ar el = document.getelementbyid('div-02'); el.remove(); // removes the div with the 'div-02' id childnode.remove() is unscopable the remove() method is not scoped into the with statement. see symbol.unscopables for more information. ...
Client.postMessage() - Web APIs
the message is received in the "message" event on navigator.serviceworker. syntax client.postmessage(message[, transfer]); client.postmessage(message[, { transfer }]); parameters message the message to send to the client. this can be any structured-clonable type. transfer optional a sequence of objects that are transferred with the message. the ownership of these objects is given to the destination side and they are no longer usable on the sending side. return value undefined. ...
Clients.matchAll() - Web APIs
Web › API › Clients › matchAll
options parameter to return all service worker clients whose origin is the same as the associated service worker's origin. if options are not included, the method returns only the service worker clients controlled by the service worker. syntax self.clients.matchall(options).then(function(clients) { // do something with your clients list }); parameters options optional an options object allowing you to set options for the matching operation. available options are: includeuncontrolled: a boolean — if set to true, the matching operation will return all service worker clients who share the same origin as the current service worker. otherwise, it returns only the service worker clients controlled by the current service worker. the default is false. type: sets the type of clients y...
Clients.openWindow() - Web APIs
in chrome for android, the method may instead open the url in an existing browsing context provided by a standalone web app previously added to the user's home screen. ...
Clients - Web APIs
Web › API › Clients
the clients interface provides access to client objects. access it via self.clients within a service worker. methods clients.get() returns a promise for a client matching a given id. clients.matchall() returns a promise for an array of client objects. an options argument allows you to control the types of clients returned. clients.openwindow() opens a new browser window for a given url and returns a promise for the new windowclient. clients.claim() allows an active service worker to set itself as the controller for all clients within its scope. examples the following example shows an existing chat window or creates a new one when the user clicks a notification. addeventlistener('notificationclick', event => { event.waituntil(async function() { const allclients = await ...
ClipboardEvent() - Web APIs
o modification of the clipboard, that is cut, copy, and paste events. syntax var clipboardevent = new clipboardevent(type[, options]); parameters the clipboardevent() constructor also inherits arguments from event(). type is a domstring representing the name of the type of the clipboardevent. it is case-sensitive and can be: 'copy', 'cut', or 'paste'. options optional options are as follows: clipboarddata: a datatransfer containing the data concerned by the clipboard event. datatype : a domstring containing the mime-type of the data contained in the data argument. data : a domstring containing the data concerned by the clipboard event. specifications specification status comment clipboard api and eventsthe definition of 'clipboardevent()' ...
ClipboardItem() - Web APIs
format support varies by browser. see the browser compatibility table for the clipboard interface. syntax var clipboarditem = new clipboarditem(clipboarditemdata); parameters clipboarditemdata an object with the mime type as the key and blob as the value. note: to work with text see the clipboard.readtext() and clipboard.writetext() methods of the clipboard interface. examples the below example requests a png image using the fetch api, and in turn, the responses' blob() method, to create a new clipboarditem and write it to the clipboard, using the clipboard api. note: you can only pass in one clipboard item at a time. async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await...
ClipboardItem.getType() - Web APIs
b of the requested mime type or an error if the mime type is not found. syntax var blob = clipboarditem.gettype(type); parameters type a valid mime type. return value a promise that resolves with a blob object. exceptions domexception the type does not match a known mime type. typeerror no parameter is specified or the type is not that of the clipboarditem. examples in the following example, we're returning all items on the clipboard via the clipboard.read() method. then utilizing the clipboarditem.types property to set the gettype() argument and return the corresponding blob object. async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clip...
ClipboardItem.types - Web APIs
then checking the types property for available types before utilizing the clipboarditem.gettype() method to return the blob object. if no clipboards contents is found for the specified type, an error is returned. ...
ClipboardItem - Web APIs
y trying to read data from the clipboard. note: to work with text see the clipboard.readtext() and clipboard.writetext() methods of the clipboard interface. note: you can only pass in one clipboard item at a time. constructor clipboarditem.clipboarditem() creates a new clipboarditem object, with the mime type as the key and blob as the value properties this interface provides the following properties. types read only returns an array of mime types available within the clipboarditem. methods this interface defines the following methods. gettype() returns a promise that resolves with a blob of the requested mime type, or an error if the mime type is not found. examples writing to clipboard here we're writing a new clipboarditem.clipboarditem() to the clipboard by r...
CloseEvent() - Web APIs
"code", optional and defaulting to 0, of type unsigned short, that is the connection close code sent by the server. ...
CloseEvent - Web APIs
is sent to clients using websockets when the connection is closed. this is delivered to the listener indicated by the websocket object's onclose attribute. constructor closeevent() creates a new closeevent. properties this interface also inherits properties from its parent, event. closeevent.code read only returns an unsigned short containing the close code sent by the server. the following values are permitted status codes. the following definitions are sourced from the iana website [ref]. note that the 1xxx codes are only websocket-internal and not for the same meaning by the transported data (like when the application-layer protocol is invalid). the only permitted codes to be specified in firefox are 1000 and 3000 to 4999 [source, bug]. status code name de...
Comment - Web APIs
Web › API › Comment
is generally not visually shown, such comments are available to be read in the source view. comments are represented in html and xml as content between '<!--' and '-->'. in xml, the character sequence '--' cannot be used within a comment. ...
CompositionEvent.CompositionEvent() - Web APIs
the compositionevent() constructor creates a new compositionevent object instance. syntax const myevent = new compositionevent(typearg [, compositioneventinit]) values typearg is a domstring representing the name of the event. compositioneventinit optional a compositioneventinit dictionary object, which can contain the following members: data initializes the data attribute of the compositionevent object to the characters generated by the ime composition. note: the compositioneventinit dictionary inherits from the uieventinit dictionary, so can also accept members defined on there. specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'compositionevent()' in that specific...
CompositionEvent - Web APIs
the dom compositionevent represents events that occur due to the user indirectly entering text. ...
console.clear() - Web APIs
Web › API › Console › clear
the console.clear() method clears the console if the environment allows it. syntax console.clear(); specifications specification status comment console apithe definition of 'console.clear()' in that specification. living standard initial definition ...
Console.group() - Web APIs
Web › API › Console › group
note: this feature is available in web workers. syntax console.group([label]); parameters label label for the group. optional. (chrome 59 tested) does not work with console.groupend(). using groups in the console requires gecko 9.0(firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) you can use nested groups to help organize your output by visually associating related messages. to create a new nested block, call console.group(). the console.groupcollapsed() method is similar, but the new block is collapsed and requires clicking a disclosure button to read it. ...
Console.timeEnd() - Web APIs
Web › API › Console › timeEnd
ce stopped, the elapsed time is automatically displayed in the web console along with an indicator that the time has ended. examples console.time("answer time"); alert("click to continue"); console.timelog("answer time"); alert("do a bunch of other stuff..."); console.timeend("answer time"); the output from the example above shows the time taken by the user to dismiss the first alert box, followed by the time it took for the user to dismiss the second alert: notice that the timer's name is displayed when the timer value is logged using timelog() and again when it's stopped. in addition, the call to timeend() has the additional information, "timer ended" to make it obvious that the timer is no longer tracking time. specifications specification status comment ...
Console.timeLog() - Web APIs
Web › API › Console › timeLog
...
console.trace() - Web APIs
Web › API › Console › trace
ion for details and examples. syntax console.trace( [...any, ...data ]); parameters ...any, ...data optional zero or more objects to be output to console along with the trace. these are assembled and formatted the same way they would be if passed to the console.log() method. example function foo() { function bar() { console.trace(); } bar(); } foo(); in the console, the following trace will be displayed: bar foo <anonymous> specifications specification status comment console apithe definition of 'console.trace()' in that specification. living standard initial definition ...
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. ...
ConstrainDOMString - Web APIs
the constraindomstring dictionary is used to specify a constraint for a property whose value is a string. it allows you to specify one or more exact string values from which one must be the parameter's value, or a set of ideal values which should be used if possible. you can also specify a single string (or an array of strings) which the user agent will do its best to match once all more stringent constraints have been applied. properties the value of a constraindomstring can be any of the following: a single domstring an array of domstring objects an object with one or both of the following properties: exact either a single domstring which must be the value of the property, or an array of domstring objects one of which must be the property's value. if the property can't be set t...
ConstrainDouble - Web APIs
values) to also support an exact value and/or an ideal value the property should take on. additionally, you can specify the property's value as a simple floating-point value, in which case the user agent does its best to match the value once all other more stringent constraints are met. properties if the value of a constraindouble is an object rather than a number, it may have the properties below in addition the properties it inherits from doublerange. exact a double-precision floating-point number specifying a specific, required, value the property must have to be considered acceptable. ideal a double-precision floating-point number specifying a value the property would ideally have, but which can be considered optional if necessary to find a match. specifications speci...
ConstrainULong - Web APIs
nge of property values) to also support an exact value and/or an ideal value the property should take on. in addition, you can specify the value as a simple long integer value, in which case the user agent does its best to match the value once all other more stringent constraints are met. properties if the value of a constrainulong is an object rather than a number, it may have the properties below in addition to the properties it inherits from ulongrange. exact an integer specifying precise, required, value the property must have to be considered acceptable. ideal an integer specifying a value the property would ideally have, but which can be considered optional if necessary to find a match. specifications specification status comment media capture and stre...
ContentIndex.delete() - Web APIs
he delete() method of the contentindex interface unregisters an item from the currently indexed content. calling delete() only affects the index. it does not delete anything from the cache. syntax contentindex.delete(id).then(...); parameters this method receives no parameters. return value returns a promise that resolves with undefined exceptions no exceptions are thrown. examples below is an asynchronous function, that removes an item from the content index. we receive a reference to the current serviceworkerregistration, which allows us to access the index property and thus access the delete method. async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!regi...
ContentIndexEvent - Web APIs
emoved. 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. constructor contentindexevent() creates and returns a new contentindexevent object whose type and other options are configured as specified. properties in addition to the properties listed below, this interface inherits the properties of its parent interface, extendableevent. id read only a string which identifies the deleted content index via it's id. methods 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 ...
ConvolverNode() - Web APIs
the convolvernode() constructor of the web audio api creates a new convolvernode object instance. syntax var convolvernode = new convolvernode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options optional options are as follows: audiobuffer: a mono, stereo, or 4-channel audiobuffer containing the (possibly multichannel) impulse response used by the convolvernode to create the reverb effect. disablenormalization: a boolean controlling whether the impulse response from the buffer will be scaled by an equal-power normalization, or not. the default is 'false'. return value a new convolvernode object instance. exceptions exception explanation notsupportederror the...
ConvolverNode - Web APIs
ntaining the (possibly multichannel) impulse response used by the convolvernode to create the reverb effect. convolvernode.normalize a boolean that controls whether the impulse response from the buffer will be scaled by an equal-power normalization when the buffer attribute is set, or not. methods no specific method; inherits methods from its parent, audionode. convolvernode example the following example shows basic usage of an audiocontext to create a convolver node. note: you will need to find an impulse response to complete the example below. see this codepen for an applied example. let audioctx = new window.audiocontext(); async function createreverb() { let convolver = audioctx.createconvolver(); // load impulse response from file let response = await fetch...
CredentialsContainer.preventSilentAccess() - Web APIs
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. ...
CredentialsContainer - Web APIs
instance based on the provided options, or null if no credential object can be created. in exceptional circumstances, the promise may reject. credentialscontainer.get()secure context returns a promise that resolves with the credential instance that matches the provided parameters. credentialscontainer.preventsilentaccess()secure context 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. earlier versions of the spec called this method requireusermediation(). see browser compatibility for support details. credentialscontainer.store()secure context stores a set of...
Crypto.subtle - Web APIs
Web › API › Crypto › subtle
the crypto.subtle read-only property returns a subtlecrypto which can then be used to perform low-level cryptographic operations. syntax var crypto = crypto.subtle; value a subtlecrypto object you can use to interact with the web crypto api's low-level cryptography features. specifications specification status comment web cryptography apithe definition of 'crypto.subtle' in that specification. recommendation initial definition. ...
Crypto - Web APIs
Web › API › Crypto
note: this feature is available in web workers. the web crypto api is accessed through the window.crypto property, which is a crypto object. properties this interface implements properties defined on randomsource. crypto.subtle read only secure context returns a subtlecrypto object providing access to common cryptographic primitives, like hashing, signing, encryption, or decryption. methods this interface implements methods defined on randomsource. ...
CryptoKey - Web APIs
Web › API › CryptoKey
the cryptokey interface of the web crypto api represents a cryptographic key obtained from one of the subtlecrypto methods generatekey(), derivekey(), importkey(), or unwrapkey(). for security reasons, the cryptokey interface can only be used in a secure context. properties cryptokey.type string which may take one of the following values: "secret": this key is a secret key for use with a symmetric algorithm. "private": this key is the private half of an asymmetric algorithm's cryptokeypair. "public": this key is the public half of an asymmetric algorithm's cryptokeypair. cryptokey.extractable boolean indicating whether or not the key may be extracted using subtlecrypto.exportkey() or subtlecrypto.wrapkey(). true: the key may be extracted. false the k...
CustomElementRegistry - Web APIs
the custom element is not defined. customelementregistry.upgrade() upgrades a custom element directly, even before it is connected to its shadow root. customelementregistry.whendefined() returns an empty promise that resolves when a custom element becomes defined with the given name. if such a custom element is already defined, the returned promise is immediately fulfilled. examples the following code is taken from our word-count-web-component example (see it live also). note how we use the customelementregistry.define() method to define the custom element after creating its class. // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // count words in element's parent element ...
CustomEvent() - Web APIs
the customevent() constructor creates a new customevent. note: this feature is available in web workers. syntax event = new customevent(typearg, customeventinit); parameters typearg a domstring representing the name of the event. customeventinit optional a customeventinit dictionary, having the following fields: "detail", optional and defaulting to null, of type any, that is an event-dependent value associated with the event. the customeventinit dictionary also accepts fields from the eventinit dictionary. return value a new customevent object of the specified type, with any other properties configured according to the customeventinit dictionary (if one was provided). example // add an appropriate event listener obj.addeventlistener("cat", function(e) { process(...
CustomEvent - Web APIs
his is the object to which the event is currently slated to be sent. it's possible this has been changed along the way through retargeting. event.deeppath an array of dom nodes through which the event has bubbled. event.defaultprevented read only indicates whether or not the call to event.preventdefault() canceled the event. event.eventphase read only indicates which phase of the event flow is being processed. event.explicitoriginaltarget read only the explicit original target of the event (mozilla-specific.) event.originaltarget read only the original target of the event, before any retargetings. (mozilla-specific.) event.returnvalue a historical property introduced by internet explorer and eventually adopted into the dom specification in order to ensure existing sites ...
DOMMatrixReadOnly.scale() - Web APIs
not modified. if a scale is applied about the z-axis, the resulting matrix will be a 4x4 3d matrix. note: at time of writing, firefox still supports an older version of the specification that accepts either one or three values. dommatrix.scale(scale[, originx][, originy]) we'll show an example of how you can deal with the cross-browser support implications of this in the examples section, below. examples this svg contains three squares, one red, one blue, and one green, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 25 25"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> <rect id="transformedorigin" width="25" height="25" fill="green" /> </svg> this javascript first creates an identity...
DOMMatrixReadOnly.translate() - Web APIs
nal matrix is not modified. if a translation is applied about the z-axis, the resulting matrix will be a 4x4 3d matrix. examples this svg contains two squares, one red and one blue, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 50 50"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> </svg> the following javascript first creates an identity matrix, then uses the translate() method to create a new, translated matrix — which is then applied to the blue square as a transform. the red square is left in place. const matrix = new dommatrixreadonly().translate(25, 25); document.queryselector('#transformed').setattribute('transform', matrix.tostring()); screenshotlive sample specifications ...
DOMPoint.fromPoint() - Web APIs
table and may be changed at any time. examples creating a mutable point from a read-only point if you have a dompointreadonly object, you can easily create a mutable copy of that point: var mutablepoint = dompoint.frompoint(readonlypoint); creating a 2d point this sample creates a 2d point, specifying an inline object that includes the values to use for x and y. the z and w properties are allowed to keep their default values (0 and 1 respectively). var center = dompoint.frompoint({x: 75, y: -50, z: -55, w: 0.25}); specifications specification status comment geometry interfaces module level 1the definition of 'frompoint()' in that specification. candidate recommendation initial definition ...
DOMPoint.w - Web APIs
Web › API › DOMPoint › w
the dompoint interface's w property holds the point's perspective value, w, for a point in space. syntax var perspective = dompoint.w; value a double-precision floating-point value indicating the w perspective 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). the default is 1.0. specifications specification status comment geometry interfaces module level 1the definition of 'w' in that specification. candidate recommendation initial definition ...
DOMPoint.x - Web APIs
Web › API › DOMPoint › x
the horizontal coordinate, x, for a point in space. in general, positive values x mean to the right, and negative values of x means to the left, barring any transforms that may have altered the orientation of the axes. syntax var xpos = dompoint.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 recommendation initial definition ...
DOMPoint.y - Web APIs
Web › API › DOMPoint › y
the dompoint interface's y property holds the vertical coordinate, y, for a point in space. unless transforms have been applied to alter the orientation, the value of y increases downward and decreases upward. syntax var ypos = dompoint.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 recommendation initial definition ...
DOMPoint.z - Web APIs
Web › API › DOMPoint › z
ess transforms have changed the orientation, a z of 0 is the plane of the screen, with positive values extending outward toward the user from the screen, and negative values receding into the distance behind the screen. syntax var zpos = dompoint.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 1the definition of 'z' in that specification. candidate recommendation initial definition ...
DOMPointInit.w - Web APIs
Web › API › DOMPointInit › w
d to specify the w perspective value of a point in space when either creating or serializing to json a dompoint or dompointreadonly object. syntax var dompointinit = { w: wperspective }; dompointinit.w = wperspective; var wperspective = dompointinit.w; value a double-precision floating-point value indicating the point's w perspective value. this value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be nan or ±infinity). there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created. this method is, by inheritance, also available as dompoint.frompoin...
DOMPointInit.x - Web APIs
Web › API › DOMPointInit › x
only. in general, positive values x mean to the right, and negative values of x means to the left, assuming that transforms have not altered the orientation of the axes. 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. this value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be nan or ±infinity). if this property is missing when the dompointinit object is passed into frompoint(), the value is assumed to be 0 by default. dompointinit is used as an input when calling either dompointreadonly.frompoint() or dompoint.frompoint(), and is returned by the dompointreadonly.tojson() and dompoint.tojson() methods. specific...
DOMPointInit.y - Web APIs
Web › API › DOMPointInit › y
the right and decreases to the left, becoming negative to the left of the origin. this may change if transforms have been applied causing the axes' orientation to change. syntax var dompointinit = { y: ypos }; dompointinit.y = ypos; var ypos = dompointinit.y; value a double-precision floating-point value indicating the point's y-coordinate. this value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be nan or ±infinity). if this property is missing when the dompointinit object is passed into frompoint(), the value is assumed to be 0 by default. there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordi...
DOMPointInit.z - Web APIs
Web › API › DOMPointInit › z
om the user, with negative values being behind the screen, receding into the distance. of course, if transforms have been applied, the axes may have changed orientation. syntax var dompointinit = { z: zpos }; dompointinit.z = zpos; var zpos = dompointinit.z; value a double-precision floating-point value indicating the point's z-coordinate. this value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be nan or ±infinity). there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created. this method is, by inheritance, also available as dompoint.frompoin...
DOMPointReadOnly() - Web APIs
the default value is 0. w optional the value of the perspective, w, as a floating point number. the default is 1. note: each of these values is what's called an unrestricted number. in addition to any finite floating-point value, you may use special values such as ±infinity and nan. return value a new dompointreadonly object representing the specified location in space. examples the following code demonstrates creating both 2d and 3d points. var point2d = new dompointreadonly(50, 25); var point3d = new dompointreadonly(50, 0, 10); var perspectivepoint3d = new dompointreadonly(50, 50, 25, 0.5); specifications specification status comment geometry interfaces module level 1the definition of 'dompointreadonly' in that specification. candidate recommendatio...
DOMPointReadOnly.fromPoint() - Web APIs
a dompointinit-compliant object, which includes both dompoint and dompointreadonly, from which to take the values of the new point's properties. return value a new dompointreadonly object (which is identical to the source point). examples creating a 2d point this sample creates a 2d point, specifying an inline object that includes the values to use for x and y. the z and w properties are allowed to keep their default values (0 and 1 respectively). const point2d = dompointreadonly.frompoint({x: 25, y: 25}) creating a 3d point using an existing point this example creates a point, origpoint, of type dompoint, using new dompoint(). that point is then used as the input for frompoint() to create a new point, newpoint. const origpoint = new dompoint(25, 25, 100, 0.5) const newpoint = dom...
DOMPointReadOnly.w - Web APIs
e's w property holds the point's perspective value, w, 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. syntax const perspective = somedompointreadonly.w value a double-precision floating-point value indicating the w perspective 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). the default is 1.0. specifications specification status comment geometry interfaces module level 1the definition of 'w' in that specification. candidate recommendation initial definition ...
DOMPointReadOnly.x - Web APIs
ript 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 recommendation initial definition ...
DOMPointReadOnly.y - Web APIs
alue 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 recommendation initial definition ...
DOMPointReadOnly.z - Web APIs
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 1the definition of 'z' in that specification. candidate recommendation initial definition ...
DOMRect - Web APIs
Web › API › DOMRect
returned it. for example, vreyeparameters.renderrect from the defunct webvr api specified the viewport of a canvas into which visuals for one eye of a head mounted display should be rendered. it inherits from its parent, domrectreadonly. ...
DOMTokenList.add() - Web APIs
Web › API › DOMTokenList › add
we then add a new token to the list, and write the list into the <span>'s node.textcontent. ...
DOMTokenList.contains() - Web APIs
ontains() method of the domtokenlist interface returns a boolean — true if the underlying list contains the given token, otherwise false. syntax tokenlist.contains(token); parameters token a domstring representing the token you want to check for the existance of in the list. return value a boolean, which is true if the calling list contains token, otherwise false. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then test for the existence of "c" in the list, and write the result into the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; let result = classes.contains("c"); if ...
DOMTokenList.forEach() - Web APIs
ck function to execute for each element, eventually taking three arguments: currentvalue the current element being processed in the array. currentindex the index of the current element being processed in the array. listobj the array that foreach() is being applied to. thisarg optional value to use as this when executing callback. return value undefined. example in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the values using foreach(), writing each one to the <span>'s node.textcontent inside the foreach() inner function. html <span class="a b c"></span> javascript let span = document.queryselector("span"); let classes = span.classlist; let iterator ...
DOMTokenList.item() - Web APIs
Web › API › DOMTokenList › item
the item() method of the domtokenlist interface returns an item in the list by its index. syntax tokenlist.item(index) parameters index a domstring representing the index of the item you want to return. return value a domstring representing the returned item. it returns null if the number is greater than or equal to the length of the list. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then retrieve the last item in the list using item(tokenlist.length - 1), and write it into the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; let item = classes.item(classes.length-1); span...
DOMTokenList.length - Web APIs
the length read-only property of the domtokenlist interface is an integer representing the number of objects stored in the object. syntax tokenlist.length; value an integer. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist, then write the length of the list to the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; let length = classes.length; span.textcontent = `classlist length = ${length}`; the output looks like this: specifications specification status comment domthe definition of 'length' in that specification. living standard initial definitio...
DOMTokenList.remove() - Web APIs
the remove() method of the domtokenlist interface removes the specified tokens from the list. syntax tokenlist.remove(token1[, token2[, ...tokenn]]); parameters tokenn a domstring representing the token you want to remove from the list. if the string is not in the list, no error is thrown, and nothing happens. return value undefined examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then remove a token from the list, and write the list into the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; classes.remove("c"); span.textcontent = classes; the output looks like this: to re...
DOMTokenList.supports() - Web APIs
yntax let trueorfalse = element.supports(token) parameters token a domstring containing the token to query for. returns a boolean indicating whether the token was found. example let iframe = document.getelementbyid('display'); if (iframe.sandbox.supports('an-upcoming-feature')) { // support code for mystery future feature } else { // fallback code } if (iframe.sandbox.supports('allow-scripts')) { // instruct frame to run javascript // // (note: this feature is well-supported; this is just an example!) // } specifications specification status comment credential management level 1 working draft initial definition. ...
DOMTokenList.toggle() - Web APIs
rameters token a domstring representing the token you want to toggle. force optional a boolean that, if included, turns the toggle into a one way-only operation. if set to false, then token will only be removed, but not added. if set to true, then token will only be added, but not removed. return value a boolean indicating whether token is in the list after the call. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then replace a token in the list, and write the list into the <span>'s node.textcontent. first, the html: <span class="a b">classlist is 'a b'</span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; span.addeventlistener('click', functio...
DOMTokenList.value - Web APIs
the value property of the domtokenlist interface is a stringifier that returns the value of the list as a domstring, or clears and sets the list to the given value. syntax tokenlist.value; value a domstring examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist, then write the value of the list to the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; span.textcontent = classes.value; the output looks like this: specifications specification status comment domthe definition of 'value' in that specification. living standard initial definition ...
DataTransfer.items - Web APIs
<style> div { margin: 0em; padding: 2em; } #target { border: 1px solid black; } </style> <script> function dragstart_handler(ev) { console.log("dragstart: target.id = " + ev.target.id); // add this element's id to the drag payload so the drop handler will // know which element to add to its tree ev.datatransfer.setdata("text/plain", ev.target.id); ev.datatransfer.effectallowed = "move"; } function drop_handler(ev) { console.log("drop: target.id = " + ev.target.id); ev.preventdefault(); // get the id of the target and add the moved element to the target's dom var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); // print each format type if (ev.datatransfer.types != null) { for (var i=0; i < ev.datatransfer.types.
DataTransfer.setDragImage() - Web APIs
this image is created automatically, so you do not need to create it yourself. however, if a custom image is desired, the datatransfer.setdragimage() method can be used to set the custom image to be used. the image will typically be an <image> element but it can also be a <canvas> or any other visible element. the method's x and y coordinates define how the image should appear relative to the mouse pointer. these coordinates define the offset into the image where the mouse cursor should be. ...
DataTransfer.types - Web APIs
<style> div { margin: 0em; padding: 2em; } #target { border: 1px solid black; } </style> <script> function dragstart_handler(ev) { console.log("dragstart: target.id = " + ev.target.id); // add this element's id to the drag payload so the drop handler will // know which element to add to its tree ev.datatransfer.setdata("text/plain", ev.target.id); ev.datatransfer.effectallowed = "move"; } function drop_handler(ev) { console.log("drop: target.id = " + ev.target.id); ev.preventdefault(); // get the id of the target and add the moved element to the target's dom var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); // print each format type if (ev.datatransfer.types != null) { for (var i=0; i < ev.datatransfer.types.
DataTransfer - Web APIs
drag and drop api. this object is available from the datatransfer property of all drag events. constructor datatransfer() creates and returns a new datatransfer object. properties standard properties datatransfer.dropeffect gets the type of drag-and-drop operation currently selected or sets the operation to a new type. the value must be none, copy, link or move. datatransfer.effectallowed provides all of the types of operations that are possible. must be one of none, copy, copylink, copymove, link, linkmove, move, all or uninitialized. datatransfer.files contains a list of all the local files available on the data transfer. if the drag operation doesn't involve dragging files, this property is an empty list. datatransfer.items read only gives a datatransferitemlist object ...
DataTransferItem.getAsString() - Web APIs
the datatransferitem.getasstring() method invokes the given callback with the drag data item's string data as the argument if the item's kind is a plain unicode string (i.e. kind is string). syntax datatransferitem.getasstring(callback); parameters callback a callback function that has access to the data transfer item's string data. see callback below for details. return value undefined callback the callback parameter is a callback function which accepts one parameter: domstring the drag data item's string data. the callback return value is undefined. example this example shows the use of the getasstring() method as an inline function in a drop event handler. function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.items; for ...
DataTransferItem.kind - Web APIs
'string' if the kind of drag data item is a plain unicode string. example this example shows the use of the kind property. ...
DedicatedWorkerGlobalScope.close() - Web APIs
the close() method of the dedicatedworkerglobalscope interface discards any tasks queued in the dedicatedworkerglobalscope's event loop, effectively 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 ...
DedicatedWorkerGlobalScope.onmessage - Web APIs
messages are passed to the worker when the value inside the form input first changes. ...
DedicatedWorkerGlobalScope.postMessage() - Web APIs
, which includes cyclical references. transferlist optional an optional array of transferable objects to transfer ownership of. if the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and it becomes available only to the main thread it was sent to. only messageport and arraybuffer objects can be transferred. returns void. example the following code snippet shows worker.js, in which an onmessage handler is used to handle messages from the main script. inside the handler a calculation is done from which a result message is created; this is then sent back to the main thread using postmessage(workerresult); onmessage = function(e) { console.log('message received from main script'); var workerresult = 'result: ' + (e.data[0] * e.dat...
DelayNode() - Web APIs
a delay between the arrival of an input data, and its propagation to the output. syntax var delaynode = new delaynode(context); var delaynode = new delaynode(context, options); parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext or offlineaudiocontext. options optional an object specifying the delay node options. can contain the following members: delaytime: the initial delay time for the node, in seconds. the default is 0. maxdelaytime: the maximum delay time for the node, in seconds. defaults to 1. return value a new delaynode object instance. example const audioctx = new audiocontext(); const delaynode = new delaynode(audioctx, { delaytime: 0.5, maxdelaytime: 2, }); specifications specification ...
DelayNode.delayTime - Web APIs
0, and its maximum value is defined by the maxdelaytime argument of the audiocontext.createdelay() method that created it. 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. 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). if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || win...
DelayNode - Web APIs
Web › API › DelayNode
nstance. alternatively, you can use the baseaudiocontext.createdelay() factory method. properties inherits properties from its parent, audionode. delaynode.delaytime read only is an a-rate audioparam representing the amount of delay to apply, specified in seconds. methods no specific methods; inherits methods from its parent, audionode. 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). if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || win...
Using light sensors - Web APIs
tect changes in light intensity. how does it work? when the light sensor of the device detects a change in light intensity, the browser is notified of the change and fires a devicelightevent event. the event gives information about the 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. window.addeventlistener("devicelight", function (event) { // read out the lux value var luminosity = event.value; alert(luminosity); }); example: window.addeventlistener('devicelight', function(event) { var bodybg= document.body.style; //event.value ...
DeviceMotionEvent.DeviceMotionEvent() - Web APIs
acceleration is expressed in m/s2. accelerationincludinggravity: an object giving the acceleration of the device on the three axis x, y and z with the effect of gravity. acceleration is expressed in m/s2. ...
DeviceOrientationEvent.DeviceOrientationEvent() - Web APIs
the deviceorientationevent constructor creates a new deviceorientationevent. syntax var deviceorientationevent = new deviceorientationevent(type[, options]) parameters type either "deviceorientation" or "deviceorientationabsolute". if the later, then options.absolute should be true. options optional options are as follows: alpha: a number representing the motion of the device around the z axis, express in degrees with values ranging from 0 to 360. beta: a number representing the motion of the device around the x axis, express in degrees with values ranging from -180 to 180. this represents a front to back motion of the device. gamma: a number representing the motion of the device around the y axis, express in degrees with values ranging from -90 to 90. this represents a le...
DisplayMediaStreamConstraints.audio - Web APIs
to process the audio prior to adding it to the stream. note: the specification for the screen capture api does not define what the contents of the audio track should be. this is left up to the user agent to decide. likely sources are the computer's system audio output and the user's microphone, but there is no way to specify which source to use. syntax displaymediastreamconstraints.audio = allowaudioflag; displaymediastreamconstraints.audio = mediatrackconstraints; displaymediastreamconstraints = { audio: allowaudioflag|mediatrackconstraints; } value the value may be either a boolean or a mediatrackconstraints object. if a boolean is specified, a value of true indicates that an audio track should be included in the stream returned by getdisplaymedia(), if an appropriate audio sour...
Document: DOMContentLoaded event - Web APIs
, load, should be used only to detect a fully-loaded page. it is a common mistake to use load where domcontentloaded would be more appropriate. synchronous javascript pauses parsing of the dom. if you want the dom to get parsed as fast as possible after the user has requested the page, you can make your javascript asynchronous and optimize loading of stylesheets. if loaded as usual, stylesheets slow down dom parsing as they're loaded in parallel, "stealing" traffic from the main html document. examples basic usage document.addeventlistener('domcontentloaded', (event) => { console.log('dom fully loaded and parsed'); }); delaying domcontentloaded <script> document.addeventlistener('domcontentloaded', (event) => { console.log('dom fully loaded and parsed'); }); for( let i = 0...
Document.adoptNode() - Web APIs
for more on the node.ownerdocument issues, see the w3c dom faq. specifications specification status comment domthe definition of 'document.adoptnode' in that specification. living standard ...
Document.all - Web APIs
Web › API › Document › all
ar htmlallcollection = document.all; value an htmlallcollection which contains every element in the document. conversion to boolean document.all is the only falsy object accessible to javascript, because it has the [[ishtmldda]] internal slot. this was done because of compatibility with older versions of internet explorer. more information about this can be found in this answer from stackoverflow. specifications specification status comment html living standardthe definition of 'all' in that specification. living standard initial definition. defined in the obsolete and legacy apis section. ...
Document.anchors - Web APIs
Web › API › Document › anchors
the anchors read-only property of the document interface returns a list of all of the anchors in the document. syntax nodelist = document.anchors; value an htmlcollection. ...
Document.caretRangeFromPoint() - Web APIs
the caretrangefrompoint() method of the document interface returns a range object for the document fragment under the specified coordinates. syntax var range = document.caretrangefrompoint(float x, float y); parameters x a horizontal position within the current viewport. y a vertical position within the current viewport. returns one of the following: a range. null, if x or y are negative, outside viewport, or there is no text entry node. example basic demo: when clicking in a paragraph insert a line break at the caret position: html <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...
Document.createAttribute() - Web APIs
syntax attribute = document.createattribute(name) parameters name is a string containing the name of the attribute. return value a attr node. ...
Document.createDocumentFragment() - Web APIs
objects which are never part of the main dom tree. the usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the dom tree. in the dom tree, the document fragment is replaced by all its children. since the document fragment is in memory and not part of the main dom tree, appending children to it does not cause page reflow (computation of element's position and geometry). historically, using document fragments 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. html <ul ...
Document.createEvent() - Web APIs
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 events module event events specifications specification status comment domthe definition of 'document.createevent' in that specification. living standar...
Document.createNodeIterator() - Web APIs
fication, and has therefore been removed. this parameter indicated whether or not the children of entity reference nodes were visible to the iterator. since such nodes were never created in browsers, this paramater had no effect. example const nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode(node) { return node.nodename.tolowercase() === 'p' ? nodefilter.filter_accept : nodefilter.filter_reject; } } ); const pars = []; let currentnode; while (currentnode = nodeiterator.nextnode()) { pars.push(currentnode); } specifications specification status comment domthe definition of 'document.createnodeiterator' in that specification. living standard ...
Document.createProcessingInstruction() - Web APIs
sulting processinginstruction node. target is a string containing the first part of the processing instruction (i.e., <?target … ?>) data is a string containing any information the processing instruction should carry, after the target. the data is up to you, but it can't contain ?>, since that closes the processing instruction. exceptions dom_invalid_character throws if either of the following are true: the processing instruction target is invalid — it should be a valid xml name that doesn't contain "xml", "xml", or any case combination of the two, other than standardized ones such as <?xml-stylesheet ?>. the closing processing instruction sequence (?>) is part of the data. example var doc = new domparser().parsefromstring('<foo />', 'application/xml'); var pi = doc.c...
Document.createTouchList() - Web APIs
r list = documenttouch.createtouchlist([touch1 [, touch2 [, ...]]]); parameters touches zero or more touch objects. note: firefox also accepts an array of touch objects. return value list a touchlist object containing the touch objects specified by the touches parameter. example this example illustrates using the document.createtouchlist() method to create touchlist objects. in following code snippet, some touch objects are created for the target element and those touch points are then used to create some touchlist objects. var target = document.getelementbyid("target"); // create some touch points var touch1 = document.createtouch(window, target, 1, 15, 20, 35, 40); var touch2 = document.createtouch(window, target, 2, 25, 30, 45, 50); // create an empty touchlist objects v...
Document.createTreeWalker() - Web APIs
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 acceptable each node (it could reduce the set in the acceptnode() method instead), and then makes use of tree walker iterator that is created to advance through the nodes (now all elements) and push them into an array. var treewalker = document.createtreewalker( document.body, nodefi...
Document.designMode - Web APIs
the earlier versions of chrome and ie default to "inherit". starting in chrome 43, the default is "off" and "inherit" is no longer supported. in ie6-10, the value is capitalized. syntax var mode = document.designmode; document.designmode = value; value a string indicating whether designmode is (or should be) set to on or off. valid values are on and off. ...
Document.domain - Web APIs
Web › API › Document › domain
in portion of the origin of the current document, as used by the same origin policy. if this property is successfully set, the port part of the origin is also set to null. syntax const domainstring = document.domain document.domain = domainstring value the domain portion of the current document's origin. ...
Document.evaluate() - Web APIs
Web › API › Document › evaluate
text of all h2 elements note, in the above example, a more verbose xpath is preferred over common shortcuts such as //h2. generally, more specific xpath selectors as in the above example usually gives a significant performance improvement, especially on very large documents. this is because the evaluation of the query spends does not waste time visiting unnecessary nodes. using // is generally slow as it visits every node from the root and all subnodes looking for possible matches. further optimization can be achieved by careful use of the context parameter. for example, if you know the content you are looking for is somewhere inside the body tag, you can use this: document.evaluate(".//h2", document.body, null, xpathresult.any_type, null); notice in the above document.body has been use...
Document.execCommand() - Web APIs
tsize adds a <small> tag around the selection or at the insertion point. (not supported by internet explorer.) defaultparagraphseparator changes the paragraph separator used when new paragraphs are created in editable text regions. see differences in markup generation for more details. delete deletes the current selection. enableabsolutepositioneditor enables or disables the grabber that allows absolutely-positioned elements to be moved around. the grabber is disabled by default since firefox 64 (bug 1490641). enableinlinetableediting enables or disables the table row/column insertion and deletion controls. the controls are disabled by default since firefox 64 (bug 1490641). enableobjectresizing enables or disables the resize handles on images, tables, and absolutely-positioned ele...
Document.fullscreenEnabled - Web APIs
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. ...
Document.getAnimations() - Web APIs
ffect whose target elements are descendants of the document. this array includes css animations, css transitions, and web animations. syntax var allanimations = document.getanimations(); parameters none. return value an array of animation objects, each representing one animation currently associated with elements which are descendants of the document on which it's called. examples the following code snippet will slow down all animations on a page by halving their animation.playbackrate. document.getanimations().foreach( function (animation) { animation.playbackrate *= .5; } ); specifications specification status comment web animationsthe definition of 'document.getanimations()' in that specification. working draft ...
Document.getElementsByName() - Web APIs
etelementsbyname("up"); console.log(up_names[0].tagname); // displays "input" </script> </html> notes the name attribute can only be applied in (x)html documents. the returned nodelist collection contains all elements with the given name, such as <meta>, <object>, and even elements which do not support the name attribute at all. the getelementsbyname method works differently in ie10 and below. there, getelementsbyname() also returns elements that have an id attribute with the specified value. be careful not to use the same string as both a name and an id. the getelementsbyname method works differently in ie. there, getelementsbyname() does not return all elements which may not have a name attribute (such as <span>). both ie and edge return an htmlcollection, not a nodelist spe...
Document.images - Web APIs
Web › API › Document › images
ment. syntax var imagecollection = document.images; value an htmlcollection providing a live list of all of the images contained in the current document. each entry in the collection is an htmlimageelement representing a single image element. usage notes you can use either javascript array notation or the item() method on the returned collection to access the items in the collection. the following are equivalent: firstimage = imagecollection.item(0); firstimage = imagecollection[0]; example this example looks through the list of images and finds one whose name is "banner.gif". var ilist = document.images; for(var i = 0; i < ilist.length; i++) { if(ilist[i].src == 'banner.gif') { // found the banner } } specifications specification status comment ...
Document: keydown event - Web APIs
he keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. bubbles yes cancelable yes interface keyboardevent event handler property onkeydown the keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. for example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. an uppercase "a" is reported as 65 by all events. since firefox 65, the keydown and keyup events are now fired during ime composition, to improve cross-browser compatibility for cjkt users (bug 354358, also see keydown and keyup events are now fired during ime composition for more useful details). to ignore all keydown...
Document: keyup event - Web APIs
an uppercase "a" is reported as 65 by all events. ...
Document: pointercancel event - Web APIs
active. the browser decides that the user started pointer input accidentally. this can happen if, for example, the hardware supports palm rejection to prevent a hand resting on the display while using a stylus from accidentally triggering events. the touch-action css property prevents the input from continuing. after the pointercancel event is fired, the browser will also send pointerout followed by pointerleave. examples using addeventlistener(): document.addeventlistener('pointercancel', (event) => { console.log('pointer event cancelled') }); using the onpointercancel event handler property: document.onpointercancel = (event) => { console.log('pointer event cancelled') }; specifications specification status pointer events obsolete ...
Document.readyState - Web APIs
interactive the document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading. ...
Document.registerElement() - Web APIs
optionsoptional an object with properties prototype to base the custom element on, and extends, an existing tag to extend. both of these are optional. example here is a very simple example: var mytag = document.registerelement('my-tag'); now the new tag is registered in the browser. the mytag variable holds a constructor that you can use to create a my-tag element in the document as follows: document.body.appendchild(new mytag()); this inserts an empty my-tag element that will be visible if you use the browser's developer tools. it will not be visible if you use the browser's view source capability. and it won't be visible in the browser unless you add some content to the tag. here is one way to add content to the new tag: var mytag = document.getelementsbytagname("my-tag")[0]; ...
Document: scroll event - Web APIs
ling has completed. see bootstrap issue #16202. safari and wkwebviews are not affected by this bug. examples scroll event throttling since scroll events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as dom modifications. instead, it is recommended to throttle the event using requestanimationframe(), settimeout(), or a customevent, as follows. note, however, that input events and animation frames are fired at about the same rate, and therefore the optimization below is often unnecessary. this example optimizes thescroll event for requestanimationframe. // reference: http://www.html5rocks.com/en/tutorials/speed/animations/ let last_known_scroll_position = 0; let ticking = false; function dosomething(scroll_pos) { // do something...
Document.title - Web APIs
Web › API › Document › title
document.title = newtitle; newtitle is the new title of the document. ...
Document.writeln() - Web APIs
Web › API › Document › writeln
syntax document.writeln(line); parameters line is string containing a line of text. example document.writeln("<p>enter password:</p>"); notes document.writeln is the same as document.write but adds a newline. note: document.writeln (like document.write) does not work in xhtml documents (you'll get a "operation is not supported" (ns_error_dom_not_supported_err) error on the error console). this is the case if opening a local file with a .xhtml file extension or for any document served with an application/xhtml+xml mime type. more information is available in the w3c xhtml faq. ...
Document.xmlVersion - Web APIs
tion (e.g., <?xml version="1.0"?>) or "1.0" if the declaration is absent. this attribute was never really useful, since it always returned 1.0, and has been removed in dom level 4. as such, firefox 10 no longer implements it. ...
DocumentOrShadowRoot.activeElement - Web APIs
ement is receiving user input events) is not the same thing as selection (the currently highlighted part of the document). you can get the current selection using window.getselection(). syntax element = documentorshadowroot.activeelement value the element which currently has focus, <body> or null if there is no focused element. example html <p>select some text from one of the text areas below:</p> <form> <textarea name="ta-example-one" id="ta-example-one" rows="7" cols="40">this is text area one. lorem ipsum dolor sit amet, consectetur adipiscing elit. donec tincidunt, lorem a porttitor molestie, odio nibh iaculis libero, et accumsan nunc orci eu dui.</textarea> <textarea name="ta-example-two" id="ta-example-two" rows="7" cols="40">this is text area two. fusce ullamcorper, nisl a...
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
ion object, containing the dom node, along with the caret and caret's character offset within that node. syntax var caretposition = document.caretpositionfrompoint(float x, float y); parameters x the horizontal coordinate of a point. y the vertical coordinate of a point. returns a caretposition object. example this example inserts line breaks wherever you click. the code for it is below the demo. demo html content <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 lorem ipsum dolor sit amet.</p> javascript content function insertbreakatpoint(e) { var ran...
DocumentOrShadowRoot.elementFromPoint() - Web APIs
to another document (for example, the document of an <iframe>), that document's parent element is returned (the <iframe> itself). if the element at the given point is anonymous or xbl generated content, such as a textbox's scroll bars, then the first non-anonymous ancestor element (for example, the textbox) is returned. elements with pointer-events set to none will be ignored, and the element below it will be returned. if the method is run on another document (like an <iframe>'s subdocument), the coordinates are relative to the document where the method is being called. if the specified point is outside the visible bounds of the document or either coordinate is negative, the result is null. if you need to find the specific position inside the element, use document.caretpositionfrompoint(...
DocumentOrShadowRoot.styleSheets - Web APIs
orshadowroot interface returns a stylesheetlist of cssstylesheet objects, for stylesheets explicitly linked into or embedded in a document. examples function getstylesheet(unique_title) { for (var i=0; i<document.stylesheets.length; i++) { var sheet = document.stylesheets[i]; if (sheet.title == unique_title) { return sheet; } } } notes the returned list is ordered as follows: stylesheets retrieved from <link> headers are placed first, sorted in header order. stylesheets retrieved from the dom are placed after, sorted in tree order. specifications specification status comment shadow domthe definition of 'documentorshadowroot' in that specification. obsolete initial definition. ...
DocumentOrShadowRoot - Web APIs
properties documentorshadowroot.activeelementread only returns the element within the shadow tree that has focus. documentorshadowroot.fullscreenelementread only returns the element that's currently in full screen mode for this document. documentorshadowroot.pointerlockelement read only returns the element set as the target for mouse events while the pointer is locked. it returns null if lock is pending, the pointer is unlocked, or if the target is in another document. ...
DocumentTimeline.DocumentTimeline() - Web APIs
ters options an object specifying options for the new timeline. currently the only supported option is the origintime member which specifies the zero time for the documenttimeline as a real number of milliseconds relative to the navigationstart moment of the active document for the current browsing context. examples we could share a single documenttimeline among multiple animations, 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: var cats = document.queryselectorall('.sharedtimelinecat'); cats = array.prototype.slice.call(cats); var sharedtimeline = new documenttimeline({ origintime: 500 }); cats.foreach(function(cat) { var catkeyframes = new keyframe...
DocumentTimeline - Web APIs
creates a new documenttimeline object associated with the active document of the current browsing context. properties this interface inherits its property from its parent, animationtimeline. animationtimeline.currenttime returns the time value in milliseconds for this timeline or null if it is inactive. examples we could share a single documenttimeline among multiple animations, 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...
DocumentType - Web APIs
the documenttype interface represents a node containing a doctype. ...
Locating DOM elements using selectors - Web APIs
ntation 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 first element in the document whose id is one of main, basic, or exclamation. you may use any css selectors with the queryselector() and queryselectorall() methods. ...
DragEvent() - Web APIs
transfer objects have a processing and security model that is coordinated by the browser during drag-and-drops. this interface inherits properties from mouseevent and event. syntax event = new dragevent(type, drageventinit); arguments type is a domstring representing the name of the event (see dragevent event types). drageventinitoptional is a drageventinit dictionary, having the following fields: "datatransfer", optional and defaults to "null". the type is datatransfer. the drageventinit dictionary inherits from the mouseeventinit dictionary. specifications specification status comment html living standardthe definition of 'dragevent' in that specification. living standard html 5.1the definition of 'dragevent' in that specif...
DragEvent - Web APIs
Web › API › DragEvent
fired when an element is no longer the drag operation's immediate selection target. dragleave this event is fired when a dragged element or text selection leaves a valid drop target. dragover this event is fired continuously when an element or text selection is being dragged and the mouse pointer is over a valid drop target (every 50 ms when mouse is not moving else much faster between 5 ms (slow movement) and 1ms (fast movement) approximately. this firing pattern is different than mouseover ). dragstart this event is fired when the user starts dragging an element or text selection. drop this event is fired when an element or text selection is dropped on a valid drop target. globaleventhandlers globaleventhandlers.ondrag a global event handler for the drag event. globaleventhan...
DynamicsCompressorNode.attack - Web APIs
how quickly the signal is adapted when its volume is increased. the attack property's default value is 0.003 and it can be set between 0 and 1. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.attack.value = 0; value an audioparam. note: though the audioparam returned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynam...
DynamicsCompressorNode.knee - Web APIs
old where the curve smoothly transitions to the compressed portion. the knee property's default value is 30 and it can be set between 0 and 40. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.knee.value = 40; value an audioparam. note: though the audioparam returned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynam...
DynamicsCompressorNode.ratio - Web APIs
ange, in db, needed in the input for a 1 db change in the output. the ratio property's default value is 12 and it can be set between 1 and 20. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.ratio.value = 12; value an audioparam. note: though the audioparam returned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynam...
DynamicsCompressorNode.release - Web APIs
how quick the signal is adapted when its volume is reduced. the release property's default value is 0.25 and it can be set between 0 and 1. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.release.value = 0.25; value an audioparam. note: though the audioparam returned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynam...
DynamicsCompressorNode.threshold - Web APIs
above which the compression will start taking effect. the threshold property's default value is -24 and it can be set between -100 and 0. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.threshold.value = -50; value an audioparam. note: though the audioparam returned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynam...
EXT_color_buffer_float - Web APIs
bility to render a variety of floating point formats. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is available to webgl 2 contexts only. for webgl 1, see the ext_color_buffer_half_float and webgl_color_buffer_float extensions. extended methods the following sized formats become color-renderable: gl.r16f, gl.rg16f, gl.rgba16f, gl.r32f, gl.rg32f, gl.rgba32f, gl.r11f_g11f_b10f. color-renderable means: the webglrenderingcontext.renderbufferstorage() method now accepts these formats. framebuffers with attached textures of these formats may now be framebuffer_complete. examples gl must be a webgl2renderingcontext. this extension does ...
EXT_float_blend - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is available to both, webgl1 and webgl2 contexts. however, to use it, you need to enable the use of 32-bit floating-point draw buffers by enabling the extension webgl_color_buffer_float (for webgl1) or ext_color_buffer_float (for webgl2). doing so automatically enables ext_float_blend as well. ...
EXT_sRGB - Web APIs
Web › API › EXT sRGB
on() 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.srgb, gl.srgb8, gl.srgb8_alpha8 and gl.framebuffer_attachment_color_encoding. constants this extension exposes the following constants, which can be used in the teximage2d(), texsubimage2d(), renderbufferstorage() and getframebufferattachmentparameter() methods. ext.srgb_ext unsized srgb format that leaves the precision up to the driver. ext.srgb_alpha_ext unsized srgb format with unsized alpha component. ext.srgb8_alpha8_ext sized (8-bit) srgb and alpha formats. ext.framebuffer_attachment_color_encoding_ex...
EXT_shader_texture_lod - Web APIs
f detail). 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. it requires glsl #version 300 es. ...
EXT_texture_compression_rgtc - Web APIs
texsubimage2d(). ext.compressed_red_rgtc1_ext each 4x4 block of texels consists of 64 bits of unsigned red image data. see also bc4 unsigned. ext.compressed_signed_red_rgtc1_ext each 4x4 block of texels consists of 64 bits of signed red image data. see also bc4 signed. ext.compressed_red_green_rgtc2_ext each 4x4 block of texels consists of 64 bits of compressed unsigned red image data followed by 64 bits of compressed unsigned green image data. see also bc5 unsigned. ext.compressed_signed_red_green_rgtc2_ext each 4x4 block of texels consists of 64 bits of compressed signed red image data followed by 64 bits of compressed signed green image data. see also bc5 signed. examples var ext = gl.getextension('ext_texture_compression_rgtc'); var texture = gl.createtexture(); gl.bindtext...
EcKeyGenParams - Web APIs
s the algorithm parameter into subtlecrypto.generatekey(), when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as either of ecdsa or ecdh. properties name a domstring. this should be set to ecdsa or ecdh, depending on the algorithm you want to use. namedcurve a domstring representing the name of the elliptic curve to use. this may be any of the following names for nist-approved curves: p-256 p-384 p-521 examples see the examples for subtlecrypto.generatekey(). specifications specification status comment web cryptography apithe definition of 'subtlecrypto.eckeygenparams' in that specification. recommendation ...
EcKeyImportParams - Web APIs
into subtlecrypto.importkey() or subtlecrypto.unwrapkey(), when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as either of ecdsa or ecdh. properties name a domstring. this should be set to ecdsa or ecdh, depending on the algorithm you want to use. namedcurve a domstring representing the name of the elliptic curve to use. this may be any of the following names for nist-approved curves: p-256 p-384 p-521 examples see the examples for subtlecrypto.importkey(). specifications specification status comment web cryptography apithe definition of 'subtlecrypto.eckeyimportparams' in that specification. recommendation ...
EcdsaParams - Web APIs
the ecdsaparams dictionary of the web crypto api represents the object that should be passed as the algorithm parameter into subtlecrypto.sign() or subtlecrypto.verify() when using the ecdsa algorithm. properties name a domstring. this should be set to ecdsa. hash a domstring. an identifier for the digest algorithm to use. this should be one of the following: sha-256: selects the sha-256 algorithm. sha-384: selects the sha-384 algorithm. sha-512: selects the sha-512 algorithm. warning: sha-1 is also supported here but the sha-1 algorithm is considered vulnerable and should no longer be used. examples see the examples for subtlecrypto.sign() or subtlecrypto.verify(). specifications specification status comment web cryptography apithe defin...
EffectTiming.direction - Web APIs
mingproperties = { 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 following values, with the default being "normal": "normal" the animation runs forwards, from beginning to end, in the way we experience the flow of time. "reverse" the animation runs backwards, or "rewinds." "alternate" the animation switches direction after each iteration, going forward through the animation sequence the first iteration, then backward through the sequence the second iteration,...
EffectTiming.easing - Web APIs
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). both x values must be in the range [0, 1] or the definition is invalid. ease a decelerated rate of change, going from fast to slow. equivalent to cubic-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>) s...
EffectTiming.iterationStart - Web APIs
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 progress through that iteration. usually you'll use a value between 0.0 and 1.0 to indicate an offset into the first run of the animation at which to begin the animation performance, but any positive, non-infinite value is allowed. 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 animationeffectti...
Element: MSInertiaStart event - Web APIs
it is a proprietary event specific to microsoft edge and internet explorer. ...
Element.animate() - Web APIs
Web › API › Element › animate
ationcomposite optional determines how values build from iteration to iteration in this animation. can be set to accumulate or replace (see above). defaults to replace. return value returns an animation. examples in the demo down the rabbit hole (with the web animation api), we use the convenient animate() method to immediately create and play an animation on the #tunnel element to make it flow upwards, infinitely. notice the array of objects passed as keyframes and also the timing options block. document.getelementbyid("tunnel").animate([ // keyframes { transform: 'translatey(0px)' }, { transform: 'translatey(-300px)' } ], { // timing options duration: 1000, iterations: infinity }); implicit to/from keyframes in newer browser versions, you are able to set a beginning o...
Element.attributes - Web APIs
is a key/value pair of strings that represents any information regarding that attribute. syntax var attr = element.attributes; example basic examples // get the first <p> element in the document var para = document.getelementsbytagname("p")[0]; var atts = para.attributes; enumerating elements attributes numerical indexing is useful for going through all of an element's attributes. the following example runs through the attribute nodes for the element in the document with id "paragraph", and prints each attribute's value. <!doctype html> <html> <head> <title>attributes example</title> <script type="text/javascript"> function listattributes() { var paragraph = document.getelementbyid("paragraph"); var result = document.getelementbyid("result"); // first, let'...
Element: auxclick event - Web APIs
color(); } button.oncontextmenu = function(e) { e.preventdefault(); } notice that in addition to capturing the auxclick event using onauxclick, the contextmenu event is also captured, and preventdefault() called on that event, in order to prevent the context menu from popping up after the color change is applied. ...
Element: click event - Web APIs
element". known workarounds for this bug: set cursor: pointer; on the element or any of its ancestors. add a dummy onclick="void(0)" attribute to the element or any of its ancestors up to but not including <body>. use a typically interactive element (e.g., <a>) instead of one that isn't typically interactive (e.g., <div>). stop using click event delegation. safari mobile considers the following elements to be typically interactive (and thus they aren't affected by this bug): <a> (but it must have an href) <area> (but it must have an href) <button> <img> <input> <label> (but it must be associated with a form control) <textarea> this list is incomplete; you can help mdn by doing further testing/research and expanding it. examples this example displays the number of consecu...
Element.clientLeft - Web APIs
clientleft does not include the left margin or the left padding. clientleft is read-only. when layout.scrollbar.side preference is set to 1 or to 3 and when the text-direction is set to rtl, then the vertical scrollbar is positioned on the left and this impacts the way clientleft is computed. note: this property will round the value to an integer. ...
Element: compositionend event - Web APIs
ncelable yes interface compositionevent event handler property none examples const inputelement = document.queryselector('input[type="text"]'); inputelement.addeventlistener('compositionend', (event) => { console.log(`generated characters were: ${event.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="example" name="example"> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="25"></textarea> <button class="clear-log">clear</button> </div> css body { padding: .2rem; display: grid; grid-template-areas: "control lo...
Element: compositionstart event - Web APIs
elable yes interface compositionevent event handler property none examples const inputelement = document.queryselector('input[type="text"]'); inputelement.addeventlistener('compositionstart', (event) => { console.log(`generated characters were: ${event.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="example" name="example"> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="25"></textarea> <button class="clear-log">clear</button> </div> css body { padding: .2rem; display: grid; grid-template-areas: "control lo...
Element: compositionupdate event - Web APIs
lable yes interface compositionevent event handler property none examples const inputelement = document.queryselector('input[type="text"]'); inputelement.addeventlistener('compositionupdate', (event) => { console.log(`generated characters were: ${event.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="example" name="example"> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="25"></textarea> <button class="clear-log">clear</button> </div> css body { padding: .2rem; display: grid; grid-template-areas: "control lo...
Element.currentStyle - Web APIs
element.currentstyle is a proprietary property which is similar to the standardized window.getcomputedstyle() method. it is available in old versions of microsoft internet explorer. however, it returns the units set in css while window.getcomputedstyle() returns the values in pixels. polyfill this polyfill returns the values in pixels and is likely to be rather slow, as it has to call window.getcomputedstyle() every time its value is read. /* any copyright is dedicated to the public domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ if (!("currentstyle" in element.prototype)) { object.defineproperty(element.prototype, "currentstyle", { get: function() { return window.getcomputedstyle(this); } }); } specification not part of any specification. micros...
Element.getAttributeNode() - Web APIs
var attrnode = element.getattributenode(attrname); attrnode is an attr node for the attribute. attrname is a string containing the name of the attribute. example // html: <div id="top" /> let t = document.getelementbyid("top"); let idattr = t.getattributenode("id"); alert(idattr.value == "top") notes when called on an html element in a dom flagged as an html document, getattributenode lower-cases its argument before proceeding. the attr node inherits from node, but is not considered a part of the document tree. common node attributes like parentnode, previoussibling, and nextsibling are null for an attr node. you can, however, get the element to which the attribute belongs with the ownerelement property. getattribute is usually used instead of getattributenode to get the value o...
Element.getAttributeNodeNS() - Web APIs
espace of the attribute. nodename is a string specifying the name of the attribute. == example == tbd the example needs to be fixed pre> // html: <div id="top" /> t = document.getelementbyid("top"); specialnode = t.getattributenodens( "http://www.mozilla.org/ns/specialspace", "id"); // inode.value = "full-top" </pre notes getattributenodens is more specific than getattributenode in that it allows you to specify attributes that are part of a particular namespace. the corresponding setter method is setattributenodens. dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for dealing with attr nodes directly (seldom used) dom level 2 namespace-aware methods for dealing with attr nodes dir...
Element.getClientRects() - Web APIs
, mozilla will return only a single rectangle. firefox 3.5 note firefox 3.5 adds width and height properties to the textrectangle object. the amount of scrolling that has been done of the viewport area (or any other scrollable element) is taken into account when computing the rectangles. the returned rectangles do not include the bounds of any child elements that might happen to overflow. for html <area> elements, svg elements that do not render anything themselves, display:none elements, and generally any elements that are not directly rendered, an empty list is returned. rectangles are returned even for css boxes that have empty border-boxes. the left, top, right, and bottom coordinates can still be meaningful. fractional pixel offsets are possible. examples these examples...
Element.getElementsByClassName() - Web APIs
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 as: var matches = element.getelementsbyclassname('colorbo...
Element.insertAdjacentElement() - Web APIs
the insertadjacentelement() method of the element interface inserts a given element node at a given position relative to the element it is invoked upon. syntax targetelement.insertadjacentelement(position, element); parameters position a domstring representing the position relative to the targetelement; must match (case-insensitively) one of the following strings: 'beforebegin': before the targetelement itself. 'afterbegin': just inside the targetelement, before its first child. 'beforeend': just inside the targetelement, after its last child. 'afterend': after the targetelement itself. element the element to be inserted into the tree. return value the element that was inserted, or null, if the insertion failed. exceptions exception explanation ...
Element.insertAdjacentHTML() - Web APIs
osition. it does not reparse the element it is being used on, and thus it does not corrupt the existing elements inside that element. this avoids the extra step of serialization, making it much faster than direct innerhtml manipulation. syntax element.insertadjacenthtml(position, text); parameters position a domstring representing the position relative to the element; must be one of the following strings: 'beforebegin': before the element itself. 'afterbegin': just inside the element, before its first child. 'beforeend': just inside the element, after its last child. 'afterend': after the element itself. text the string to be parsed as html or xml and inserted into the tree. visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- b...
Element: keydown event - Web APIs
eypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. bubbles yes cancelable yes interface keyboardevent event handler property onkeydown the keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. for example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. an uppercase "a" is reported as 65 by all events. keyboard events are only generated by <inputs>, <textarea> and anything with the contenteditable attribute or with tabindex="-1". since firefox 65, the keydown and keyup events are now fired during ime composition, to improve cross-browser compatibility for cjkt users ...
Element: keyup event - Web APIs
the keyup event is fired when a key is released. bubbles yes cancelable yes interface keyboardevent event handler property onkeyup the keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. for example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. an uppercase "a" is reported as 65 by all events. since firefox 65, the keyup and keydown events are now fired during ime composition, to improve cross-browser compatibility for cjkt users (bug 354358, also see keydown and keyup events are now fired during ime composition for more useful details). to ignore all keyup events that are part of composition, do something like this (22...
Element.localName - Web APIs
Web › API › Element › localName
<ecomm:partner id="1001">tony's syrup warehouse </ecomm:partner> </ecomm:partner> </ecomm:business> note: in gecko 1.9.2 and earlier, the property returns the upper-cased version of the local name for html elements in html doms (as opposed to xhtml elements in xml doms). in later versions, in compliance with html5, the property returns in the case of the internal dom storage, which is lower case for both html elements in html doms and xhtml elements in xml doms. the tagname property continues to return in the upper case for html elements in html doms. specifications specification status comment domthe definition of 'element.localname' in that specification. living standard initial definition ...
Element.matches() - Web APIs
Web › API › Element › matches
ie9+ support). if (!element.prototype.matches) { element.prototype.matches = element.prototype.msmatchesselector || element.prototype.webkitmatchesselector; } specification specification status comment domthe definition of 'element.prototype.matches' in that specification.
Element: mousedown event - Web APIs
from the click event in that click is fired after a full click action occurs; that is, the mouse button is pressed and released while the pointer remains inside the same element. mousedown is fired the moment the button is initially pressed. bubbles yes cancelable yes interface mouseevent event handler property onmousedown examples the following example uses the mousedown, mousemove, and mouseup events to allow the user to draw on an html5 canvas. its functionality is simple: the thickness of the line is set to 1, and the color is always black. when the page loads, constants mypics and context are created to store a reference to the canvas and the 2d context we will use to draw. drawing begins when the mousedown event fires. first w...
Element: mouseenter event - Web APIs
roblems. in such cases, it is better to listen for mouseover events. combined with the corresponding mouseleave (which is fired at the element when the mouse exits its content area), the mouseenter event acts in a very similar way to the css :hover pseudo-class. examples the mouseover documentation has an example illustrating the difference between mouseover and mouseenter. mouseenter the following trivial example uses the mouseenter event to change the border on the div when the mouse enters the space alloted to it. it then adds an item to the list with the number of the mouseenter or mouseleave event. html <div id='mousetarget'> <ul id="unorderedlist"> <li>no events yet!</li> </ul> </div> css styling the div to make it more visible. #mousetarget { box-sizing: border-box; w...
Element: mouseleave event - Web APIs
chy when the pointer moves from the text to an area outside of the most outer div represented here. one single mouseout event is sent to the deepest element of the dom tree, then it bubbles up the hierarchy until it is canceled by a handler or reaches the root. examples the mouseout documentation has an example illustrating the difference between mouseout and mouseleave. mouseleave the following trivial example uses the mouseenter event to change the border on the <div> when the mouse enters the space alloted to it. it then adds an item to the list with the number of the mouseenter or mouseleave event. html <div id='mousetarget'> <ul id="unorderedlist"> <li>no events yet!</li> </ul> </div> css styling the <div> to make it more visible. #mousetarget { box-sizing: border-box;...
Element: mouseout event - Web APIs
d to move the cursor so that it is no longer contained within the element or one of its children. mouseout is also delivered to an element if the cursor enters a child element, because the child element obscures the visible area of the element. bubbles yes cancelable yes interface mouseevent event handler property onmouseout examples the following examples show the use of the mouseout event. mouseout and mouseleave the following example illustrates the difference between mouseout and mouseleave events. the mouseleave event is added to the <ul> to color the list purple whenever the mouse exits the <ul>. mouseout is added to the list to color the targeted element orange when the mouse exits it. when you try this out, you'll find that m...
Element: mouseover event - Web APIs
the mouseover event is fired at an element when a pointing device (such as a mouse or trackpad) is used to move the cursor onto the element or one of its child elements. bubbles yes cancelable yes interface mouseevent event handler property onmouseover examples the following example illustrates the difference between mouseover and mouseenter events. html <ul id="test"> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> javascript let test = document.getelementbyid("test"); // this handler will be executed only once when the cursor // moves over the unordered list test.addeventlistener("mouseenter", function( event ) { // highlight the mouseenter target event.target.style.color = "purple"; // reset the color after ...
Element: mouseup event - Web APIs
the mouseup event is fired at an element when a button on a pointing device (such as a mouse or trackpad) is released while the pointer is located inside it. mouseup events are the counterpoint to mousedown events. bubbles yes cancelable yes interface mouseevent event handler property onmouseup examples the following example uses the mousedown, mousemove, and mouseup events to allow the user to draw on an html5 canvas. its functionality is simple: the thickness of the line is set to 1, and the color is always black. when the page loads, constants mypics and context are created to store a reference to the canvas and the 2d context we will use to draw. drawing begins when the mousedown event fires. first we store the x and y coordinate...
Element: mousewheel event - Web APIs
nt. wheeldelta, wheeldeltax and wheeldeltay value the wheeldelta attribute value is an abstract value which indicates how far the wheel turned. if the wheel has rotated away from the user, it's positive, otherwise negative. this means that the delta value sign is different from dom level 3 event's wheel. however, the meaning of the amount of these values is not the same between browsers. see following explanation for the detail. ie and opera (presto) only support wheeldelta attribute and do not support horizontal scroll. the wheeldeltax attribute value indicates the wheeldelta attribute value along the horizontal axis. when a user operates the device for scrolling to right, the value is negative. otherwise, i.e., if it's to left, the value is positive. the wheeldeltay attribute value ind...
Element.name - Web APIs
Web › API › Element › name
note: the name property doesn't exist for other elements; unlike tagname and nodename, it is not a property of the node, element or htmlelement interfaces. name can be used in the document.getelementsbyname() method, a form and with the form elements collection. when used with a form or elements collection, it may return a single element or a collection. ...
Element.outerHTML - Web APIs
Web › API › Element › outerHTML
value reading the value of outerhtml returns a domstring containing an html serialization of the element and its descendants. setting the value of outerhtml replaces the element and all of its descendants with a new dom tree constructed by parsing the specified htmlstring. exceptions syntaxerror an attempt was made to set outerhtml using an html string which is not valid. nomodificationallowederror an attempt was made to set outerhtml on an element which is a direct child of a document, such as document.documentelement. examples getting the value of an element's outerhtml property: html <div id="d"> <p>content</p> <p>further elaborated</p> </div> javascript var d = document.getelementbyid("d"); console.log(d.outerhtml); // the string '<div id="d"><p>content</p><p>further...
Element.part - Web APIs
Web › API › Element › part
the part property of the element interface represents the part identifier(s) of the element (i.e. set using the part attribute), returned as a domtokenlist. these can be used to style parts of a shadow dom, via the ::part pseudo-element. syntax let elementpartlist = element.part examples the following excerpt is from our shadow-part example. here the part attribute is used to find the shadow parts, and the part property is then used to change the part identifiers of each tab so the correct styling is applied to the active tab when tabs are clicked. let tabs = []; let children = this.shadowroot.children; for(let elem of children) { if(elem.getattribute('part')) { tabs.push(elem); } } tabs.foreach((tab) => { tab.addeventlistener('click', (e) => { tabs.foreach((tab) => {...
Element.prefix - Web APIs
Web › API › Element › prefix
<x:div onclick="console.log(this.prefix)"/> notes this will only work when a namespace-aware parser is used, i.e. ...
Element.scrollIntoView() - Web APIs
the visible area of the scrollable ancestor. corresponds to scrollintoviewoptions: {block: "start", inline: "nearest"}. this is the default value. if false, the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor. corresponds to scrollintoviewoptions: {block: "end", inline: "nearest"}. scrollintoviewoptions optional is an object with the following properties: behavior optional defines the transition animation. one of auto or smooth. defaults to auto. block optional defines vertical alignment. one of start, center, end, or nearest. defaults to start. inline optional defines horizontal alignment. one of start, center, end, or nearest. defaults to nearest. example var element = document.getelementbyid("box"); ...
Element.scrollTop - Web APIs
Web › API › Element › scrollTop
scrolled. var intelemscrolltop = someelement.scrolltop; after running this code, intelemscrolltop is an integer corresponding to the number of pixels that the element's content has been scrolled upwards. // set the number of pixels scrolled. element.scrolltop = intvalue; scrolltop can be set to any integer value, with certain caveats: if the element can't be scrolled (e.g. it has no overflow or if the element has a property of "non-scrollable"), scrolltop is 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 ei...
Element: scroll event - Web APIs
ling has completed. see bootstrap issue #16202. safari and wkwebviews are not affected by this bug. examples scroll event throttling since scroll events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as dom modifications. instead, it is recommended to throttle the event using requestanimationframe(), settimeout(), or a customevent, as follows. note, however, that input events and animation frames are fired at about the same rate, and therefore the optimization below is often unnecessary. this example optimizes thescroll event for requestanimationframe. // reference: http://www.html5rocks.com/en/tutorials/speed/animations/ let last_known_scroll_position = 0; let ticking = false; function dosomething(scroll_pos) { // do something...
Element.setPointerCapture() - Web APIs
pointer will be targeted at the capture element until capture is released (via element.releasepointercapture()). note: when pointer capture is set, pointerover, pointerout, pointerenter, and pointerleave events are only generated when crossing the boundary of the capture target. this has the effect of suppressing these events on all other elements. overview of pointer capture pointer capture allows events for a particular pointer event (pointerevent) to be re-targeted to a particular element instead of the normal (or hit test) target at a pointer's location. this can be used to ensure that an element continues to receive pointer events even if the pointer device's contact moves off the element (such as by scrolling or panning). syntax targetelement.setpointercapture(pointerid); paramet...
Element.shadowRoot - Web APIs
the element.shadowroot read-only property represents the shadow root hosted by the element. use element.attachshadow() to add a shadow root to an existing element. syntax var shadowroot = element.shadowroot; value a shadowroot object instance, or null if the associated shadow root was attached with its mode set to closed. (see element.attachshadow() for further details). examples the following snippets are taken from our life-cycle-callbacks example (see it live also), which creates an element that displays a square of a size and color specified in the element's attributes. inside the <custom-square> element's class definition we include some life cycle callbacks that make a call to an external function, updatestyle(), which actually applies the size and color to the element. you'll ...
Element.tagName - Web APIs
Web › API › Element › tagName
s, the value of tagname is the same as the value of the nodename property the element object inherits from node. example html <span id="born">when i was born...</span> javascript var span = document.getelementbyid("born"); console.log(span.tagname); in xhtml (or any other xml format), the original case will be maintained, so "span" would be output in case the original tag name was created lowercase. in html, "span" would be output instead regardless of the case used while creating the original document. specifications specification status comment domthe definition of 'element: tagname' in that specification. living standard ...
ElementCSSInlineStyle.style - Web APIs
is not useful for completely learning about the styles applied on the element, since it represents only the css declarations set in the element's inline style attribute, not those that come from style rules elsewhere, such as style rules in the <head> section, or external style sheets. to get the values of all css properties for an element you should use window.getcomputedstyle() instead. ...
ElementCSSInlineStyle - Web APIs
note: elementcssinlinestyle is a mixin and not an interface; you can't actually create an object of type elementcssinlinestyle. propertiesstylethe style property is used to get as well as set the inline style of an element. ...
ElementTraversal - Web APIs
it proved useless, as very few types of node were able to implement all its methods and properties. it has been split into two interfaces, containing the useful methods and properties for each kind of nodes: childnode parentnode as it was a pure interface, with no object of this type, this change has no effect on the web. specifications specification status comment domthe definition of 'childnode' in that specification. ...
Encoding API - Web APIs
the encoding api provides a mechanism for handling text in various character encodings, including legacy non-utf-8 encodings. the api provides four interfaces: textdecoder, textencoder, textdecoderstream and textencoderstream. interfaces textdecoder textencoder textdecoderstream textencoderstream tutorials & tools a shim allowing to use this interface in browsers that don't support it. stringview – a c-like representation of strings based on typed arrays. specifications specification status comment encoding living standard initial definition. ...
ErrorEvent - Web APIs
the errorevent interface represents events providing information related to errors in scripts or in files. ...
Comparison of Event Targets - Web APIs
ted to their parent node when they happen over text nodes (bug 185889), and in that case .target will show the parent and .explicitoriginaltarget will show the text node. unlike .originaltarget, .explicitoriginaltarget will never contain anonymous content. event.originaltarget event.webidl the original target of the event, before any retargetings. see anonymous content#event_flow_and_targeting for details. event.composedtarget event.webidl the original non-native target of the event before composition from shadow dom. use of explicitoriginaltarget and originaltarget todo: only available in a mozilla-based browser? todo: only suitable for extension-developers? examples <!doctype html> <html> <head> <meta charset="utf-8"> <meta http-e...
Event() - Web APIs
Web › API › Event › Event
the default is false. cancelable optional a boolean indicating whether the event can be cancelled. the default is false. ...
Event.bubbles - Web APIs
Web › API › Event › bubbles
ue if the event bubbles up through the dom. example function handleinput(e) { // checks whether the event bubbles and ... if (!e.bubbles) { // ... passes the event along if does not passiton(e); } // already bubbling dooutput(e); } note: only certain events can bubble. events that do bubble have this property set to true. you can use this property to check if an event is allowed to bubble or not. specifications specification status comment domthe definition of 'event.bubbles' in that specification. living standard document object model (dom) level 2 events specificationthe definition of 'event.bubbles' in that specification. obsolete initial definition. ...
Event.composedPath() - Web APIs
event is always able to propagate across shadow boundaries. second, you'll notice a difference in the value of composedpath for the two elements. the <open-shadow> element's composed path is this: array [ p, shadowroot, open-shadow, body, html, htmldocument https://mdn.github.io/web-components-examples/composed-composed-path/, window ] whereas the <closed-shadow> element's composed path is a follows: array [ closed-shadow, body, html, htmldocument https://mdn.github.io/web-components-examples/composed-composed-path/, window ] in the second case, the event listeners only propagate as far as the <closed-shadow> element itself, but not to the nodes inside the shadow boundary. specifications specification status comment domthe definition of 'composedpath()' in that s...
Event.originalTarget - Web APIs
note: originaltarget may also be native anonymous content (see bug 208427), in which case it's useless for non-privileged code. ...
Event.returnValue - Web APIs
Web › API › Event › returnValue
setting this property to false prevents the default action. note: while returnvalue has been adopted into the dom standard, it is present primarily to support existing code. you should use preventdefault(), and defaultprevented instead of this historical property. ...
EventListener - Web APIs
properties this interface neither implements, nor inherits, any properties. methods this interface doesn't inherit any methods. ...
EventTarget - Web APIs
bjects can be event targets, too. for example xmlhttprequest, audionode, audiocontext, and others. many event targets (including elements, documents, and windows) also support setting event handlers via onevent properties and attributes. ...
ExtendableEvent - Web APIs
ack up, and the resulting promises will be added to the list of extend lifetime promises. note: the behaviour described in the above paragraph was fixed in firefox 43 (see bug 1180274.) this interface inherits from the event interface. ...
ExtendableMessageEvent() - Web APIs
the extendablemessageevent() constructor creates a new extendablemessageevent object instance. syntax var extendablemessageevent = new extendablemessageevent(type, init); parameters type a domstring that defines the type of the message event being created. init optional an initialisation object, which should contain the following parameters: data: the event's data — this can be any data type. origin: a domstring that defines the origin of the corresponding service worker's environment settings object. lasteventid: a domstring that defines the last event id of the event source. source: the client, serviceworker or messageport that sent the message. ports: an array containing the messageport objects connected to the channel sending the message. examples var init =...
ExtendableMessageEvent.data - Web APIs
the data read-only property of the extendablemessageevent interface returns the event's data. it can be any data type. syntax var mydata = extendablemessageevent.data; value any data type. examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent. var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = function(e) { console.log(e.data); port = e.ports[0]; } ...
ExtendableMessageEvent.lastEventId - Web APIs
the lasteventid read-only property of the extendablemessageevent interface represents, in server-sent events, the last event id of the event source. this is an empty string. syntax var mylasteventid = extendablemessageevent.lasteventid; value a domstring. examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent. var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmes...
ExtendableMessageEvent.origin - Web APIs
the origin read-only property of the extendablemessageevent interface returns the origin of the client that sent the message. syntax var myorigin = extendablemessageevent.origin; value a usvstring. examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent. var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = function(e) { console.log(e.origin); port = e.p...
ExtendableMessageEvent.ports - Web APIs
the ports read-only property of the extendablemessageevent interface returns the array containing the messageport objects representing the ports of the associated message channel (the channel the message is being sent through.) syntax var myports = extendablemessageevent.ports; value an array of messageport objects. examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent. var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action =...
ExtendableMessageEvent.source - Web APIs
the source read-only property of the extendablemessageevent interface returns a reference to the client object from which the message was sent. syntax var mysource = extendablemessageevent.source; value a client, serviceworker or messageport object. examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent. var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage =...
ExtendableMessageEvent - Web APIs
st event id of the event source. this is an empty string. extendablemessageevent.source read only returns a reference to the client object that sent the message. extendablemessageevent.ports read only returns the array containing the messageport objects representing the ports of the associated message channel. methods inherits methods from its parent, extendableevent. examples in the below example a page gets a handle to the serviceworker object via serviceworkerregistration.active, and then calls its postmessage() function. // in the page being controlled if (navigator.serviceworker) { navigator.serviceworker.register('service-worker.js'); navigator.serviceworker.addeventlistener('message', event => { // event is a messageevent object console.log(`the service worker...
FeaturePolicy.features() - Web APIs
the features() method of the featurepolicy interface returns a list of names of all features supported by the user agent. feature whose name appears on the list might not be allowed by the feature policy of the current execution context and/or might not be accessible because of user's permissions. syntax const supportedfeatures = featurepolicy.features() parameters none. return value a list of strings that represent names of all feature policy directives supported by the user agent. example the followin example logs all the supported directives in the console. // get the feature policy object const featurepolicy = document.featurepolicy // retreive the list of all supported feature policy directives const supporteddirectives = featurepolicy.features() // print out each ...
FetchEvent() - Web APIs
the fetchevent() constructor creates a new fetchevent object. syntax var fetchevent = new fetchevent(type, init); parameters type a domstring object specifying which event the object represents. this is always fetch for fetch events. init optional an object conforming to the fetcheventinit dictionary, containing options to apply to the event object. options are as follows: clientid read only the client that the current service worker is controlling. isreload read only a boolean that signifies whether the page was reloaded or not when the event was dispatched. true if yes, and false if not. typically, pressing the refresh button in a browser is a reload, while clicking a link and pressing the back button is not. if not present, it defaults to false. preloadresponse...
FetchEvent.navigationPreload - Web APIs
the navigationpreload read-only property of the fetchevent interface returns a promise that resolves to the instance of navigationpreloadmanager associated with the current service worker registration. syntax var promise = fetchevent.navigationpreload value a promise that resolves to the instance of navigationpreloadmanager. example the following example shows the implementation of a fetch event that uses a preloaded response. addeventlistener('fetch', event => { event.respondwith(async function() { // respond from the cache if we can const cachedresponse = await caches.match(event.request); if (cachedresponse) return cachedresponse; // else, use the preloaded response, if it's there const response = await event.preloadresponse; if (response) return respo...
FetchEvent.respondWith() - Web APIs
in most cases you can provide any response that the receiver understands. for example, if an <img> initiates the request, the response body needs to be image data. for security reasons, there are a few global rules: you can only return response objects of type "opaque" if the fetchevent.request object's mode is "no-cors". this prevents the leaking of private data. you can only return response objects of type "opaqueredirect" if the fetchevent.request object's mode is "manual". ...
FetchEvent - Web APIs
constructor fetchevent() creates a new fetchevent object. this constructor is not typically used. the browser creates these objects itself and provides them to fetch event callbacks. properties inherits properties from its ancestor, event. ...
Fetch basic concepts - Web APIs
ased. guard guard is a feature of headers objects, with possible values of immutable, request, request-no-cors, response, or none, depending on where the header is used. when a new headers object is created using the headers() constructor, its guard is set to none (the default). ...
File.File() - Web APIs
Web › API › File › File
bits, name[, options]); parameters bits an array of arraybuffer, arraybufferview, blob, usvstring objects, or a mix of any of such objects, that will be put inside the file. usvstring objects are encoded as utf-8. name a usvstring representing the file name or the path to the file. options optional an options object containing optional attributes for the file. available options are as follows: type: a domstring representing the mime type of the content that will be put into the file. defaults to a value of "". lastmodified: a number representing the number of milliseconds between the unix time epoch and when the file was last modified. defaults to a value of date.now(). example var file = new file(["foo"], "foo.txt", { type: "text/plain", }); specifications ...
File.getAsText() - Web APIs
Web › API › File › getAsText
returned data. if this string is empty, utf-8 is assumed. returns a string containing the file's data interpreted as text in the specified encoding. ...
File.lastModified - Web APIs
Web › API › File › lastModified
if it is missing, lastmodified inherits the current 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); //retur...
File.name - Web APIs
Web › API › File › name
his property. syntax var name = file.name; value a string, containing the name of the file without path, such as "my resume.rtf". example <input type="file" multiple onchange="processselectedfiles(this)"> function processselectedfiles(fileinput) { var files = fileinput.files; for (var i = 0; i < files.length; i++) { alert("filename " + files[i].name); } } try the results out below: specifications specification status comment file apithe definition of 'name' in that specification. working draft initial definition. ...
FileReader() - Web APIs
the filereader() constructor creates a new filereader. for details about how to use filereader, see using files from web applications. syntax var reader = new filereader(); parameters none. ...
FileReader.readyState - Web APIs
none of the read methods called yet. 1 loading a read method has been called. 2 done the operation is complete. empty the filereader has been created, but no readas method was called yet. loading a readas method was invoked. a file or blob is being read, and no error has occurred yet. done the read operation is complete. ...
FileReader.result - Web APIs
Web › API › FileReader › result
ration is complete, and the format of the data depends on which of the methods was used to initiate the read operation. syntax var file = instanceoffilereader.result value an appropiate string or arraybuffer based on which of the reading methods was used to initiate the read operation. the value is null if the reading is not yet complete or was unsuccessful. the result types are described below. method description readasarraybuffer() the result is a javascript arraybuffer containing binary data. readasbinarystring() the result contains the raw binary data from the file in a string. readasdataurl() the result is a string with a data: url representing the file's data. readastext() the result is text in a string. examp...
FileReader - Web APIs
feature is available in web workers. constructor filereader() returns a newly constructed filereader. see using files from web applications for details and examples. properties filereader.error read only a domexception representing the error that occurred while reading the file. filereader.readystate read only a number indicating the state of the filereader. this is one of the following: empty 0 no data has been loaded yet. loading 1 data is currently being loaded. done 2 the entire read request has been completed. filereader.result read only the file's contents. this property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to init...
FileReaderSync - Web APIs
this interface is only available in workers as it enables synchronous i/o that could potentially block. properties this interface does not have any properties. methods filereadersync.readasarraybuffer() this method converts a specified blob or a file into an arraybuffer representing the input data as a binary string. filereadersync.readasbinarystring() this method converts a specified blob or a file into a domstring representing the input data as a binary string. this method is deprecated, consider using readasarraybuffer() instead. filereadersync.readastext() this method converts a specified blob or a file into a domstring representing the input data as a text string. ...
FileSystemDirectoryEntry.removeRecursively() - Web APIs
al a function to be called if an error occurs while attempting to remove the directory subtree. receives a fileerror describing the error which occurred as input. return value undefined. errors if an error occurs and an errorcallback was specified, it gets called with a single parameter: a fileerror object describing the error. the fileerror.code specifies what type of error occurred, as follows: fileerror.invalid_modification_err an attempt was made to remove the root directory; this is not permitted. fileerror.no_modification_allowed_err the file system's state doesn't permit modification. fileerror.not_found_err the directory represented by the filesystemdirectoryentry no longer exists. fileerror.not_readable_err the directory is not accessible; perhaps it's in use by anoth...
FileSystemDirectoryEntry - Web APIs
ry. basic concepts you can create a new directory by calling getdirectory(). if you want to create subdirectories, create each child directory in sequence. if you try creating a directory using a full path that includes parent directories that do not exist yet, an error is returned. so create the hierarchy by recursively adding a new path after creating the parent directory. example in the following code snippet, we create a directory called "documents." // taking care of the browser-specific prefixes. window.requestfilesystem = window.requestfilesystem || window.webkitrequestfilesystem; window.directoryentry = window.directoryentry || window.webkitdirectoryentry; ... function onfs(fs){ fs.root.getdirectory('documents', {create:true}, function(directoryentry){ //directoryentry.is...
FileSystemEntry.remove() - Web APIs
t to remove the file fails. return value undefined. errors fileerror.invalid_modification_err the specified entry was the file system's root directory, or the specified entry is a directory which isn't empty. fileerror.invalid_state_err the file system's cached state is inconsistent with its state on disk, so the file could not be deleted for safety reasons. fileerror.no_modification_allowed_err the file system's state doesn't permit removing the file or directory. fileerror.not_found_err the file or directory doesn't exist. fileerror.security_err the entry couldn't be removed due to permissions or other access constraints, or because there are too many calls being made on file resources. example this example deletes a temporary work file. workingdirectory.getfile("tmp/wor...
FileSystemFileEntry - Web APIs
ile's attributes, as well as the file() method, which creates a file object that can be used to read the file. properties inherits the properties of its parent interface, filesystementry, but has no properties unique to this interface. methods file() creates a new file object which can be used to read the file. obsolete methods createwriter() creates a new filewriter object which allows writing to the file represented by the file system entry. basic concepts to write content to file, create a filewriter object by calling createwriter(). to read a file, obtain a file object representing its contents by calling file(). example the following code creates an empty file called "log.txt" (if it doesn't exist) and fills it with the text "meow". inside the success callback, event ...
FileSystemFlags.create - Web APIs
the create property on the filesystemflags dictionary is used to indicate whether or not the file should be created if it's missing. filesystemflags is only used when calling filesystemdirectoryentry.getfile() or filesystemdirectoryentry.getdirectory(). syntax filesystemflags.create = booleanvalue values the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback is called with a filesystemfileentry if getfile() was called o...
FileSystemFlags.exclusive - Web APIs
the exclusive property on the filesystemflags dictionary is used in tandem with the create property to determine whether or not it's acceptable to require that the file not already exist when the reference to it is created by calling filesystemdirectoryentry.getfile() or filesystemdirectoryentry.getdirectory(). syntax filesystemflags.exclusive = booleanvalue values the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback ...
FileSystemFlags - Web APIs
is true, and the requested file or directory doesn't exist, the user agent should create it. the default is false. the parent directory must already exist. exclusive optional if true, and the create option is also true, the file must not exist prior to issuing the call. instead, it must be possible for it to be created newly at call time. the default is false. values and results the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallb...
FileSystemSync - Web APIs
the specification is abandonned for the moment, failing to get significant traction. basic concepts the filesystemsync object is your gateway to the entire api and you will use it a lot. so once you have a reference, cache the object in a global variable or class property. ...
FocusEvent() - Web APIs
t has both a source and a destination, the relatedtarget value must be set to the other target. syntax var focusevent = new focusevent(typearg[, focuseventinit]); properties the focusevent() constructor also inherits arguments from uievent() and from event(). typearg is a domstring representing the name of the event. focuseventinit optional is a focuseventinit dictionary, having the following fields: "relatedtarget", optional and defaulting to null, is an eventtarget representing the secondary target of a focusevent. the focuseventinit dictionary also accepts fields from the uieventinit and eventinit dictionaries. specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'focusevent...
FocusEvent - Web APIs
the focusevent interface represents focus-related events, including focus, blur, focusin, and focusout. ...
FontFace.FontFace() - Web APIs
Web › API › FontFace › FontFace
face = new fontface(family, source, descriptors); parameters family specifies a name that will be used as the font face value for font properties. takes the same type of values as the font-family descriptor of @font-face . source the font source. this can be either: a url binary font data descriptors optional a set of optional descriptors passed as an object. ...
FontFace.family - Web APIs
Web › API › FontFace › family
this is equivalent to the font-family descriptor of @font-face. syntax instanceoffontface.family = 'font family name'; var fontface = instanceoffontface.family; // "font family name" value a domstring. example var fontface = new fontface('roboto', 'url(https://fonts.example.com/roboto.woff2)'); console.log(fontface.family); // 'roboto' fontface.family = 'newroboto'; console.log(fontface.family); // 'newroboto' specifications specification status comment css font loading module level 3the definition of 'family' in that specification. ...
FontFace - Web APIs
Web › API › FontFace
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. ...
FontFaceSetLoadEvent.FontFaceSetLoadEvent() - Web APIs
the fontfacesetloadevent constructor creates a new fontfaceloadevent object which is fired whenever a fontfaceset loads. syntax var fontfacesetloadevent = new fontfacesetloadevent(type[, options]) parameters type the literal value 'type' (quotation marks included). options optional options are as follows: fontfaces: an array of fontface instances. specifications specification status comment css font loading module level 3the definition of 'fontfacesetloadevent()' 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 re...
Force Touch events - Web APIs
to qualify as a "force click". webkitmouseforceup this event is fired after the webkitmouseforcedown event as soon as the pressure has been reduced sufficiently to end the "force click". webkitmouseforcechanged this event is fired each time the amount of pressure changes. this event first fires after the mousedown event and stops firing before the mouseup event. ...
FormData() - Web APIs
Web › API › FormData › FormData
ject. note: this feature is available in web workers. syntax var formdata = new formdata(form) parameters form optional an html <form> element — when specified, the formdata object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. it will also encode file input content. ...
FormData.append() - Web APIs
Web › API › FormData › append
when a blob or file is passed as the second parameter. the default filename for blob objects is "blob". the default filename for file objects is the file's filename. note: if you specify a blob as the data to append to the formdata object, the filename that will be reported to the server in the "content-disposition" header used to vary from browser to browser. returns void. example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you can add key/value pairs to this using formdata.append: formdata.append('username', 'chris'); formdata.append('userpic', myfileinput.files[0], 'chris.jpg'); as with regular form data, you can append multiple values with the same name. for example (and being compatible with php's naming conventions b...
FormData.delete() - Web APIs
Web › API › FormData › delete
the delete() method of the formdata interface deletes a key and its value(s) from a formdata object. note: this method is available in web workers. syntax formdata.delete(name); parameters name the name of the key you want to delete. returns void. example the following line creates an empty formdata object and prepopulates it with key/value pairs from a form: var formdata = new formdata(myform); you can delete keys and their values using delete(): formdata.delete('username'); specifications specification status comment xmlhttprequestthe definition of 'delete()' in that specification. living standard ...
FormData.entries() - Web APIs
Web › API › FormData › entries
the key of each pair is a usvstring object; the value either a usvstring, or a blob. note: this method is available in web workers. syntax formdata.entries(); return value returns an iterator. ...
FormData.keys() - Web APIs
Web › API › FormData › keys
the keys are usvstring objects. note: this method is available in web workers. syntax formdata.keys(); return value returns an iterator. example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the keys for (var key of formdata.keys()) { console.log(key); } the result is: key1 key2 specifications specification status comment xmlhttprequestthe definition of 'keys() (as iterator<>)' in that specification. ...
FormData.set() - Web APIs
Web › API › FormData › set
(a usvstring), when a blob or file is passed as the second parameter. the default filename for blob objects is "blob". the default filename for file objects is the file's filename. note: if you specify a blob as the data to append to the formdata object, the filename that will be reported to the server in the "content-disposition" header used to vary from browser to browser. ...
FormData.values() - Web APIs
Web › API › FormData › values
the values are usvstring or blob objects. note: this method is available in web workers. syntax formdata.values(); return value returns an iterator. ...
FormDataEntryValue - Web APIs
a string or file that represents a single value from a set of formdata key-value pairs. this type is returned by the formdata.get() and formdata.getall() methods. the formdata.get() method returns a single value while formdata.getall() returns an array of formdataentryvalues. note that the formdata.append() and formdata.set() methods allow passing a blob value, which is converted to a file in the process. ...
FormDataEvent() - Web APIs
the default is false. cancelable: a boolean indicating whether the event can be cancelled. the default is false. ...
FormDataEvent - Web APIs
the formdataevent interface represents a formdata event — such an event is fired on an htmlformelement object after the entry list representing the form's data is constructed. this happens when the form is submitted, but can also be triggered by the invocation of a formdata() constructor. this allows a formdata object to be quickly obtained in response to a formdata event firing, rather than needing to put it together yourself when you wish to submit form data via a method like xmlhttprequest (see using formdata objects). constructor formdataevent() creates a new formdataevent object instance. properties inherits properties from its parent interface, event. formdataevent.formdata contains the formdata object representing the data contained in the form when the event was fired.
FullscreenOptions.navigationUI - Web APIs
the default is "auto". ...
GainNode() - Web APIs
Web › API › GainNode › GainNode
or of the web audio api creates a new gainnode object which an audionode that represents 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 compatibilit...
Gamepad.axes - Web APIs
Web › API › Gamepad › axes
the gamepad.axes property of the gamepad interface returns 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). syntax readonly attribute double[] axes; example function gameloop() { if(navigator.webkitgetgamepads) { var gp = navigator.webkitgetgamepads()[0]; } else { var gp = navigator.getgamepads()[0]; } if(gp.axes[0] != 0) { b -= gp.axes[0]; } else if(gp.axes[1] != 0) { a += gp.axes[1]; } else if(gp.axes[2] != 0) { b += gp.axes[2]; } else if(gp.axes[3] != 0) { a -= gp.axes[3]; } ball.style.left = a*2 + "px"; ball.style.t...
Gamepad.id - Web APIs
Web › API › Gamepad › id
tion about the controller. the exact syntax is not strictly specified, but in firefox it will contain three pieces of information separated by dashes (-): two 4-digit hexadecimal strings containing the usb vendor and product id of the controller the name of the controller as provided by the driver. for example, a ps2 controller returned 810-3-usb gamepad. this information is intended to allow you to find a mapping for the controls on the device as well as display useful feedback to the user. syntax readonly attribute domstring id; example window.addeventlistener("gamepadconnected", function() { var gp = navigator.getgamepads()[0]; gamepadinfo.innerhtml = "gamepad connected at index " + gp.index + ": " + gp.id + "."; }); value a string. specifications ...
Gamepad.timestamp - Web APIs
Web › API › Gamepad › timestamp
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. ...
GamepadEvent() - Web APIs
the gamepadevent() constructor creates a new gamepadevent object. syntax var gamepadevent = new gamepadevent(typearg, options) parameters typearg a domstring that must be one of gamepadconnected or gamepaddisconnected. options optional options are as follows: gamepad: an instance of gamepad describing the gamepad associated with the event. specifications specification status comment gamepadthe definition of 'gamepadevent_' in that specification. working draft initial definition. ...
Gamepad API - Web APIs
button on one of the connected controllers. gamepadevent the event object representing events fired that are related to gamepads. experimental gamepad extensions gamepadhapticactuator represents hardware in the controller designed to provide haptic feedback to the user (if available), most commonly vibration hardware. see also the extensions to the gamepad interface, for features that allow you to access the above information. extensions to other interfaces navigator navigator.getgamepads() an extension to the navigator object that returns an array of gamepad objects, one for each connected gamepad. window events window.ongamepadconnected represents an event handler that will run when a gamepad is connected (when the gamepadconnected event fires). window.ongamepaddiscon...
Geolocation - Web APIs
an object with this interface is obtained using the navigator.geolocation property implemented by the navigator object. note: for security reasons, when a 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. ...
GeolocationCoordinates.longitude - Web APIs
eridian that most people think of. it is, instead, the iers reference meridian, which is located 5.3 arcseconds (102 meters / 335 feet) east of the greenwich meridian. this is the same standard used by the global positioning system (gps). examples in this simple example, we fetch the user's location and display the resulting coordinates once they're returned. javascript the javascript code below creates an event listener so that when the user clicks on a button, the location information is retrieved and displayed. let button = document.getelementbyid("get-location"); let lattext = document.getelementbyid("latitude"); let longtext = document.getelementbyid("longitude"); button.addeventlistener("click", function() { navigator.geolocation.getcurrentposition(function(position) { let ...
GeolocationPositionError.code - Web APIs
the geolocationpositionerror.code read-only property is an unsigned short representing the error code. syntax let typeerr = geolocationpositionerrorinstance.code value an unsigned short representing the error code. the following values are possible: value associated constant description 1 permission_denied the acquisition of the geolocation information failed because the page didn't have the permission to do it. 2 position_unavailable the acquisition of the geolocation failed because one or several internal sources of position returned an internal error. 3 timeout the time allowed to acquire the geolocation, defined by positionoptions.timeout information that was reached before the information was obtained. ...
GestureEvent - Web APIs
read only change in rotation (in degrees) since the event's beginning. positive values indicate clockwise rotation; negative values indicate anticlockwise rotation. initial value: 0.0 gestureevent.scale read only distance between two digits since the event's beginning. expressed as a floating-point multiple of the initial distance between the digits at the beginning of the gesture. values below 1.0 indicate an inward pinch (zoom out). values above 1.0 indicate an outward unpinch (zoom in). initial value: 1.0 methods this interface also inherits methods of its parents, uievent and event. gestureevent.initgestureevent() initializes the value of an gestureevent. if the event has already being dispatched, this method does nothing. gesture event types gesturestart gesturechange ...
GlobalEventHandlers.onanimationiteration - Web APIs
cating that a css animation has reached the end of an iteration while running on the target, where the target object is an html element (htmlelement), document (document), or window (window). the function receives as input a single parameter: an animationevent object describing the event which occurred. example let's create an animation which automatically pauses at the end of each iteration, allowing the user to choose whether or not to start the next iteration. much of this code is the same as in other examples of animation events, so it may look familiar. html <div class="main"> <div id="box"> <div id="text">box</div> </div> </div> <div class="button" id="play"> begin demonstration </div> css :root { --boxwidth:50px; } .main { width: 300px; height:300px; border...
GlobalEventHandlers.onclick - Web APIs
the onclick property of the globaleventhandlers mixin is the eventhandler for processing click events on a given element. the click event is raised when the user clicks on an element. it fires after the mousedown and mouseup events, in that order. note: when using the click event to trigger an action, also consider adding this same action to the keydown event, to allow the use of that same action by people who don't use a mouse or a touch screen. syntax target.onclick = functionref; value functionref is a function name or a function expression. the function receives a mouseevent object as its sole argument. within the function, this will be the element upon which the event was triggered. only one onclick handler can be assigned to an object at a time. you may prefer to use the eventt...
GlobalEventHandlers.ondrag - Web APIs
m; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function drag_handler(ev) { console.log("drag"); } function dragstart_handler(ev) { console.log("dragstart"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { console.log("drop"); ev.currenttarget.style.background = "lightyellow"; ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <!-- <div class="source"> --> <p id="source" ondr...
GlobalEventHandlers.ondragend - Web APIs
var el=document.getelementbyid("target"); el.style.background = "pink"; } function ...
GlobalEventHandlers.ondragenter - Web APIs
var el=document.getelementbyid("target"); el.style.background = "pink"; } function ...
GlobalEventHandlers.ondragexit - Web APIs
var el=document.getelementbyid("target"); el.style.background = "pink"; } function ...
GlobalEventHandlers.ondragleave - Web APIs
var el=document.getelementbyid("target"); el.style.background = "pink"; } ...
GlobalEventHandlers.ondragover - Web APIs
m; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function drag_handler(ev) { console.log("drag"); } function dragstart_handler(ev) { console.log("dragstart"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { console.log("drop"); ev.currenttarget.style.background = "lightyellow"; ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <p id="source" ondrag="drag_handler(event);" ondr...
GlobalEventHandlers.ondragstart - Web APIs
m; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function drag_handler(ev) { console.log("drag"); } function dragstart_handler(ev) { console.log("dragstart"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { console.log("drop"); ev.currenttarget.style.background = "lightyellow"; ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <p id="source" ondrag="drag_handler(event);" ondr...
GlobalEventHandlers.ondrop - Web APIs
m; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function drag_handler(ev) { console.log("drag"); } function dragstart_handler(ev) { console.log("dragstart"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { console.log("drop"); ev.currenttarget.style.background = "lightyellow"; ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div class="source"> <p id="source" ondrag="drag_handle...
GlobalEventHandlers.onerror - Web APIs
r can be overriden in some browsers using the crossorigin attribute on <script> and having the server send the appropriate cors http response headers. a workaround is to isolate "script error." and handle it knowing that the error detail is only viewable in the browser console and not accessible via javascript. ...
GlobalEventHandlers.onkeypress - Web APIs
/* type the word "exit" in any point of your page... */ (function () { const ssecret = /* choose your hidden word...: */ "exit"; let noffset = 0; document.onkeypress = function(opevt) { let oevent = opevt || window.event, nchr = oevent.charcode, snodetype = oevent.tar...
GlobalEventHandlers.onpointerdown - Web APIs
t, and doesn't affect its functionality at all. #target { width: 400px; height: 30px; text-align: center; font: 16px "open sans", "helvetica", sans-serif; color: white; background-color: blue; border: 2px solid darkblue; cursor: pointer; user-select: none; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; } result the resulting output is shown below. try tapping, clicking, or touching the box and see what happens. for full effect, try it with a variety of pointer types. specifications specification status comment pointer events – level 2the definition of 'onpointerdown' in that specification. recommendation non-stable version pointer eventsthe definition of 'onpointerdown' in that specificatio...
GlobalEventHandlers.ontransitionend - Web APIs
means that the value of transition-delay doesn't affect the value of elapsedtime, which is zero until the delay period ends and the animation begins. example in this example, we use the transitionrun and transitionend events to detect when the transition begins and ends, to cause a text update to occur during the transition. this could also be used to trigger animations or other effects, to allow chaining of reactions. html this simply creates a <div> which we'll style with css below to make into a box that resizes and changes color and such. <div class="box"></div> css the css below styles the box and applies a transition effect which makes the box's color and size change, and causes the box to rotate, while the mouse cursor hovers over it. .box { margin-left: 70px; margin-top...
GlobalEventHandlers - Web APIs
the globaleventhandlers mixin describes the event handlers common to several interfaces like htmlelement, document, or window. each of these interfaces can, of course, add more event handlers in addition to the ones listed below. note: globaleventhandlers is a mixin and not an interface; you can't actually create an object of type globaleventhandlers. properties this interface doesn't include any properties except for the event handlers listed below. event handlers these event handlers are defined on the globaleventhandlers mixin, and implemented by htmlelement, document, window, as well as by workerglobalscope for web workers. globaleventhandlers.onabort is an eventhandler representing the code to be called when the abort event is raised. globaleventhandlers.onanimationcancel ...
Gyroscope.Gyroscope() - Web APIs
reading the angular velocity of the device along all three axes. 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. syntax var gyroscope = new gyroscope([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called. a whole number or decimal may be used, the latter for frequencies less than a second. the actual reading frequency depends device hardware and consequently may be less than requested. referenceframe: either 'device' or 'screen'. the defau...
Gyroscope.x - Web APIs
Web › API › Gyroscope › x
ong the its x axis. 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. syntax var x = gyroscope.x value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let gyroscope = new gyroscope({frequency: 60}); gyroscope.addeventlistener('reading', e => { console.log("angular velocity along the x-axis " + gyroscope.x); console.log("angular velocity along the y-axis " + gyroscope.y); console.log("angular velocity along the z-axis " + gyroscope.z); }); gyroscope.start(); specifications specification sta...
Gyroscope.y - Web APIs
Web › API › Gyroscope › y
ong the its y axis. 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. syntax var y = gyroscope.y value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let gyroscope = new gyroscope({frequency: 60}); gyroscope.addeventlistener('reading', e => { console.log("angular velocety along the x-axis " + gyroscope.x); console.log("angular velocety along the y-axis " + gyroscope.y); console.log("angular velocety along the z-axis " + gyroscope.z); }); gyroscope.start(); specifications specification sta...
Gyroscope.z - Web APIs
Web › API › Gyroscope › z
ong the its z axis. 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. syntax var z = gyroscope.z value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let gyroscope = new gyroscope({frequency: 60}); gyroscope.addeventlistener('reading', e => { console.log("angular velocety along the x-axis " + gyroscope.x); console.log("angular velocety along the y-axis " + gyroscope.y); console.log("angular velocety along the z-axis " + gyroscope.z); }); gyroscope.start(); specifications specification sta...
Gyroscope - Web APIs
Web › API › Gyroscope
ining the angular velocity of the device along the device's x axis. gyroscope.y read only returns a double, containing the angular velocity of the device along the device's y axis. gyroscope.z read only returns a double, containing the angular velocity of the device along the device's z axis. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let gyroscope = new gyroscope({frequency: 60}); gyroscope.addeventlistener('reading', e => { console.log("angular velocity along the x-axis " + gyroscope.x); console.log("angular velocity along the y-axis " + gyroscope.y); console.log("angular velocity along the z-axis " + gyroscope.z); }); gyroscope.start(); specifications specification sta...
HTMLBaseElement - Web APIs
the htmlbaseelement interface contains the base uri for a document. this object inherits all of the properties and methods as described in the htmlelement interface. ...
HTMLCanvasElement.height - Web APIs
it is set to an invalid value, like a negative, the default value of 150 is used. this is one of the two properties, the other being htmlcanvaselement.width, that controls the size of the canvas. syntax var pxl = canvas.height; canvas.height = pxl; examples given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> you can get the height of the canvas with the following code: var canvas = document.getelementbyid('canvas'); console.log(canvas.height); // 300 specifications specification status comment html living standardthe definition of 'htmlcanvaselement.height' in that specification. living standard no change since the latest snapshot, html5 html 5.1the definition of 'htmlcanvaselement.height' in that specificatio...
HTMLCanvasElement.mozFetchAsStream() - Web APIs
s technique also converts it to ico, however it will not work in windows xp as winxp cannot convert from png to ico. it saves to the desktop it uses fileutils.jsm. ...
HTMLCanvasElement.mozGetAsFile() - Web APIs
the file's data is entirely located in memory until such time as it is explicitly written to disk. examples this example creates an image file from the <canvas> element on the page, then uses a filereader to read the image data from the file. html <canvas id="canvas" width="100" height="100"></canvas> <p><a href="#" id="link">click here to try out mozgetasfile()</a>.</p> javascript the following code uses mozgetasfile() to create a file object from the canvas and appends it as an image to the page by loading it as a data url using the readasdataurl() method. then a new <img> element is created using the new data url. function draw() { var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.fillstyle = 'rgb(200, 0, 0)'; ctx.fillrect(10, 10, 55, ...
HTMLCanvasElement.width - Web APIs
f it is set to an invalid value, like a negative, the default value of 300 is used. this is one of the two properties, the other being htmlcanvaselement.height, that controls the size of the canvas. syntax var pxl = canvas.width; canvas.width = pxl; examples given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> you can get the width of the canvas with the following code: var canvas = document.getelementbyid('canvas'); console.log(canvas.width); // 300 specifications specification status comment html living standardthe definition of 'htmlcanvaselement.width' in that specification. living standard no change since the latest snapshot, html5 html 5.1the definition of 'htmlcanvaselement.width' in that specification. ...
HTMLCanvasElement - Web APIs
the htmlcanvaselement interface provides properties and methods for manipulating the layout and presentation of <canvas> elements. the htmlcanvaselement interface also inherits the properties and methods of the htmlelement interface. ...
HTMLCollection.item - Web APIs
e same order in which they appear in the document's source. return value the node at the specified index, or null if index is less than zero or greater than or equal to the length property. usage notes the item() method returns a numbered element from an htmlcollection. in javascript, it is easier to treat the htmlcollection as an array and to index it using array notation. see the example below. example var c = document.images; // this is an htmlcollection var img0 = c.item(0); // you can use the item() method this way var img1 = c[1]; // but this notation is easier and more common ...
HTMLDListElement - Web APIs
the htmldlistelement interface provides special properties (beyond those of the regular htmlelement interface it also has available to it by inheritance) for manipulating definition list (<dl>) elements. ...
HTMLDataElement - Web APIs
the htmldataelement interface provides special properties (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <data> elements. ...
HTMLDataListElement - Web APIs
the htmldatalistelement interface provides special properties (beyond the htmlelement object interface it also has available to it by inheritance) to manipulate <datalist> elements and their content. ...
HTMLDetailsElement - Web APIs
the htmldetailselement interface provides special properties (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <details> elements. ...
HTMLDialogElement.close() - Web APIs
the close() method of the htmldialogelement interface closes the dialog. an optional domstring may be passed as an argument, updating the returnvalue of the the dialog. syntax dialoginstance.close(returnvalue); parameters returnvalue optional a domstring representing an updated value for the htmldialogelement.returnvalue of the dialog. return value void. examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal() method. from there you can click the cancel button to close the dialog (via the htmldialogelement.close() method), or submit the form via the submit button. <!-- simple pop-up dialog box, containing a form --> <dialog id="favdialog"> <form method="dialog"> <section> <p>...
HTMLDialogElement.open - Web APIs
on. syntax dialoginstance.open = true; var myopenvalue = dialoginstance.open; value a boolean representing the state of the open html attribute. true means it is set, and therefore the dialog is shown. false means it not set, and therefore the dialog is not shown. the property is now read only — it is possible to set the value to programmatically show or hide the dialog. examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal() method. from there you can click the cancel button to close the dialog (via the htmldialogelement.close() method), or submit the form via the submit button. <!-- simple pop-up dialog box, containing a form --> <dialog id="favdialog"> <form method="dialog"> <section> <...
HTMLDialogElement.returnValue - Web APIs
the returnvalue property of the htmldialogelement interface gets or sets the return value for the <dialog>, usually to indicate which button the user pressed to close it. syntax dialoginstance.returnvalue = 'myreturnvalue'; var myreturnvalue = dialoginstance.returnvalue; value a domstring representing the returnvalue of the dialog. examples the following example displays a button to open a <dialog> containing a form via the showmodal() method. from there, either button will close the dialog. <!-- simple pop-up dialog box containing a form --> <dialog id="favdialog"> <form method="dialog"> <p><label>favorite animal: <select name="favanimal" required> <option></option> <option>brine shrimp</option> <option>red panda</option> ...
HTMLDialogElement.showModal() - Web APIs
it displays into the top layer, along with a ::backdrop pseudo-element. interaction outside the dialog is blocked and the content outside it is rendered inert. syntax dialoginstance.showmodal(); parameters none. return value void. exceptions if the dialog is already open (i.e. if the open attribute is already set on the <dialog> element), an invalidstateerror is thrown. examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal() method. from there you can click the cancel button to close the dialog (via the htmldialogelement.close() method), or submit the form via the submit button. <!-- simple pop-up dialog box, containing a form --> <dialog id="favdialog"> <form method="dialog"> <section> <...
HTMLDivElement - Web APIs
the htmldivelement interface provides special properties (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <div> elements. ...
HTMLDocument - Web APIs
the htmldocument interface, which may be accessed through the window.htmldocument property, extends the window.htmldocument property to include methods and properties that are specific to html documents. ...
HTMLElement: change event - Web APIs
element = document.queryselector('.ice-cream'); selectelement.addeventlistener('change', (event) => { const result = document.queryselector('.result'); result.textcontent = `you like ${event.target.value}`; }); result text input element for some elements, including <input type="text">, the change event doesn't fire until the control loses focus. try entering something into the field below, and then click somewhere else to trigger the event. html <input placeholder="enter some text" name="name"/> <p id="log"></p> javascript const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.addeventlistener('change', updatevalue); function updatevalue(e) { log.textcontent = e.target.value; } result specifications specification s...
HTMLElement.contentEditable - Web APIs
'false' indicates that the element cannot be edited. 'inherit' indicates that the element inherits its parent's editable status. you can use the htmlelement.iscontenteditable property to test the computed boolean value of this property. ...
HTMLElement.dir - Web APIs
Web › API › HTMLElement › dir
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 shift and ctrl + right shift. firefox uses ctrl/cmd + shift + x but does not update the dir attribute value. syntax var currentwriti...
inert - Web APIs
Web › API › HTMLElement › inert
visible. ...
HTMLElement.innerText - Web APIs
e is the same as the node.textcontent property. example this example compares innertext with node.textcontent. note how innertext is aware of things like <br> elements, and ignores hidden elements. ...
HTMLElement.offsetHeight - Web APIs
s, as an integer. typically, offsetheight is a measurement in pixels of the element's css height, including any borders, padding, and horizontal scrollbars (if rendered). it does not include the height of pseudo-elements such as ::before or ::after. for the document body object, the measurement includes total linear content height instead of the element's css height. floated elements extending below other linear content are ignored. if the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is returned. this property will round the value to an integer. if you need a fractional value, use element.getboundingclientrect(). syntax var intelemoffsetheight = element.offsetheight; intelemoffsetheight is a variable storing an inte...
HTMLElement.offsetParent - Web APIs
the htmlelement.offsetparent read-only property returns a reference to the element which is the closest (nearest in the containment hierarchy) positioned ancestor element. if there is no positioned ancestor element, the nearest ancestor td, th, table will be returned, or the body if there are no ancestor table elements either. note: offsetparent returns null in the following situations: the element or its parent element has the display property set to none. the element has the position property set to fixed (firefox returns <body>). the element is <body> or <html>. offsetparent is useful because offsettop and offsetleft are relative to its padding edge. syntax parentobj = element.offsetparent; parentobj is an object reference to the element in which the current element is o...
HTMLElement.oncut - Web APIs
Web › API › HTMLElement › oncut
the htmlelement.oncut property of the htmlelement interface is an eventhandler that processes cut events. the cut event fires when the user attempts to cut text. syntax target.oncut = functionref; value functionref is a function name or a function expression. the function receives a clipboardevent object as its sole argument. example this example allows text to be copied from the <textarea>, but doesn't allow text to be cut. it also logs each copy and cut attempt. html <h3>play with this text area:</h3> <textarea id="editor" rows="3">try copying and cutting the text in this field!</textarea> <h3>log:</h3> <p id="log"></p> javascript function logcopy(event) { log.innertext = 'copied!\n' + log.innertext; } function preventcut(event) { event.preventdefault(); log.i...
HTMLElement.outerText - Web APIs
htmlelement.outertext is a non-standard property. as a getter, it returns the same value as node.innertext. as a setter, it removes the current node and replaces it with the given text. example see this stackoverflow answer. specification not part of any specification. standards discussion: whatwg/html#668. ...
HTMLElement: pointercancel event - Web APIs
active. the browser decides that the user started pointer input accidentally. this can happen if, for example, the hardware supports palm rejection to prevent a hand resting on the display while using a stylus from accidentally triggering events. the touch-action css property prevents the input from continuing. after the pointercancel event is fired, the browser will also send pointerout followed by pointerleave. examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointercancel', (event) => { console.log('pointer event cancelled'); }); using the onpointercancel event handler property: const para = document.queryselector('p'); para.onpointercancel = (event) => { console.log('pointer event cancelled'); }; specifications ...
HTMLElement: transitioncancel event - Web APIs
ansition = document.queryselector('.transition'); transition.addeventlistener('transitioncancel', () => { console.log('transition canceled'); }); the same, but using the ontransitioncancel property instead of addeventlistener(): const transition = document.queryselector('.transition'); transition.ontransitioncancel = () => { console.log('transition canceled'); }; live example in the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition"></div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform background; transition-duration: 2s; transition-delay: 2s; } .transition:hover { transform: rotate(90deg); background: rgba(25...
HTMLElement: transitionend event - Web APIs
d adds a listener to the transitionend event: const transition = document.queryselector('.transition'); transition.addeventlistener('transitionend', () => { console.log('transition ended'); }); the same, but using the ontransitionend: const transition = document.queryselector('.transition'); transition.ontransitionend = () => { console.log('transition ended'); }; live example in the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition">hover over me</div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); backgr...
HTMLElement: transitionrun event - Web APIs
event: el.addeventlistener('transitionrun', () => { console.log('transition is running but hasn\'t necessarily started transitioning yet'); }); the same, but using the ontransitionrun property instead of addeventlistener(): el.ontransitionrun = () => { console.log('transition started running, and will start transitioning when the transition delay has expired'); }; live example in the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition">hover over me</div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); backg...
HTMLElement: transitionstart event - Web APIs
event handler property ontransitionstart examples this code adds a listener to the transitionstart event: element.addeventlistener('transitionstart', () => { console.log('started transitioning'); }); the same, but using the ontransitionstart property instead of addeventlistener(): element.ontransitionrun = () => { console.log('started transitioning'); }; live example in the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition">hover over me</div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); backg...
HTMLEmbedElement - Web APIs
tmlelement interface it also has available to it by inheritance) for manipulating <embed> elements. this topic describes the htmlembedelement interface as defined in the standard. it does not address earlier, non-standardized version of the interface. ...
HTMLFormControlsCollection - Web APIs
trol elements. it represents the lists returned by the htmlformelement interface's elements property and the htmlfieldsetelement interface's elements property. this interface replaces one method from htmlcollection, on which it is based. ...
HTMLFormElement.enctype - Web APIs
text/plain: a type introduced in html5. this value can be overridden by a formenctype attribute on a <button> or <input> element. ...
HTMLFormElement.length - Web APIs
t.length read-only property returns the number of controls in the <form> element. you can access the list of the form's controls using the elements property. this includes both elements that are descendents of the <form> element as well as elements that are made members of the form using their form property. the elements included by htmlformelement.elements and htmlformelement.length are the following: <button> <fieldset> <input> (with the exception that any whose type is "image" are omitted for historical reasons) <object> <output> <select> <textarea> no other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms. syntax numcontrols = form.length; value numcontrols is the number of...
HTMLFormElement.name - Web APIs
the htmlformelement.name property represents the name of the current <form> element as a string. if your <form> element contains an element named name then that element overrides the form.name property, so that you can't access it. internet explorer (ie) does not allow the name attribute of an element created using createelement() to be set or modified using the name property. syntax var string = form.name; form.name = string; example var form1name = document.getelementbyid('form1').name; if (form1name != document.form.form1) { // browser doesn't support this form of reference } specifications specification status comment html living standardthe definition of 'htmlformelement: name' in that specification. living standard ...
HTMLFormElement.requestSubmit() - Web APIs
had the submit() method since the dawn of time? the answer is simple. submit() submits the form, but that's all it does. requestsubmit(), on the other hand, acts as if a submit button were clicked. the form's content is validated, and the form is submitted only if validation succeeds. once the form has been submitted, the submit event is sent back to the form object. examples in the example below, the form is submitted by attempting to send the request using requestsubmit() if it's available. if a submit button with the id main-submit is found, that's used to submit the form. otherwise, the form is submitted with no submitter parameter, so it's submitted directly by the form itself. if, on the other hand, requestsubmit() isn't available, this code falls back to calling the form's submit(...
HTMLHeadingElement - Web APIs
the htmlheadingelement interface represents the different heading elements, <h1> through <h6>. it inherits methods and properties from the htmlelement interface. ...
HTMLHtmlElement - Web APIs
root node for a given html document. this object inherits the properties and methods described in the htmlelement interface. you can retrieve the htmlhtmlelement object for a given document by reading the value of the document.documentelement property. ...
HTMLHyperlinkElementUtils.hash - Web APIs
the fragment is not percent-decoded. if the url does not have a fragment identifier, this property contains an empty string, "". ...
HTMLHyperlinkElementUtils.href - Web APIs
the htmlhyperlinkelementutils.href property is a stringifier that returns a usvstring containing the whole url, and allows the href to be updated. syntax string = object.href; object.href = string; examples // lets imagine an <a id="myanchor" href="https://developer.mozilla.org/htmlhyperlinkelementutils/href"> element is in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.href; // returns: 'https://developer.mozilla.org/htmlhyperlinkelementutils/href' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.href' in that specification. living standard initial definition. ...
HTMLHyperlinkElementUtils.pathname - Web APIs
the htmlhyperlinkelementutils.pathname property is a usvstring containing an initial '/' followed by the path of the url (or the empty string if there is no path). syntax string = object.pathname; object.pathname = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/docs/htmlhyperlinkelementutils.pathname"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.pathname; // returns:'/docs/htmlhyperlinkelementutils.pathname' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.pathname' in that specification. living standard initial definition. ...
HTMLHyperlinkElementUtils.search - Web APIs
modern browsers provide urlsearchparams and url.searchparams to make it easy to parse out the parameters from the querystring. ...
HTMLIFrameElement.setNfcFocus() - Web APIs
specifications not part of any specification. ...
Image() - Web APIs
ic width and height of the image in css pixels are reflected through the properties htmlimageelement.naturalwidth and htmlimageelement.naturalheight. if no size is specified in the constructor both pairs of properties have the same values. examples var myimage = new image(100, 200); myimage.src = 'picture.jpg'; document.body.appendchild(myimage); this would be the equivalent of defining the following html tag inside the <body>: <img width="100" height="200" src="picture.jpg"> specifications specification status comment html living standardthe definition of 'image()' in that specification. living standard ...
HTMLImageElement.decoding - Web APIs
string representing the decoding hint. possible values are: sync: decode the image synchronously for atomic presentation with other content. async: decode the image asynchronously to reduce delay in presenting other content. auto: default mode, which indicates no preference for the decoding mode. the browser decides what is best for the user. usage notes the decoding property allows you to control whether or not the browser is allowed to try to parallelize loading your image. if doing so would cause problems, you can specify sync to disable asynchronous loading. this can be useful when applied to <img> elements, but may be even more so when used for offscreen image objects. examples var img = new image(); img.decoding = 'sync'; img.src = 'img/logo.png'; specifications ...
HTMLImageElement.src - Web APIs
tting the element's src property. if you use the srcset content attribute to provide multiple image options for different display pixel densities, the url specified by the src attribute is used in one of two ways: as a fallback for browsers that don't support srcset. as an equivalent for specifying an image in srcset with the size multiplier 1x; that is, the image specified by src is used on low-density screens (such as typical 72 dpi or 96 dpi displays). additionally, if you use src along with both sizes (or the corresponding sizes content attribute) and srcset in order to choose an image based on the viewport size, the src attribute is only used as a fallback for browsers that don't support sizes and srcset; otherwise, it's not used at all. examples specifying a single image html ...
HTMLImageElement.useMap - Web APIs
attribute with a pound or hash symbol prepended to it. consider a <map> that looks like this: <map name="mainmenu-map"> <area shape="circle" coords="25, 25, 75, 75" href="/index.html" alt="return to home page"> <area shape="rect" coords="25, 25, 100, 150" href="/index.html" alt="shop"> </map> given the image map named mainmenu-map, the image which uses it should look something like the following: <img src="menubox.png" usemap="#mainmenu-map"> for additional examples (including interactive ones), see the articles about the <map> and <area> elements, as well as the guide to using image maps. example 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/interacti...
HTMLInputElement.stepUp() - Web APIs
input.stepup() } } css input:invalid { border: red solid 3px; } result note if you don't pass a parameter to the stepup method, it defaults to 1. any other value is a multiplier of the step attribute value, which in this case is 5. if you pass 4 as the stepincrement, the input will stepup by 4 * 5, or 20. if the parameter is 0, the number will not be incremented. the stepup will not allow the input to out of range, in this case stopping when it reaches 400, and rounding down any floats that are passed as a parameter. try setting the step increment to 1.2. what happens when you invoke the method? try setting the value to 4, which is not valid. what happens when you invoke the method? specifications specification status comment html living standardthe...
HTMLInputElement.webkitEntries - Web APIs
called webkitentries in the specification due to its origins as a google chrome-specific api. it's likely to be renamed someday. syntax var entries = htmlinputelement.webkitentries; value an array of objects based on filesystementry, each representing one file which is selected in the <input> element. more specifically, files are represented by filesystemfileentry objects, and, if they're allowed, directories are represented by filesystemdirectoryentry objects. example this example shows how to create a file selection <input> element and process the selected files. html <input id="files" type="file" multiple> javascript document.getelementbyid("files").addeventlistener("change", function(event) { event.target.webkitentries.foreach(function(entry) { /* do stuff with the entry...
HTMLInputElement.webkitdirectory - Web APIs
that the <input> element should let the user select directories instead of files. when a directory is selected, the directory and its entire hierarchy of contents are included in the set of selected items. the selected file system entries can be obtained using the webkitentries property. syntax htmlinputelement.webkitdirectory = boolvalue value a boolean; true if the <input> element should allow picking only directories or false if only files should be selectable. understanding the results after the user makes a selection, each file object in files has its file.webkitrelativepath property set to the relative path within the selected directory at which the file is located. for example, consider this file system: photoalbums birthdays jamie's 1st birthday ...
HTMLMapElement - Web APIs
the htmlmapelement interface provides special properties and methods (beyond those of the regular object htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of map elements. ...
HTMLMediaElement.autoplay - Web APIs
much more in-depth look at autoplay, autoplay blocking, and how to respond whena autoplay is blocked by the user's browser, see our article autoplay guide for media and web audio apis. syntax htmlmediaelement.autoplay = true | false; var autoplay = htmlmediaelement.autoplay; value a boolean whose value is true if the media element will begin playback as soon as enough content has loaded to allow it to do so without interruption. note: some browsers offer users the ability to override autoplay in order to prevent disruptive audio or video from playing without permission or in the background. do not rely on autoplay actually starting playback and instead use play event. examples ... <video id="video" controls> <source src="https://player.vimeo.com/external/250688977.sd.mp4?s=d14b1f...
HTMLMediaElement.canPlayType() - Web APIs
ikely it is that the current browser will be able to play media of a given mime type. note: this feature is not available in web workers. syntax canplayresponse = audioorvideo.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...
HTMLMediaElement.captureStream() - Web APIs
eam 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 explanation. specifications...
HTMLMediaElement.disableRemotePlayback - Web APIs
syntax var remoteplaybackdisabled ​= element.disableremoteplayback; value a boolean indicating whether the media element may have a remote playback ui. ...
HTMLMediaElement: loadstart event - Web APIs
living standard html5the definition of 'loadstart media event' in that specification. recommendation ...
HTMLMediaElement.onencrypted - Web APIs
the onencrypted property of the htmlmediaelement is an event handler, fired whenever an encrypted event occurs, denoting the media is encrypted. this interface inherits from the extendableevent interface. ...
HTMLMediaElement.onwaitingforkey - Web APIs
the onwaitingforkey property of the htmlmediaelement is an event handler, fired when a waitingforkey event occurs, when playback is blocked while waiting for an encryption key. this interface inherits from the extendableevent interface. ...
HTMLMediaElement: progress event - Web APIs
living standard html5the definition of 'progress media event' in that specification. recommendation ...
HTMLMediaElement.seekToNextFrame() - Web APIs
ant). possible uses for this method include filtering and editing of video content. this method returns immediately, returning a promise, whose fulfillment handler is called when the seek operation is complete. in addition, a seeked event is sent to let interested parties know that a seek has taken place. if the seek fails because the media is already at the last frame, a seeked event occurs, followed immediately by an ended event. if there is no video on the media element, or the media isn't seekable, nothing happens. syntax var seekcompletepromise = htmlmediaelement.seektonextframe(); htmlmediaelement.seektonextframe(); return value a promise which is fulfilled once the seek operation has completed. firefox 49 returns undefined instead of a promise, and performs the seek operation...
HTMLMenuElement - Web APIs
the htmlmenuelement interface provides special properties (beyond those defined on the regular htmlelement interface it also has available to it by inheritance) for manipulating <menu> elements. ...
HTMLMenuItemElement - Web APIs
the htmlmenuitemelement interface provides special properties (beyond those defined on the regular htmlelement interface it also has available to it by inheritance) for manipulating <menuitem> elements. ...
HTMLModElement - Web APIs
htmlmodelement interface provides special properties (beyond the regular methods and properties available through the htmlelement interface they also have available to them by inheritance) for manipulating modification elements, that is <del> and <ins>. ...
HTMLOptGroupElement - Web APIs
the htmloptgroupelement interface provides special properties and methods (beyond the regular htmlelement object interface they also have available to them by inheritance) for manipulating the layout and presentation of <optgroup> elements. ...
HTMLOptionElement - Web APIs
the htmloptionelement interface represents <option> elements and inherits all classes and methods of the htmlelement interface. ...
HTMLElement.focus() - Web APIs
the htmlelement.focus() method sets focus on the specified element, if it can be focused. the focused element is the element which will receive keyboard and similar events by default. syntax element.focus(options); // object parameter parameters options optional an optional object providing options to control aspects of the focusing process. this object may contain the following property: preventscroll optional a boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view. a value of false for preventscroll (the default) means that the browser will scroll the element into view after focusing it. if preventscroll is set to true, no scrolling will occur. examples focus on a text field javascript focusmethod...
HTMLOrForeignElement.nonce - Web APIs
in later implementations, elements only expose their nonce attribute to scripts (and not to side-channels like css attribute selectors). ...
HTMLOutputElement - Web APIs
the htmloutputelement interface provides properties and methods (beyond those inherited from htmlelement) for manipulating the layout and presentation of <output> elements. ...
HTMLPictureElement - Web APIs
the htmlpictureelement interface represents a <picture> html element. it doesn't implement specific properties or methods. ...
HTMLProgressElement - Web APIs
the htmlprogresselement interface provides special properties and methods (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of <progress> elements. ...
HTMLQuoteElement - Web APIs
the htmlquoteelement interface provides special properties and methods (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating quoting elements, like <blockquote> and <q>, but not the <cite> element. ...
HTMLScriptElement.referrerPolicy - Web APIs
no referrer information is sent along with requests. ...
HTMLSelectElement.form - Web APIs
html <form action="http://www.google.com/search" method="get"> <label>google: <input type="search" name="q"></label> <input type="submit" value="search..."> </form> javascript a property available on all form elements, "type" returns the type of the calling form element. for select, the two possible values are "select-one" or "select-multiple", depending on the type of selection list. ...
HTMLSelectElement.remove() - Web APIs
method removes the element at the specified index from the options collection for this select element. syntax collection.remove(index); parameters index is a long for the index of the htmloptionelement to remove from the collection. if the index is not found the method has no effect. ...
HTMLShadowElement - Web APIs
the htmlshadowelement interface represents a <shadow> html element, which is used in shadow dom. ...
HTMLSlotElement.assignedNodes() - Web APIs
ent. syntax var assignednodes = htmlslotelement.assignednodes(options) parameters options optional an object that sets options for the nodes to be returned. the available options are: flatten: a boolean indicating whether to return the assigned nodes of any available child <slot> elements (true) or not (false). defaults to false. return value an array of nodes. examples the following snippet is taken from our slotchange example (see it live also). let slots = this.shadowroot.queryselectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the slots, then add a slotchange event listener...
HTMLSlotElement.name - Web APIs
the name property of the htmlslotelement interface returns or sets the slot name. a slot is a placeholder inside a web component that users can fill with their own markup. syntax var name = htmlslotelement.name htmlslotelement.name = name value a domstring. examples the following snippet is taken from our slotchange example (see it live also). let slots = this.shadowroot.queryselectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template — which is the one that keeps having its contents changed in the example. every ti...
HTMLSlotElement: slotchange event - Web APIs
e) the actual nodes themselves. bubbles yes cancelable no interface event event handler property none in order to trigger a slotchange event, one has to set or remove the slot attribute. examples element.setattribute('slot', slotname); // element.assignedslot = $slot element.removeattribute('slot'); // element.assignedslot = null the following snippet is taken from our slotchange example (see it live also). let slots = this.shadowroot.queryselectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the <slot>s, then add a slotchange event listen...
HTMLSlotElement - Web APIs
elements assigned to this slot (and no other nodes). if the flatten option is set to true, it also returns the assigned elements of any other slots that are descendants of this slot. if no assigned nodes are found, it returns the slot's fallback content. events slotchange fired on an htmlslotelement instance (<slot> element) when the node(s) contained in that slot change. examples the following snippet is taken from our slotchange example (see it live also). let slots = this.shadowroot.queryselectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the slots, then add a slotchange event listener...
HTMLSpanElement - Web APIs
the htmlspanelement interface represents a <span> element and derives from the htmlelement interface, but without implementing any additional properties or methods. ...
HTMLTableCaptionElement - Web APIs
the htmltablecaptionelement interface special properties (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating table caption elements. ...
HTMLTableColElement - Web APIs
the htmltablecolelement interface provides special properties (beyond the htmlelement interface it also has available to it inheritance) for manipulating single or grouped table column elements. ...
HTMLTableElement.align - Web APIs
the htmltableelement.align property represents the alignment of the table. syntax htmltableelement.align = alignment; var alignment = htmltableelement.align; parameters alignment domstring with one of the following values: left center right example // set the alignmnet of a table var t = document.getelementbyid('tablea'); t.align = 'center'; specification w3c dom 2 html specification htmltableelement .align. ...
HTMLTableElement.rows - Web APIs
syntax htmlcollectionobject = table.rows; value an htmlcollection providing a live-updating list of the htmltablerowelement objects representing all of the <tr> elements contained in the table. ...
HTMLTableElement.rules - Web APIs
the htmltableelement.rules property indicates which cell borders to render in the table. ...
HTMLTableElement.tBodies - Web APIs
the collection returned includes implicit <tbody> elements. for example: <table> <tr> <td>cell one</td> </tr> </table> the html dom generated from the above html will have a <tbody> element even though the tags are not included in the source html. syntax htmlcollectionobject = table.tbodies example this snippet gets the number of bodies in a table. ...
HTMLTemplateElement - Web APIs
the htmltemplateelement interface enables access to the contents of an html <template> element. ...
HTMLTimeElement - Web APIs
the htmltimeelement interface provides special properties (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <time> elements. ...
HTMLTitleElement - Web APIs
the htmltitleelement interface contains the title for a document. this element inherits all of the properties and methods of the htmlelement interface. ...
HTMLUListElement - Web APIs
the htmlulistelement interface provides special properties (beyond those defined on the regular htmlelement interface it also has available to it by inheritance) for manipulating unordered list elements. ...
HTMLUnknownElement - Web APIs
the htmlunknownelement interface represents an invalid html element and derives from the htmlelement interface, but without implementing any additional properties or methods. ...
HTMLVideoElement.msIsLayoutOptimalForPlayback - Web APIs
this proprietary property is specific to internet explorer and microsoft edge. syntax htmlvideoelement.msislayoutoptimalforplayback: domstring; value boolean value set to true indicates that video is being rendered optimally (better performance and using less battery power). if false, improvements can be made to optimize performance. for msislayoutoptimalforplayback to be true, avoid the following: video elements with cascading style sheets (css) outlines set. rendering a video element through a canvas element. embedding video elements in a scalable vector graphics (svg). you can listen to the onmsvideooptimallayoutchanged event to be notified when the msislayoutoptimalforplayback property changes. *to enable stereo 3d playback, msislayoutoptimalforplayback must be true. see al...
msStereo3DPackingMode - Web APIs
so be large incompatibilities between implementations and the behavior may change in the future. msstereo3dpackingmode is a read/write property which gets or sets the frame-packing mode for stereo 3-d video content. this proprietary property is specific to internet explorer and microsoft edge. syntax htmlvideoelement.msstereo3dpackingmode(topbottom, sidebyside, none); value the following values return, or set, the stereo 3-d content packing as "topbottom", "sidebyside", or "none" for regular 2-d video. none (0): specifies regular 2-d video. topbottom (1): specifies stereo 3-d content packing and that the views are packed side-by-side in a single frame. sidebyside (2): specifies sidebyside stereo 3-d content packing and that the views are packed top-to-bottom in a single f...
msStereo3DRenderMode - Web APIs
be large incompatibilities between implementations and the behavior may change in the future. msstereo3drendermode is a read/write property which gets or sets whether the system display is set to stereo display (if stereo-capable). this proprietary property is specific to internet explorer and microsoft edge. syntax htmlvideoelement.msstereo3drendermode(mono, stereo); value the following values set the stereo display to mono or stereo. the default is mono. mono (0): specifies that stereo mode is disabled. stereo (1): specifies stereo mode is enabled. see also htmlvideoelement microsoft api extensions ...
HTMLVideoElement - Web APIs
ne browser to the other. you should either provide your video in a single format that all the relevant browsers supports, or provide multiple video sources in enough different formats that all the browsers you need to support are covered. ...
Headers() - Web APIs
Web › API › Headers › Headers
t inherits its data from the existing headers object. example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append: myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' or you can add the headers you want as the headers object is created. ...
Headers.delete() - Web APIs
Web › API › Headers › delete
the value of guard is immutable. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.delete(name); parameters name the name of the http header you want to delete from the headers object. returns void. ...
Headers.entries() - Web APIs
Web › API › Headers › entries
the both the key and value of each pairs are bytestring objects. note: this method is available in web workers. syntax headers.entries(); return value returns an iterator. ...
Headers.keys() - Web APIs
Web › API › Headers › keys
the keys are bytestring objects. note: this method is available in web workers. syntax headers.keys(); return value returns an iterator. ...
Headers.values() - Web APIs
Web › API › Headers › values
the values are bytestring objects. note: this method is available in web workers. syntax headers.values(); return value returns an iterator. ...
History.back() - Web APIs
Web › API › History › back
the history.back() method causes the browser to move back one page in the session history. it has the same effect as calling history.go(-1). if there is no previous page, this method call does nothing. this method is asynchronous. add a listener for the popstate event in order to determine when the navigation has completed. syntax history.back() examples the following short example causes a button on the page to navigate back one entry in the session history. html <button id="go-back">go back!</button> javascript document.getelementbyid('go-back').addeventlistener('click', () => { history.back(); }); specifications specification status comment html living standardthe definition of 'history.back()' in that specification. living standard no change fro...
History.forward() - Web APIs
Web › API › History › forward
the history.forward() method causes the browser to move forward one page in the session history. it has the same effect as calling history.go(1). this method is asynchronous. add a listener for the popstate event in order to determine when the navigation has completed. syntax history.forward() examples the following examples create a button that moves forward one step in the session history. html <button id='go-forward'>go forward!</button> javascript document.getelementbyid('go-forward').addeventlistener('click', e => { window.history.forward(); }) specifications specification status comment html living standardthe definition of 'history' in that specification. living standard no change from html5. html5the definition of 'history' in that ...
History.go() - Web APIs
Web › API › History › go
moves back two pages. if no value is passed or if delta equals 0, it has the same result as calling location.reload(). examples to move back one page (the equivalent of calling back()): history.go(-1) to move forward a page, just like calling forward(): history.go(1) to move forward two pages: history.go(2); to move backwards by two pages: history.go(-2); and, finally either of the following statements will reload the current page: history.go(); history.go(0); specifications specification status comment html living standardthe definition of 'history.go()' in that specification. living standard no change from html5. html5the definition of 'history.go()' in that specification. recommendation initial definition. ...
History.scrollRestoration - Web APIs
syntax const scrollrestore = history.scrollrestoration values auto the location on the page to which the user has scrolled will be restored. manual the location on the page is not restored. the user will have to scroll to the location manually. examples query the current scroll restoration behavior. ...
History.state - Web APIs
Web › API › History › state
the history.state property returns a value representing the state at the top of the history stack. this is a way to look at the state without having to wait for a popstate event. syntax const currentstate = history.state value the state at the top of the history stack. the value is null until the pushstate() or replacestate() method is used. examples the code below logs the value of history.state before using the pushstate() method to push a value to the history. the next line logs the value to the console again, showing that history.state now has a value. // should be null because we haven't modified the history stack yet console.log(`history.state before pushstate: ${history.state}`); // now push something on the stack history.pushstate({name: 'example'}, "pushstate example", 'page...
IDBCursor.continue() - Web APIs
position along its direction, to the item whose key matches the optional key parameter. if no key is specified, the cursor advances to the immediate next position, based on its direction. note: this feature is available in web workers. syntax cursor.continue(key); parameters key optional the key to position the cursor at. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbcursor's transaction is inactive. dataerror the key parameter may have any of the following conditions: the key is not a valid key. the key is less than or equal to this cursor's position and the cursor's direction is next or nextunique. the key is greater than or eq...
IDBCursor.continuePrimaryKey() - Web APIs
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: exception description transactioninactiveerror this idbcursor's transaction is inactive. dataerror the key parameter may have any of the following conditions: the key is not a valid key. the key is less than or equal to this cursor's position and the cursor's direction is next or nextunique. the key is greater than or eq...
IDBCursor.delete() - Web APIs
Web › API › IDBCursor › delete
) on cursors obtained from idbindex.openkeycursor(). for such needs, you have to use idbindex.opencursor() instead. note: this feature is available in web workers. syntax myidbcursor.delete(); returns an idbrequest object on which subsequent events related to this operation are fired. the result attribute is set to undefined. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbcursor's transaction is inactive. readonlyerror the transaction mode is read-only. invalidstateerror the cursor was created using idbindex.openkeycursor, is currently being iterated, or has iterated past its end. example in this simple fragment we create a transaction, ret...
IDBCursor.direction - Web APIs
note: this feature is available in web workers. syntax var direction = cursor.direction; value a string (defined by the idbcursordirection enum) indicating the direction in which the cursor is traversing the data. ...
IDBCursor - Web APIs
Web › API › IDBCursor
t, and, in a separate thread, updates the value at the current position of the cursor in the object store. this can be used to update specific records. constants these constants are no longer available — they were removed in gecko 25. you should use the string constants directly instead. (bug 891944) next : "next" : the cursor shows all records, including duplicates. it starts at the lower bound of the key range and moves upwards (monotonically increasing in the order of keys). nextunique : "nextunique" : the cursor shows all records, excluding duplicates. if multiple records exist with the same key, only the first one iterated is retrieved. it starts at the lower bound of the key range and moves upwards. prev : "prev" : the cursor shows all records, including duplicates. it st...
IDBCursorWithValue - Web APIs
nlimited number of cursors at the same time. you always get the same idbcursorwithvalue object representing a given cursor. operations are performed on the underlying index or object store. note: this feature is available in web workers. ...
IDBDatabase.deleteObjectStore() - Web APIs
nected database, along with any indexes that reference it. as with idbdatabase.createobjectstore, this method can be called only within a versionchange transaction. note: this feature is available in web workers. syntax dbinstance.deleteobjectstore(name); parameters name the name of the object store you want to delete. exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror occurs if the method was not called from a versionchange transaction callback. for older webkit browsers, you must call first. transactioninactiveerror occurs if a request is made on a source database that doesn't exist (e.g. has been deleted or removed.) in firefox previous to version 41, an invalidstatee...
IDBDatabase.name - Web APIs
Web › API › IDBDatabase › name
eddb.open("todolist", 4); // these two event handlers act on the database being // opened successfully, or not dbopenrequest.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. this is used a lot below db = dbopenrequest.result; // this line will log the name of the database, which should be "todolist" console.log(db.name); }; specifications specification status comment indexed database api 2.0the definition of 'name' in that specification. recommendation indexed database api draftthe definition of 'name' in that specification. recommendation...
IDBDatabase.objectStoreNames - Web APIs
dexeddb.open("todolist", 4); // these two event handlers act on the database being opened successfully, or not dbopenrequest.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. this is used a lot below db = dbopenrequest.result; // this line will log the version of the connected database, which should be // an object that looks like { ['my-store-name'] } console.log(db.objectstorenames); }; specifications specification status comment indexed database api 2.0the definition of 'objectstorenames' in that specification. recommendation indexed data...
IDBDatabase.version - Web APIs
eddb.open("todolist", 4); // these two event handlers act on the database // being opened successfully, or not dbopenrequest.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. this is used a lot below db = dbopenrequest.result; // this line will log the version of the connected database, which should be "4" console.log(db.version); }; specifications specification status comment indexed database api 2.0the definition of 'version' in that specification. recommendation indexed database api draftthe definition of 'version' in that specification. ...
IDBEnvironment - Web APIs
xeddb property, which provides access to indexeddb functionality. it is the top level indexeddb interface implemented by the window and worker objects. note: this feature is available in web workers. properties idbenvironment.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; contains an idbfactory object. ...
databases - Web APIs
tions and browser compatibility is limited. syntax const promise = indexeddb.databases() parameters the method does not take in any parameters. return value a promise that resolves either to an error or a list of dictionaries, each with two elements, name and version. name the database name. version the database version. exceptions this method may raise a domexception of the following types: attribute description securityerror the method is called from an opaque origin. other error specification does not describe all possible errors. example const promise = indexeddb.databases() promise.then(databases => { console.log(databases) }) specifications specification status comment indexed database api dr...
IDBFactory.deleteDatabase() - Web APIs
ng deleted, then an error event is fired on the request object that is returned from this method. when deletedatabase() is called, any other open connections to this particular database will get a versionchange event. note: this feature is available in web workers. syntax for the current standard: var request = indexeddb.deletedatabase(name); for the experimental version with options (see below): var request = indexeddb.deletedatabase(name, options); parameters name the name of the database you want to delete. note that attempting to delete a database that doesn't exist does not throw an exception, in contrast to idbdatabase.deleteobjectstore(), which does throw an exception if the named object store does not exist. optionsnon-standard in gecko, since version 26, you can include...
IDBFactory - Web APIs
ry.open the current method to request opening a connection to a database. idbfactory.deletedatabase a method to request the deletion of a database. idbfactory.cmp a method that compares two keys and returns a result indicating which one is greater in value. idbfactory.databases a method that returns a list of all available databases, including their names and versions. example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases. for a full working example, see our to-do notifications app (view example live.) // in the following line, you should include the prefixes of implementations you want to test. window.indexeddb = window.indexeddb || window.mozindexeddb || window.webkitindexeddb || window.msindexeddb; // do...
IDBFactorySync - Web APIs
s the database using the specified name and description. idbdatabasesync open ( in domstring name, in domstring description ) raises (idbdatabaseexception); parameters name the name for the database. description the description for the database. returns idbdatabasesync an object to access the open database. exceptions this method can raise an idbdatabaseexception with the following codes: non_transient_err if the name parameter is not valid. a valid name is any string including the empty string. unknown_err if an error occurs while the database is being opened. ...
IDBIndex.getAll() - Web APIs
Web › API › IDBIndex › getAll
getall(query); var getallkeysrequest = idbindex.getall(query, count); parameters query optional a key or an idbkeyrange identifying the records to retrieve. if this value is null or missing, the browser will use an unbound key range. count optional the number records to return. if this value exceeds the number of records in the query, the browser will only retrieve the first item. if it is lower than 0 or greater than 232-1 a typeerror exception will be thrown. return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive. invalidstateerror the idbi...
IDBIndex.getAllKeys() - Web APIs
tallkeys(query); var allkeysrequest = idbindex.getallkeys(query, count); parameters query optional a key or an idbkeyrange identifying the keys to retrieve. if this value is null or missing, the browser will use an unbound key range. count optional the number records to return. if this value exceeds the number of records in the query, the browser will only retrieve the first item. if it is lower than 0 or greater than 232-1 a typeerror exception will be thrown. return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive. invalidstateerror the idbi...
IDBIndex.isAutoLocale - Web APIs
the isautolocale read-only property of the idbindex interface returns a boolean indicating whether the index had a locale value of auto specified upon its creation (see createindex()'s optionalparameters.) syntax var myindex = objectstore.index('index'); console.log(myindex.isautolocale); value a boolean. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key. the isautolocale value is logged to the console. function displaydatabyindex() { table...
IDBIndex.keyPath - Web APIs
Web › API › IDBIndex › keyPath
the keypath property of the idbindex interface returns the key path of the current index. if null, this index is not auto-populated. note: this feature is available in web workers. syntax var mykeypath = myindex.keypath; value any data type that can be used as a key path. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key. the key path of the current index is logged to the console: it should be returned as lname. finally, we iterate through each reco...
IDBIndex.locale - Web APIs
Web › API › IDBIndex › locale
returns the locale of the index (for example en-us, or pl) if it had a locale value specified upon its creation (see createindex()'s optionalparameters.) note that this property always returns the current locale being used in this index, in other words, it never returns "auto". syntax var myindex = objectstore.index('index'); console.log(myindex.locale); value a domstring. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key. the locale value is logged to t...
IDBIndex.multiEntry - Web APIs
n optional options parameter whose multientry property is set to true/false. note: this feature is available in web workers. syntax var ismultientry = myindex.multientry; value a boolean: value effect true there is one record in the index for each item in an array of keys. false there is one record for each key that is an array. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key. the multi-entry status of the i...
IDBIndex.name - Web APIs
Web › API › IDBIndex › name
e an index's name. invalidstateerror the index, or its object store, has been deleted; or the current transaction is not an upgrade transaction. you can only rename indexes during upgrade transactions; that is, when the mode is "versionchange". transactioninactiveerror the current transaction is not active. constrainterror an index is already using the specified name. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor() — this works the same as opening a cursor directly on an idbobjectstore using opencursor() except that the returned records are sorted based on the index, not the primary key. the name of the index is logged to the ...
IDBIndex.objectStore - Web APIs
we then open a basic cursor on the index using idbindex.opencursor. ...
IDBIndex.unique - Web APIs
Web › API › IDBIndex › unique
the unique read-only property returns a boolean that states whether the index allows duplicate keys. this is decided when the index is created, using the idbobjectstore.createindex method. this method takes an optional parameter, unique, which if set to true means that the index will not be able to accept duplicate entries. note: this feature is available in web workers. syntax var isunique = idbindex.unique; value a boolean: value effect true the current index does not allow duplicate values for a key. false the current index allows duplicate key values. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using i...
IDBLocaleAwareKeyRange - Web APIs
tionalparameters) — 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 idblocaleawarekeyrange is that the latter doesn’t do the aforementioned check. developers should always use idblocaleawarekeyrange when dealing with local...
FileHandle.getFile() - 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. summary the getfile method allows to retrieve a read-only snapshot of the handled file in the form of a file object. syntax var request = instanceoffilehandle.getfile(); return a domrequest object. in case of success, the request's result is a file object. specifications specification status comment filesystem api editor's draft draft proposal ...
FileHandle.open() - 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. summary the open method returns a lockedfile object that allows to safely write in the file. syntax var myfile = instanceoffilehandle.open(mode); parameters mode a string that specifies the writing mode for the file. it can be readonly or readwrite. return a lockedfile object. specifications specification status comment filesystem api editor's draft draft proposal ...
IDBObjectStore.count() - Web APIs
ture is available in web workers. syntax var request = objectstore.count(); var request = objectstore.count(query); parameters query optional a key or idbkeyrange object that specifies a range of records you want to count. return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror this idbobjectstore has been deleted. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the specified key or key range is invalid. example in this simple fragment we create a transaction, retrieve an object store, then count the number of records in the st...
IDBObjectStore.getAll() - Web APIs
syntax var request = objectstore.getall(); var request = objectstore.getall(query); var request = objectstore.getall(query, count); parameters query optional a key or idbkeyrange to be queried. if nothing is passed, this will default to a key range that selects all the records in this object store. count optional specifies the number of values to return if more than one is found. if it is lower than 0 or greater than 232-1 a typeerror exception will be thrown. return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror ...
IDBObjectStore.getAllKeys() - Web APIs
that method provides a cursor if the record exists, and no cursor if it does not. syntax var request = objectstore.getallkeys(); var request = objectstore.getallkeys(query); var request = objectstore.getallkeys(query, count); parameters query optional a value that is or resolves to an idbkeyrange. count optional specifies the number of values to return if more than one is found. if it is lower than 0 or greater than 232-1 a typeerror exception will be thrown. return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror ...
IDBObjectStore.getKey() - Web APIs
ated and set as the result of the request object. note: this feature is available in web workers. syntax var request = objectstore.getkey(key); parameters key the key or key range that identifies the record to be retrieved. return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbobjectstore has been deleted or removed. example let openrequest = indexeddb.open("telemetry"); openrequest.onsuccess = (event) =...
IDBObjectStore.openCursor() - Web APIs
ange that selects all the records in this object store. direction optional an idbcursordirection telling the cursor what direction to travel. valid values are "next", "nextunique", "prev", and "prevunique". the default is "next". return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror this idbobjectstore or idbindex has been deleted. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the specified key or key range is invalid. example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to ite...
IDBObjectStore.openKeyCursor() - Web APIs
ange that selects all the records in this object store. direction optional an idbcursordirection telling the cursor what direction to travel. valid values are "next", "nextunique", "prev", and "prevunique". the default is "next". return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror this idbobjectstore or idbindex has been deleted. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the specified key or key range is invalid. example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to ite...
IDBObjectStore - Web APIs
tion, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBOpenDBRequest.onblocked - Web APIs
= indexeddb.open("todolist", 4); // these two event handlers act on the database being opened // successfully, or not request.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; request.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. // this is used a lot below db = request.result; // run the displaydata() function to populate the task list with // all the to-do list data already in the idb displaydata(); }; // this event handles the event whereby a new version of the // database needs to be created. either one has not been created // before, or a new version number has been submitted via the // window.indexeddb.open line above //it is only im...
IDBOpenDBRequest.onupgradeneeded - Web APIs
the onupgradeneeded property of the idbopendbrequest interface is the event handler for the upgradeneeded event, triggered when a database of a bigger version number than the existing stored database is loaded. the event passed to the listener is an idbversionchangeevent. inside the event handler function you can include code to upgrade the database structure, as shown in the example below. note: this feature is available in web workers. syntax idbopendbrequest.onupgradeneeded = function(event) { ... }; example in the following example you can see the onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. for a full working example, see our to-do notifications app (view example live.) var db; // request version 3 o...
IDBRequest.onerror - Web APIs
the onerror event handler of the idbrequest interface handles the error event, fired when a request returns an error. the event handler takes one parameter, an error event with type="error". note: this feature is available in web workers. syntax request.onerror = function(event) { ... }; example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store. also included at the bottom is an onerror function that reports what the error was if the request fails. for a full working example, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transacti...
IDBRequest.onsuccess - Web APIs
the onsuccess event handler of the idbrequest interface handles the success event, fired when the result of a request is successfully returned. the event handler takes one parameter, a success event with type="success". note: this feature is available in web workers. syntax request.onsuccess = function(event) { ... }; example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store. for a full working example, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").ob...
IDBRequest.result - Web APIs
Web › API › IDBRequest › result
the result read-only property of the idbrequest interface returns the result of the request. if the request failed and the result is not available, an invalidstateerror exception is thrown. note: this feature is available in web workers. syntax var myresult = request.result; value any example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store. for a full working example, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get th...
IDBRequest.source - Web APIs
Web › API › IDBRequest › source
, such as an index or an object store. if no source exists (such as when calling indexeddb.open), it returns null. note: this feature is available in web workers. syntax var idbindex = request.source; var idbcursor = request.source; var idbobjectstore = request.source; value an object representing the source of the request, such as an idbindex, idbobjectstore or idbcursor. example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store in another request. the source of the 2nd request is logged to the developer console. for a full working example, see our to-do notifications app (v...
IDBTransaction: abort event - Web APIs
the abort event is fired when an indexeddb transaction is aborted. bubbles yes cancelable no interface event event handler property onabort this can happen for any of the following reasons: bad requests, (for example, trying to add the same key twice, or put the same index key when the key has a uniqueness constraint), an explicit abort() call an uncaught exception in the request's success/error handler, an i/o error (an actual failure to write to disk, for example disk detached, or other os/hardware failure) quota exceeded. examples this example opens a database (creating the database if it does not exist), then opens a transaction, adds a listener to the abort event, then aborts the transaction to trigger the event. // open...
IDBTransaction.commit() - Web APIs
tion, ready for adding the data var transaction = db.transaction(["mydb"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBVersionChangeEvent.newVersion - Web APIs
the newversion read-only property of the idbversionchangeevent interface returns the new version number of the database. note: this feature is available in web workers. syntax var newversion = idbversionchangeevent.newversion value a 64-bit integer. example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases. these events are fired via the custom idbversionchangeevent interface. for a full working example, see our to-do notifications app (view example live.) var note = document.queryselector("ul"); // in the following line, you should include the prefixes of // implementations you want to test. window.indexeddb = window.indexeddb || window.mozindexeddb || window.webkitindexeddb || window.msindexeddb; // don't us...
IIRFilterNode() - Web APIs
the iirfilternode() constructor of the web audio api creates a new iirfilternode object which an audionode processor which implements a general infinite impulse response filter. syntax var iirfilternode = new iirfilternode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options options are as follows: feedforward: a sequence of feedforward coefficients. feedback: a sequence of feedback coefficients. unlike other nodes in the web audio api, the options passed into the iir filter upon creation are not optional. the filter needs these values to work and with the vast range of filters available, there is no default. return value a new iirfilternode object instance. examples let feedforward = ...
IIRFilterNode.getFrequencyResponse() - Web APIs
ray to receive the computed magnitudes of the freqency response for each frequency value in the frequencyarray. phaseresponseoutput a float32array to receive the computed phase response values in radians for each frequency value in the input frequencyarray. return value undefined exceptions notsupportederror the three arrays provided are not all of the same length. examples in the following example we are using an iir filter on a media stream (for a complete full demo, see our stream-source-buffer demo live, or read its source.) as part of this demo, we get the frequency responses for this iir filter, for five sample frequencies. we first create the float32array objects we need, one containing the input frequencies, and two to receive the output magnitude and phase values: var m...
ImageCapture() constructor - Web APIs
syntax const imagecapture = new imagecapture(videotrack) parameters videotrack a mediastreamtrack from which the still images will be taken. this can be any source, such as an incoming stream of a video conference, a playing movie, or the stream from a webcam. return value a new imagecapture object which can be used to capture still frames from the specified video track. example the following example shows how to use a call to mediadevices.getusermedia() to retrieve the mediastreamtrack needed by the imagecapture() constructor. navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); }) .catch(error => co...
ImageCapture.getPhotoCapabilities() - Web APIs
the getphotocapabilities() method of the imagecapture interface returns a promise that resolves with a photocapabilities object containing the ranges of available configuration options. syntax const capabilitiespromise = imagecaptureobj.getphotocapabilities() return value a promise that resolves with a photocapabilities object. example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities() to modify the size of an input range. this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream. const input = document.queryselector('input[type="range"]'); var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { d...
InputDeviceCapabilities - Web APIs
bilities object provides information about the physical device responsible for generating a touch event. syntax var inputdevicecapabilities = new inputdevicecapabilities([inputdevicecapabilitiesinit]) returns an instance of the inputdevicecapabilities interface. parameters inputdevicecapabilitiesinit optional a dictionary object containing a set of device capabilities. it contains the following property. firetouchevents: a boolean that indicates whether the device dispatches touch events. specifications specification status comment inputdevicecapabilities draft initial definition. ...
InputDeviceCapabilities - Web APIs
sponsible for generating input events. events caused by the same physical input device get the same instance of this object, but the converse isn't true. for example, two mice with the same capabilities in a system may appear as a single inputdevicecapabilities instance. in some instances, inputdevicecapabilities represents the capabilities of logical devices rather than physical devices. this allows, for example, touchscreen keyboards and physical keyboards to be represented the same way when they produce the same input. constructors inputdevicecapabilities.inputdevicecapabilities() creates an inputdevicecapabilities object. properties inputdevicecapabilities.firestoucheventsread only a boolean that indicates whether the device dispatches touch events. methods none. specific...
InputEvent() - Web APIs
data: (optional) a string containing characters to insert. ...
InputEvent.data - Web APIs
Web › API › InputEvent › data
the data read-only property of the inputevent interface returns a domstring with the inserted characters. this may be an empty string if the change doesn't insert text (such as when deleting characters, for example). syntax var astring = inputevent.data; value a domstring. examples in the following simple example we've set up an event listener on the input event so that when any change is made to the contents of the <input> element (either by typing or pasting), the text that was added is retrieved via the inputevent.data property and reported in the paragraph below the input. <p>some text to copy and paste.</p> <input type="text"> <p class="result"></p> var editable = document.queryselector('input') var result = document.queryselector('.result'); editable.addeventlistener('inpu...
InputEvent.dataTransfer - Web APIs
the datatransfer read-only property of the inputevent interface returns a datatransfer object containing information about richtext or plaintext data being added to or removed from editible content. syntax var datatransfer = inputevent.datatransfer value a datatransfer object. examples in the following simple example we've set up an event listener on the input event so that when any content is pasted into the contenteditable <p> element, its html source is retrieved via the inputevent.datatransfer.getdata() method and reported in the paragraph below the input. try copying and pasting some of the content provided to see the effects. <p><span style="font-weight: bold; color: blue">whoa, bold blue text!</span></p> <p><span style="font-style: italic; color: red">exciting: italic red te...
InputEvent - Web APIs
the inputevent interface represents an event notifying of editable content change. ...
InstallEvent.InstallEvent() - Web APIs
the installevent() constructor creates a new installevent object. syntax var myinstallevent = new installevent(type, init); parameters type the type of the event. init optional an options object containing any custom settings that you want to apply to the event object. available options are as follows: activeworker: the serviceworker that is currently actively controlling the page. ...
InstallEvent - Web APIs
d on the serviceworkerglobalscope of a serviceworker. as a child of extendableevent, it ensures that functional events such as fetchevent are not dispatched during installation. this interface inherits from the extendableevent interface. ...
enabled - Web APIs
or not software installation is enabled for this client machine. method of installtrigger object syntax boolean enabled (); parameters none returns true if software installation is enabled for this client machine; otherwise, false. ...
installChrome - Web APIs
url url is a string containing a full or relative url to download name name is displayed in the dialog, but is also used to *select* the theme somust match exactly the name in the internal manifest.rdf file. ...
startSoftwareUpdate - Web APIs
summary triggers the downloading and installation of the software at the specified url. method of installtrigger object syntax boolean startsoftwareupdate ( string url); parameters the startsoftwareupdate method has the following parameter: url a uniform resource locator specifying the location of the xpi file containing the software. returns true. description the startsoftwareupdate method triggers a software download and install from the specified url. this method has been largely superseded by newer install method, which is more flexible and allows you to install more than one xpi. note also that xpis installed with this method must have their own install.js files in which the full installation is defined. ...
InstallTrigger - Web APIs
ither case, you must trigger the installation process by creating a web page script in which installtrigger methods download the specified xpi file and "trigger" the execution of the install.js script at the top level of that xpi. the principal method on the installtrigger object is install, which downloads and installs one or more software packages archived in the xpi file format. the following is a basic example of an install trigger on a web page: xpi={'xpinstall dialog display name':'simple.xpi'}; installtrigger.install(xpi); you can also use the installtrigger object to install netscape 6/mozilla skins and language packs, and perform multiple-package installations with install. compareversion compares the version of a file or package with th...
IntersectionObserver.IntersectionObserver() - Web APIs
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 a callback). you can provide any combination of the following options: root an element or document object which is an ancestor of the intended target, whose bounding rectangle will be considered the viewport. any part of the target not visible in the visible area of the root is not considered visible. rootmargin a string which specifies a set of offsets to add to the root's bounding_box when calculating intersections, effectively shrinking or g...
IntersectionObserver.observe() - Web APIs
g with those. to stop observing the element, call intersectionobserver.unobserve(). when the visibility of the specified element crosses over one of the observer's visibility thresholds (as listed in intersectionobserver.thresholds), the observer's callback is executed with an array of intersectionobserverentry objects representing the intersection changes which occurred. note that this design allows multiple elements' intersection changes to be processed by a single call to the callback. syntax intersectionobserver.observe(targetelement); parameters targetelement an element whose visibility within the root is to be monitored. this element must be a descendant of the root element (or contained wtihin the current document, if the root is the document's viewport). return value undefi...
InterventionReportBody - Web APIs
the interventionreportbody interface of the reporting api represents the body of an intervention report (the return value of its report.body property). an intervention report is generated when usage of a feature in a web document has been blocked by the browser for reasons such as security, performance, or user annoyance. so for example, a script was been stopped because it was significantly slowing down the browser, or the browser's autoplay policy blocked audio from playing without a user gesture to trigger it. properties id a string representing the intervention that generated the report. this can be used to group reports by deprecated feature. message a string containing a human-readable description of the intervention, including information such how the intervention could be a...
Keyboard.getLayoutMap() - Web APIs
the getlayoutmap() method of the keyboard interface returns a promise that resolves with an instance of keyboardlayoutmap which is a map-like object with functions for retrieving the strings associated with specific physical keys. syntax var promise = keyboard.getlayoutmap() parameters none. return value a promise that resolves with an instance of keyboardlayoutmap. example the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard. var keyboard = navigator.keyboard; keyboard.getlayoutmap() .then(keyboardlayoutmap => { var upkey = keyboardlayoutmap.get('keyw'); window.alert('press ' + upkey + ' to move up.'); }) specifications specification status...
Keyboard.lock() - Web APIs
Web › API › Keyboard › lock
re keys that are granted access by the underlying operating system. syntax var promise = keyboard.lock([keycodes[]]) parameters keycodes optional an array of one or more key codes to lock. if no keycodes are provided all keys will be locked. 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 ...
Keyboard - Web APIs
Web › API › Keyboard
solves with an instance of keyboardlayoutmap which is a map-like object with functions for retrieving the strings associated with specific physical keys. keyboard.lock() returns a promise after enabling the capture of keypresses for any or all of the keys on the physical keyboard. keyboard.unlock() unlocks all keys captured by the lock() method and returns synchronously. example the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard. if (navigator.keyboard) { var keyboard = navigator.keyboard; keyboard.getlayoutmap() .then(keyboardlayoutmap => { var upkey = keyboardlayoutmap.get('keyw'); window.alert('press ' + upkey + ' to move up.'); }); } else { ...
KeyboardEvent() - Web APIs
"code", optional and defaulting to "", of type domstring, that sets the value of keyboardevent.code. ...
KeyboardEvent.charCode - Web APIs
ode read-only property of the keyboardevent interface returns the unicode value of a character key pressed during a keypress event. do not use this property, as it is deprecated. use the key property instead. syntax var code = event.charcode; return value a number that represents the unicode value of the character key that was pressed. ...
KeyboardEvent.initKeyEvent() - Web APIs
cument.getelementbyid('blah').dispatchevent(event); specification this implementation of keyboard events is based on the key events spec in the early versions of dom 2 events, later removed from that spec. ...
KeyboardLayoutMap.get() - Web APIs
the get() method of the keyboardlayoutmap interface returns the element with the given key. a list of valid keys is found in the ui events keyboardevent code values spec. syntax var value = keyboardlayoutmap.get(key) parameters key the key of the item to return from the map. return value the value of the specified key. example the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard. var keyboard = navigator.keyboard; keyboard.getlayoutmap() .then(keyboardlayoutmap => { var upkey = keyboardlayoutmap.get('keyw'); window.alert('press ' + upkey + ' to move up.'); } specifications specification status comment keyboard mapthe defin...
KeyboardLayoutMap - Web APIs
layoutmap object. methods keyboardlayoutmap.foreach() read only executes a provided function once for each element of keyboardlayoutmap. keyboardlayoutmap.get() returns the element with the given key from the keyboardlayoutmap object. keyboardlayoutmap.has() returns a boolean indicating whether the keyboardlayoutmap object has an element with the specified key. examples the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard. var keyboard = navigator.keyboard; keyboard.getlayoutmap() .then(keyboardlayoutmap => { var upkey = keyboardlayoutmap.get('keyw'); window.alert('press ' + upkey + ' to move up.'); }) specifications specification status...
KeyframeEffect.getKeyframes() - Web APIs
offset the offset of the keyframe specified as a number between 0.0 and 1.0 inclusive or null. ...
KeyframeEffect.target - Web APIs
t 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. ...
LayoutShift - Web APIs
of viewport). layoutshift.hadrecentinput returns true if there was a user input in the past 500 milliseconds. layoutshift.lastinputtime returns the time of the most recent user input. layoutshift.sources returns an array of layoutshiftattribution objects with information on the elements that were shifted. methods layoutshift.tojson() converts the properties to json. examples the following example shows how to capture layout shifts and log them to the console. note that in this example data is only sent to the server when the user leaves the tab. // catch errors since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let cumulativelayoutshiftscore = 0; const observer = new performanceobserver((list) => { for (c...
LinearAccelerationSensor.LinearAccelerationSensor() - Web APIs
thout the contribution of gravity. 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. syntax var linearaccelerationsensor = new linearaccelerationsensor([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called. a whole number or decimal may be used, the latter for frequencies less than a second. the actual reading frequency depends on device hardware and consequently may be less than requested. referenceframe: either 'device' or 'screen'. the de...
LinearAccelerationSensor.x - Web APIs
cks 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. syntax var xlinearaccelerationsensor = linearaccelerationsensor.x value a number. example linear acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let lasensor = new linearaccelerationsensor({frequency: 60}); lasensor.addeventlistener('reading', e => { console.log("linear acceleration along the x-axis " + lasensor.x); console.log("linear acceleration along the y-axis " + lasensor.y); console.log("linear acceleration along the z-axis " + lasensor.z); }); lasensor.start(); specifications sp...
LinearAccelerationSensor.y - 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. syntax var yacceleration = accelerometer.y value a number. example linear acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let lasensor = new linearaccelerationsensor({frequency: 60}); lasensor.addeventlistener('reading', e => { console.log("linear acceleration along the x-axis " + lasensor.x); console.log("linear acceleration along the y-axis " + lasensor.y); console.log("linear acceleration along the z-axis " + lasensor.z); }); lasensor.start(); specifications sp...
LinearAccelerationSensor.z - 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. syntax var zacceleration = accelerometer.z value a number. example linear acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let lasensor = new linearaccelerationsensor({frequency: 60}); lasensor.addeventlistener('reading', e => { console.log("linear acceleration along the x-axis " + lasensor.x); console.log("linear acceleration along the y-axis " + lasensor.y); console.log("linear acceleration along the z-axis " + lasensor.z); }); lasensor.start(); specifications sp...
LinearAccelerationSensor - Web APIs
along the device's x axis. linearaccelerationsensor.y read only returns a double containing the linear acceleration of the device along the device's y axis. linearaccelerationsensor.z read only returns a double containing the linear acceleration of the device along the device's z axis. example linear acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let lasensor = new linearaccelerationsensor({frequency: 60}); lasensor.addeventlistener('reading', e => { console.log("linear acceleration along the x-axis " + lasensor.x); console.log("linear acceleration along the y-axis " + lasensor.y); console.log("linear acceleration along the z-axis " + lasensor.z); }); lasensor.start(); specifications sp...
Location: hash - Web APIs
Web › API › Location › hash
the fragment is not percent-decoded. if the url does not have a fragment identifier, this property contains an empty string, "". ...
Location: href - Web APIs
Web › API › Location › href
setting the value of href navigates to the provided url. if you want redirection, use location.replace(). ...
Location: pathname - Web APIs
Web › API › Location › pathname
the pathname property of the location interface is a usvstring containing an initial '/' followed by the path of the url (or the empty string if there is no path). syntax string = object.pathname; object.pathname = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/docs/location.pathname"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.pathname; // returns:'/docs/location.pathname' specifications specification status comment html living standardthe definition of 'pathname' in that specification. living standard initial definition. ...
Location: search - Web APIs
Web › API › Location › search
modern browsers provide urlsearchparams and url.searchparams to make it easy to parse out the parameters from the querystring. ...
Locks.mode - Web APIs
Web › API › Lock › mode
lockmanager is the object returned by navigator.locks. ...
Locks.name - Web APIs
Web › API › Lock › name
me is selected by the developer to represent an abstract resource for which use is being coordinated across multiple tabs, workers, or other code within the origin. for example, if only one tab of a web application should be synchronizing network resources with an offline database, it could use a lock name such as "net_db_sync". syntax var name = lock.name value a domstring. example the following examples show how the name property passed in the call to lockmanager.request(). lockmanager is the object returned by navigator.locks. navigator.locks.request("net_db_sync", show_lock_properties); function show_lock_properties(lock) { console.log(`the lock name is: ${lock.name}`); console.log(`the lock mode is: ${lock.mode}`); } specifications specification status comm...
Lock - Web APIs
Web › API › Lock
nd mode of a previously requested lock, which is received in the callback to lockmanager.request(). properties lock.mode read only returns the access mode passed to lockmanager.request() when the lock was requested. the mode is either "exclusive" (the default) or "shared". lock.name read only returns the name passed to lockmanager.request() when the lock was requested. examples the following examples show how the mode and name properties are passed in the call to lockmanager.request(). lockmanager is the object returned by navigator.locks. navigator.locks.request("net_db_sync", show_lock_properties); navigator.locks.request("another_lock", {mode: "shared"}, show_lock_properties); function show_lock_properties(lock) { console.log(`the lock name is: ${lock.name}`); console.log...
LockManager.query() - Web APIs
Web › API › LockManager › query
held: an array of lock objects for held locks. pending: an array of lock objects for pending lock requests. ...
LockedFile.active - Web APIs
Web › API › LockedFile › active
if the object is inactive then it is impossible to perform any read or write operation with it. ...
LockedFile.flush() - Web APIs
Web › API › LockedFile › flush
rds 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. summary the flush method is used to ensure any change made to a file is properly written on disk. for performance reasons, a lockedfile object buffers all its operation in memory. this allows fast writing and reading operations. periodically, the data are written onto disk. however, if something goes wrong before that, some operations can be lost. to avoid that, it's possible to force a write onto the disk by calling the flush method. syntax var request = instanceoflockedfile.flush(); return a filerequest object to handle the success or failure of the operation. specifications ...
Long Tasks API - Web APIs
ong other issues: delayed "time to interactive". high/variable input latency. high/variable event handling latency. janky animations and scrolling. concepts some key terms or ideas that are utilized by the long tasks api. long task any uninterrupted period where the main ui thread is busy for 50 ms or longer. common examples include: long running event handlers. expensive reflows and other re-renders. work the browser does between different turns of the event loop that exceeds 50 ms. culprit browsing context container the "culprit browsing context container", or "the container" for short, is the top level page, iframe, embed or object that the task occurred within. attributions a list of containers that the task occurred within. for tasks that don't occur within th...
MSCandidateWindowUpdate - Web APIs
nguages. syntax event property object.oncandidatewindowupdate = handler; addeventlistener method object.addeventlistener("mscandidatewindowupdate", handler, usecapture) parameters pevtobj [in] type: ihtmleventobj pointer to an ihtmleventobj interface for the current event. tan ime candidate window may be identified as needing to change size for any of the following reasons: as a result of displaying new / changed alternatives or predictions web applications need only register for this event once per element (the handler will remain valid for the lifetime of the element). see also microsoft api extensions ime handling guide for gecko ...
MSGraphicsTrust - Web APIs
hange in the future. the msgraphicstrust() constructor returns an object that provides properties for info on protected video playback. this proprietary method is specific to internet explorer and microsoft edge. syntax var trustobject = media.msgraphicstruststatus; parameters constrictionactive a read-only property which returns true when protected media is forced to play in a lower resolution. status a read-only property which returns an enum with the driver status when playing protected content. inheritance hierarchy the msgraphicstrust does not inherit from any class or interface. example var trustobject = media.msgraphicstruststatus; ...
Magnetometer.Magnetometer() - Web APIs
ld as detected by a device’s primary magnetometer sensor. 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. syntax var magnetometer = new magnetometer([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called. a whole number or decimal may be used, the latter for frequencies less than a second. the actual reading frequency depends on device hardware and consequently may be less than requested. referenceframe: either 'device' or 'screen'. the de...
Magnetometer.x - Web APIs
Web › API › Magnetometer › x
is. 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. syntax var magnetometerx = magnetometer.x value a number. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let magsensor = new magnetometer({frequency: 60}); magsensor.addeventlistener('reading', e => { console.log("magnetic field along the x-axis " + magsensor.x); console.log("magnetic field along the y-axis " + magsensor.y); console.log("magnetic field along the z-axis " + magsensor.z); }); magsensor.start(); specifications specification status...
Magnetometer.y - Web APIs
Web › API › Magnetometer › y
is. 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. syntax var magnetometery = magnetometer.x value a number. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let magsensor = new magnetometer({frequency: 60}); magsensor.addeventlistener('reading', e => { console.log("magnetic field along the x-axis " + magsensor.x); console.log("magnetic field along the y-axis " + magsensor.y); console.log("magnetic field along the z-axis " + magsensor.z); }); magsensor.start(); specifications specification status...
Magnetometer.z - Web APIs
Web › API › Magnetometer › z
. 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. syntax var magnetometerz = magnetometer.z value a number. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let magsensor = new magnetometer({frequency: 60}); magsensor.addeventlistener('reading', e => { console.log("magnetic field along the x-axis " + magsensor.x); console.log("magnetic field along the y-axis " + magsensor.y); console.log("magnetic field along the z-axis " + magsensor.z); }); magsensor.start(); specifications specification status...
Magnetometer - Web APIs
r.x read only returns a double containing the magnetic field around the device's x axis. magnetometer.y read only returns a double containing the magnetic field around the device's y axis. magnetometer.z read only returns a double containing the magnetic field around the device's z axis. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. let magsensor = new magnetometer({frequency: 60}); magsensor.addeventlistener('reading', e => { console.log("magnetic field along the x-axis " + magsensor.x); console.log("magnetic field along the y-axis " + magsensor.y); console.log("magnetic field along the z-axis " + magsensor.z); }); magsensor.start(); specifications specification status...
MediaConfiguration - Web APIs
to file or media-source. if the media is an audio file, the audio configuration must include a valid audio mime type as contenttype, the number of channels, the bitrate, and the sample rate. video configurations mush include a valid video mime type as contenttype, the bitrate, and framerate, along with the width and the height of the video file. all of these must be present, as in the examples below, or a typeerror will occur. a valid media decoding configuration, to be submitted as the parameter for mediacapabilities.decodinginfo() method, has it's `type` set as: file: for plain playback file. media-source: for media source files. a valid media encoding configuration, to be submitted as the parameter for mediacapabilities.encodinginfo() method, has it's `type` set as: ...
MediaDevices.getSupportedConstraints() - Web APIs
traints(); parameters none. return value a new object based on the mediatracksupportedconstraints dictionary listing the constraints supported by the user agent. because only constraints supported by the user agent are included in the list, each of these boolean properties has the value true. example this example outputs a list of the constraints supported by your browser. ...
MediaDevices - Web APIs
; }) .catch(function(error) { if (error.name === 'constraintnotsatisfiederror') { errormsg('the resolution ' + constraints.video.width.exact + 'x' + constraints.video.height.exact + ' px is not supported by your device.'); } else if (error.name === 'permissiondeniederror') { errormsg('permissions have not been granted to use your camera and ' + 'microphone, you need to allow the page access to your devices in ' + 'order for the demo to work.'); } errormsg('getusermedia error: ' + error.name, error); }); function errormsg(msg, error) { errorelement.innerhtml += '<p>' + msg + '</p>'; if (typeof error !== 'undefined') { console.error(error); } } specifications specification status comment media capture and streamsthe de...
MediaError.code - Web APIs
Web › API › MediaError › code
the read-only property mediaerror.code returns a numeric value which represents the kind of error that occurred on a media element. to get a text string with specific diagnostic information, see mediaerror.message. syntax var myerror = mediaerror.code; value a numeric value indicating the general type of error which occurred. the possible values are described below, in media error code constants. media error code constants 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 hav...
MediaError.message - Web APIs
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 specification. living standard initial definition ...
MediaError - Web APIs
lement based on htmlmediaelement, such as <audio> or <video>. a mediaerror object describes the error in general terms using a numeric code categorizing the kind of error, and a message, which provides specific diagnostics about what went wrong. properties this interface doesn't inherit any properties. mediaerror.code a number which represents the general type of error that occurred, as follows: 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 determin...
MediaKeyMessageEvent() - Web APIs
the mediakeymessageevent constructor creates a new mediakeymessageevent object which creates a new instance of mediakeymessageevent. syntax var mediakeymessageevent = new mediakeymessageevent(typearg, options) parameters typearg a domstring containing one of may be one of license-request, license-renewal, license-renewal, or individualization-request. options options are as follows: messagetype: a developer-defined message type that allows applications to differentiate messages without parsing them. message: an array containing the message generated by the content decryption module. 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-com...
MediaKeyMessageEvent - Web APIs
the mediakeymessageevent interface of the encryptedmediaextensions api contains the content and related data when the content decryption module generates a message for the session. ...
MediaKeySession.onkeystatuseschange - Web APIs
operty of the mediakeysession is an event handler, fired whenever a keystatuschange event ocurrs, denoting there has been a change in the keys or their statuses within a session. this interface inherits from the extendableevent interface. ...
MediaKeySession.onmessage - Web APIs
the onmessage property of the mediakeysession is an event handler, fired whenever a mediakeymessageevent occurs, denoting a message is generated by the content decryption module. this interface inherits from the extendableevent interface. ...
MediaMetadata - Web APIs
constructor mediametadata.mediametadata() creates a new mediametadata object. properties mediametadata.title returns or sets the title of the media to be played. mediametadata.artist returns or sets the name of the artist, group, creator, etc. of the media to be played. mediametadata.album returns or sets the name of the album or collection containing the media to be played. mediametadata.artwork returns or sets an array of images associated with playing media. ...
MediaPositionState.playbackRate - Web APIs
. syntax let positionstate = { playbackrate: rate }; let playbackrate = positionstate.playbackrate; value a floating-point value specifying a multiplier corresponding to the current relative rate at which the media being performed is playing. a value of 1.0 indicates the media is playing forward at normal speed, while higher values indicate that the media is being played faster than normal. lower values indicate the media is being played more slowly. negative values can be specified to indicate the media is playing in reverse, with decreasing values then indicating faster and faster reverse playback. note: a value of 0.0 is not permitted. example in this example, an app is updating the browser to let it know that the user has clicked a button causing the playback to shift to a doub...
MediaRecorder() - Web APIs
configuration(s) to use by specifying the codecs parameter. syntax var mediarecorder = new mediarecorder(stream[, options]); parameters stream the mediastream that will be recorded. this source media can come from a stream created using navigator.mediadevices.getusermedia() or from an <audio>, <video> or <canvas> element. options optional a dictionary object that can contain the following properties: mimetype: a mime type specifying the format for the resulting media; you may simply specify the container format (the browser will select its preferred codecs for audio and/or video), or you may use the codecs parameter and/or the profiles parameter to provide detailed information about which codecs to use and how to configure them. applications can check in advance if a mimet...
MediaRecorder: error event - Web APIs
bubbles no cancelable no interface mediarecordererrorevent event handler property onerror for details of the all the possible errors see the documentation for the event handler property: onerror. ...
MediaRecorder.mimeType - Web APIs
nction(stream) { var options = { audiobitspersecond: 128000, videobitspersecond: 2500000, mimetype: 'video/mp4' } var mediarecorder = new mediarecorder(stream,options); m = mediarecorder; m.mimetype; // would return '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...
MediaRecorder.onpause - Web APIs
the pause event is thrown as a result of the mediarecorder.pause() method being invoked. syntax mediarecorder.onpause = function(event) { ... } mediarecorder.addeventlistener('pause', function(event) { ... }) example ... ...
MediaRecorder.onresume - Web APIs
the resume event is thrown as a result of the mediarecorder.resume() method being invoked. syntax mediarecorder.onresume = function(event) { ... } mediarecorder.addeventlistener('resume', function(event) { ... }) example ... ...
MediaRecorder.onstart - Web APIs
the start event is thrown as a result of the mediarecorder.start() method being invoked. at this point, the data starts being gathered into a blob. syntax mediarecorder.onstart = function(event) { ... } mediarecorder.addeventlistener('start', function(event) { ... }) example ... record.onclick = function() { mediarecorder.start(); console.log("recorder started"); } mediarecorder.onstart = function() { // do something in response to // recording being started } ... ...
MediaRecorder.onstop - Web APIs
the stop event is thrown either as a result of the mediarecorder.stop() method being invoked, or when the media stream being captured ends. in each case, the stop event is preceded by a dataavailable event, making the blob captured up to that point available for you to use in your application. syntax mediarecorder.onstop = function(event) { ... } mediarecorder.addeventlistener('stop', function(event) { ... }) example ... ...
MediaRecorder.onwarning - Web APIs
syntax mediarecorder.onwarning = function(event) { ... } mediarecorder.addeventlistener('warning', function(event) { ... }) example ... ...
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. raise a pause event. syntax mediarecorder.pause() return value undefined. ...
MediaRecorder.requestData() - Web APIs
the mediarecorder.requestdata() method (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 ...
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. raise a resume event. ...
MediaRecorder.state - Web APIs
recording recording has been started and the ua is capturing data. paused recording has been started, then paused, but not yet stopped or resumed. example ... ...
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.error - Web APIs
name property's value may be any exception that makes sense during the handling of media recording, including these specifically identified by the specification. the descriptions here are generic ones; you'll find more specific ones to various scenarios in which they may occur in the corresponding method references. invalidstateerror an operation was attempted in a context in which it isn't allowed, or a request has been made on an object that's deleted or removed. notsupportederror a mediarecorder couldn't be created because the specified options weren't valid. the message atttribute should provide additional information, if it exists. securityerror the mediastream is configured to disallow recording. this may be the case, for example, with sources obtained using getusermedia() when ...
MediaSession.metadata - Web APIs
the metadata has not been set. this metadata is provided by the browser to the device for presentation in any standard media control user interface the device might offer. syntax var mediametadata = navigator.mediasession.metadata; navigator.mediasession.metadata = mediametadata; value an instance of mediametadata containing information about the media currently being played. ...
Media Session action types - Web APIs
for that action. the specific type of media session action to be handled on a mediasession is identified using a string from the mediasessionaction enumerated type. syntax a media session action's type is specified using a string from the mediasessionaction enumerated type. values each of the actions is a common media session control request. implement support for each of these in order to allow that type of action to be performed. the following strings identify the currently available types of media session action: nexttrack advances playback to the next track. pause pauses playback of the media. play begins (or resumes) playback of the media. previoustrack moves back to the previous track. seekbackward seeks backward through the media from the current position. the mediase...
MediaSettingsRange - Web APIs
ht 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 imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const tr...
MediaSource.MediaSource() - Web APIs
the mediasource() constructor of the mediasource interface constructs and returns a new mediasource object with no associated source buffers. syntax var mediasource = new mediasource(); parameters none. ...
MediaSource.activeSourceBuffers - Web APIs
s a sourcebufferlist object containing a subset of the sourcebuffer objects contained within sourcebuffers — the list of objects providing the selected video track, enabled audio tracks, and shown/hidden text tracks. syntax var myactivesourcebuffers = mediasource.activesourcebuffers; value a sourcebufferlist containing the sourcebuffer objects for each of the active tracks. ...
MediaSource.addSourceBuffer() - Web APIs
mimetype isn't supported by the user agent, or is not compatible with the mime types of other sourcebuffer objects that are already included in the media source's sourcebuffers list. quotaexceedederror the user agent can't handle any more sourcebuffer objects, or creating a new sourcebuffer using the given mimetype would result in an unsupported configuration of sourcebuffers. ...
MediaSource.endOfStream() - Web APIs
upt, 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 open, or one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e. ...
MediaSource.isTypeSupported() - Web APIs
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. ...
MediaSource.readyState - Web APIs
three possible values are: closed: the source is not currently attached to a media element. open: the source is attached to a media element and ready to receive sourcebuffer objects. ended: the source is attached to a media element but the stream has been ended via a call to mediasource.endofstream(). syntax var myreadystate = mediasource.readystate; value a domstring. ...
MediaSource.sourceBuffers - Web APIs
the sourcebuffers read-only property of the mediasource interface returns a sourcebufferlist object containing the list of sourcebuffer objects associated with this mediasource. syntax var mysourcebuffers = mediasource.sourcebuffers; value a sourcebufferlist. ...
MediaStream.getVideoTracks() - Web APIs
s no video tracks. note: the order of the tracks is not defined by the specification, and may not be the same from one call to getvideotracks() to another. early versions of this api included a special videostreamtrack interface which was used as the type for each entry in the list of video streams; however, this has since been merged into the main mediastreamtrack interface. example the following example, extracted from chrome's image capture / photo resolution sample, uses getvideotracks() to retrieve a track for passing to the imagecapture() constructor. var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecap...
MediaStreamAudioSourceNode() - Web APIs
working draft ...
MediaStreamConstraints - Web APIs
the mediastreamconstraints dictionary is used when calling getusermedia() to specify what kinds of tracks should be included in the returned mediastream, and, optionally, to establish constraints for those tracks' settings. to learn more about how constraints work, see capabilities, constraints, and settings. properties some combination—but not necessarily all—of the following properties will exist on the object. track constraints audio either a boolean (which indicates whether or not an audio track is requested) or a mediatrackconstraints object providing the constraints which must be met by the audio track included in the returned mediastream. if constraints are specified, an audio track is inherently requested. video either a boolean (which indicates whether or not a video t...
MediaStreamEvent() - Web APIs
the mediastreamevent() constructor creates a new mediastreamevent. syntax var event = new mediastreamevent(type, mediastreameventinit); values type is a domstring containing the name of the event, like addstream or removestream. mediastreameventinit is a mediastreameventinit dictionary, having the following fields: "stream" of type mediastream representing the stream being concerned by the event. "bubbles", optional and defaulting to false, inherited from eventinit, and indicating if the event must bubble or not. "cancelable", optional and defaulting to false, inherited from eventinit, and indicating if the event can be canceled or not. example // s is a mediastream var event = new mediastreamevent("addstream", {"stream": s}); ...
MediaStreamTrack.enabled - Web APIs
this can be used to intentionally mute a track. when enabled, a track's data is output from the source to the destination; otherwise, empty frames are output. in the case of audio, a disabled track generates frames of silence (that is, frames in which every sample's value is 0). for video tracks, every frame is filled entirely with black pixels. ...
MediaStreamTrack.getConstraints() - Web APIs
rack using a prior call to applyconstraints(). these constraints indicate values and ranges of values that the web site or application has specified are required or acceptable for the included constrainable properties. constraints can be used to ensure that the media meets certain guidelines you prefer. for example, you may prefer high definition video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network. constraints can also specify ideal and/or acceptable sizes or ranges of sizes. see capabilities, constraints, and settings for details on how to work with constrainable properties. syntax const constraints = track.getconstraints() return value a mediatrackconstraints object which indicates the constrainable properties the web site...
MediaStreamTrack.kind - Web APIs
the mediastreamtrack.kind read-only property returns a domstring set to "audio" if the track is an audio track and to "video", if it is a video track. it doesn't change if the track is deassociated from its source. syntax const type = track.kind value the possible values are a domstring with on of the following values: "audio": the track is an audio track. "video": the track is a video track. specifications specification status comment media capture and streamsthe definition of 'mediastreamtrack.kind' in that specification. candidate recommendation initial specification. ...
MediaStreamTrack.readyState - Web APIs
in that case, the output of data can be switched on or off using the mediastreamtrack.enabled property. "ended" which indicates that the input is not giving any more data and will never provide new data. ...
MediaStreamTrack.remote - Web APIs
the mediastreamtrack.remote read-only property allows javascript to know whether a webrtc mediastreamtrack is from a remote source or a local one. it returns a boolean with a value of true if the track is sourced remotely (that is, sourced by an rtcpeerconnection), or false if it is sourced locally. syntax var bool ​= track.remote; ...
MediaStreamTrackAudioSourceNode() - Web APIs
working draft ...
MediaStreamTrackAudioSourceOptions.mediaStreamTrack - Web APIs
working draft ...
MediaStreamTrackEvent - Web APIs
ediastreamtrackevent interface represents events which indicate that a mediastream has had tracks added to or removed from the stream through calls to media stream api methods. these events are sent to the stream when these changes occur. ...
MediaTrackConstraints.cursor - Web APIs
cksettings 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 be provided and insert a fake representation of the cursor at the correct position. examples here are some example constraints objects for getdisplaymedia() that make use of the cursor property. ...
MediaTrackConstraints.displaySurface - Web APIs
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 ...
MediaTrackConstraints.facingMode - Web APIs
) facing modes are acceptable for a video track. an exact value in this case indicates that the specified facing mode is specifically required; for example: var constraints = { facingmode: { exact: "user" } }; this indicates that only a user-facing camera is acceptable; if there is no user-facing camera, or the user declines permission to use that camera, the media request will fail. the following strings are permitted values for the facing mode. these may represent separate cameras, or they may represent directions in which an adjustable camera can be pointed. "user" the video source is facing toward the user; this includes, for example, the front-facing camera on a smartphone. "environment" the video source is facing away from the user, thereby viewing their environment. this is...
MediaTrackConstraints.latency - Web APIs
straint; value a constraindouble describing the acceptable or required value(s) for an audio track's latency, with values specified in seconds. in audio processing, latency is the time between the start of processing (when sound occurs in the real world, or is generated by a hardware device) and the data being made available to the next step in the audio input or output process. in most cases, low latency is desirable for performance and user experience purposes, but when power consumption is a concern, or delays are otherwise acceptable, higher latency might be 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...
MediaTrackSettings.cursor - Web APIs
the mediatracksettings dictionary's cursor property indicates whether or not the cursor should be captured as part of the video track included in the mediastream returned by getdisplaymedia(). syntax cursorsetting = mediatracksettings.cursor; value the value of cursor comes from the cursorcaptureconstraint enumerated string type, and may have one of the following values: always the mouse should always be visible in the video content of the {domxref("mediastream"), unless the mouse has moved outside the area of the content. motion the mouse cursor should always be included in the video if it's moving, and for a short time after it stops moving. never the mouse cursor is never included in the shared video. specifications specification status comment scree...
MediaTrackSettings.displaySurface - Web APIs
the mediatracksettings dictionary's displaysurface property indicates the type of display surface being captured. syntax displaysurface = mediatracksettings.displaysurface; value the value of displaysurface is a string that comes from the displaycapturesurfacetype enumerated type, and is one of the following: application the stream's video track contains all of the windows belonging to the application chosen by the user. the windows are aggragated into a single video track, with any empty space filled with a backdrop; that backdrop is selected by the user agent. browser the stream's video track presents the entire contents of a single browser tab which the user selected during the getdisplaymedia() call. monitor the video track in the stream presents the complete contents of one ...
MediaTrackSettings.facingMode - Web APIs
ypically 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 never include this property. syntax var facingmode = mediatracksettings.facingmode; value a domstring whose value is one of the strings in videofacingmodeenum. videofacingmodeenum the following strings are permitted values for the facing mode. these may represent separate cameras, or they may represent directions in which an adjustable camera can be pointed. "user" the video source is facing toward the user; this includes, for example, the front-facing camera on a smartphone. "environment" the video source is facing away from the user, thereby viewing their environment. this is...
MediaTrackSettings.logicalSurface - Web APIs
ea of a window which is too large to display onscreen at once. since the window that contains the surface has to be scrolled to show the rest of the contents, the surface is a logical one. a visible display surface (that is, a surface for which logicalsurface returns false) is the portion of a logical display surface which is currently visible onscreen. for example, a user agent may choose to allow the user to choose whether to share the entire document (a browser with logicalsurface value of true), or just the currently visible portion of the document (where the logicalsurface of the browser surface is false). specifications specification status comment screen capturethe definition of 'mediatracksettings.logicalsurface' in that specification. working draft i...
MediaTrackSettings.sampleRate - Web APIs
h. syntax var samplerate = mediatracksettings.samplerate; value an integer value indicating how many samples each second of audio data includes. common values include 44,100 (standard cd audio), 48,000 (standard digital audio), 96,000 (commonly used in audio mastering and post-production), and 192,000 (used for high-resolution audio in professional recording and mastering sessions). however, lower values are often used to reduce bandwidth requirements; 8,000 samples per second is adequate for comprehensible albeit imperfect human speech, and both 11,025 fps and 22,050 fps are often used for low-bandwidth, reduced quality sound and music. example see example: constraint exerciser in capabilities, constraints, and settings for an example. specifications specification status...
MediaTrackSupportedConstraints.displaySurface - Web APIs
dconstraints(). syntax isdisplaysurfacesupported = supportedconstraints.displaysurface; value a boolean value which is true if the displaysurface constraint is supported by the device and user agent. example this method sets up the constraints object specifying the options for the call to getdisplaymedia(). it adds the displaysurface constraint (requesting that only full-screen sharing be allowed) only if it is known to be supported by the browser. capturing is then started by calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem. async function capture() { let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); let displaymediaoptions = { video: { }, audio: false; }; if (supported...
Media Capture and Streams API (Media Stream) - Web APIs
streams api specification included separate audiostreamtrack and videostreamtrack interfaces—each based upon mediastreamtrack—which represented streams of those types. these no longer exist, and you should update any existing code to instead use mediastreamtrack directly. events addtrack ended muted overconstrained removetrack started unmuted guides and tutorials the articles below provide additional guidance and how-to information that will help you learn to use the api, and how to perform specific tasks that you may wish to handle. capabilities, constraints, and settingsthe twin concepts of constraints and capabilities let the browser and web site or app exchange information about what constrainable properties the browser's implementation supports and what valu...
MerchantValidationEvent() - Web APIs
d not have to create these events yourself; instead, just handle the merchantvalidation event. syntax merchantvalidationevent = new merchantvalidationevent(type, options); parameters type a domstring which must be merchantvalidation, the only type of event which uses the merchantvalidationevent interface. options optional an optional dictionary which may contain zero or more of the following properties: methodname optional a domstring containing the payment method identifier for the payment handler being used. this is an empty string by default. validationurl optional the url from which to retrieve payment handler specific verification information used to validate the merchant. this is an empty string by default. return value a newly-created merchantvalidationeve...
MerchantValidationEvent - Web APIs
to learn more about merchant validation, see merchant validation in payment processing concepts. constructor merchantvalidationevent() secure context creates a new merchantvalidationevent object describing a merchantvalidation event that will be sent to the payment handler to request that it validate the merchant. properties merchantvalidationevent.methodname secure context a domstring providing a unique payment method identifier for the payment handler that's requiring validation. ...
MessageChannel() - Web APIs
the messagechannel() constructor of the messagechannel interface returns a new messagechannel object with two new messageport objects. note: this feature is available in web workers. syntax var channel = new messagechannel(); returns a newly created messagechannel object. example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check when the message arrives. var channel = new messagechannel(); var para = document.queryselec...
MessageChannel.port1 - Web APIs
the port1 read-only property of the messagechannel interface returns the first port of the message channel — the port attached to the context that originated the channel. note: this feature is available in web workers. syntax channel.port1; value a messageport object, the first port of the channel, that is the port attached to the context that originated the channel. example in the following code block, you can see a new channel being created using the messagechannel() constructor. when the <iframe> has loaded, we pass messagechannel.port2 to the <iframe> using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the <iframe> (using messageport.onmessage), putting it into a paragraph. the handlemessage method is asso...
MessageChannel.port2 - Web APIs
interface returns the second port of the message channel — the port attached to the context at the other end of the channel, which the message is initially sent to. note: this feature is available in web workers. syntax channel.port2; value a messageport object representing the second port of the channel, the port attached to the context at the other end of the channel. example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, t...
MessageChannel - Web APIs
the messagechannel interface of the channel messaging api allows us to create a new message channel and send data through it via its two messageport properties. note: this feature is available in web workers. properties messagechannel.port1 read only returns port1 of the channel. messagechannel.port2 read only returns port2 of the channel. constructor messagechannel() returns a new messagechannel object with two new messageport objects. example in the following example, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message. when a message i...
MessageEvent.MessageEvent() - Web APIs
this can be of any data type, and will default to null if not specified. ...
MessagePort.close() - Web APIs
Web › API › MessagePort › close
the close() method of the messageport interface disconnects the port, so it is no longer active. this stops the flow of messages to that port. note: this feature is available in web workers. syntax port.close() returns void. parameters none. example in the following code block, you can see a handlemessage handler function, run when a message is sent back to this document using eventtarget.addeventlistener. channel.port1.addeventlistener('message', handlemessage, false); function handlemessage(e) { para.innerhtml = e.data; textinput.value = ''; } channel.port1.start(); you could stop messages being sent at any time using channel.port1.close(); specifications specification status comment html living standardthe definition of 'close()' in that specifi...
MessagePort.onmessage - Web APIs
the onmessage event handler of the messageport interface is an eventlistener, called whenever an messageevent of type message is fired on the port — that is, when the port receives a message. note: this feature is available in web workers. syntax channel.onmessage = function() { ... }; example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass messagechannel.port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives. var channel = new messagechannel(); var para = d...
MessagePort.postMessage() - Web APIs
; returns void. parameters message the message you want to send through the channel. this can be of any basic data type. multiple data items can be sent as an array. transferlist optional transferable objects to be transferred — these objects have their ownership transferred to the receiving browsing context, so are no longer usable by the sending browsing context. example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass messagechannel.port2 to the iframe using window.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to...
Microsoft API extensions - Web APIs
playtodisabled msplaytopreferredsourceuri msplaytoprimary msplaytosource msrealtime mssetmediaprotectionmanager mssetvideorectangle msstereo3dpackingmode msstereo3drendermode onmsvideoformatchanged onmsvideoframestepcompleted onmsvideooptimallayoutchanged msfirstpaint pinned sites apis mssitemodeevent mssitemodejumplistitemremoved msthumbnailclick other apis x-ms-aria-flowfrom x-ms-acceleratorkey x-ms-format-detection mscaching mscachingenabled mscapslockwarningoff event.msconverturl() mselementresize document.mselementsfromrect() msisstatichtml navigator.mslaunchuri() mslaunchuricallback element.msmatchesselector() msprotocols msputpropertyenabled mswriteprofilermark ...
MimeTypeArray - Web APIs
type instances, each of which contains information about a supported browser plugins. this object is returned by navigatorplugins.mimetypes. properties mimetypearray.length the number of items in the array. methods mimetypearray.item() returns the mimetype object with the specified index. mimetypearray.nameditem() returns the mimetype object with the specified name. example the following example tests whether a plugin is available for the application/pdf mime type and if so, which plugin that is. var mimetypes = navigator.mimetype; var flashplugin = mimetypes['video/x-flv']; if (typeof flashplugin === "undefined") { var vid = document.createelement('video'); // use vid.canplaytype() to test for a supported mime type. } else { // notify the user that flash is being depre...
MouseEvent() - Web APIs
the mouseevent() constructor creates a new mouseevent. syntax event = new mouseevent(typearg, mouseeventinit); values typearg is a domstring representing the name of the event. mouseeventinit optional is a mouseeventinit dictionary, having the following fields: "screenx", optional and defaulting to 0, of type long, that is the horizontal position of the mouse event on the user's screen; setting this value doesn't move the mouse pointer. "screeny", optional and defaulting to 0, of type long, that is the vertical position of the mouse event on the user's screen; setting this value doesn't move the mouse pointer. "clientx", optional and defaulting to 0, of type long, that is the horizontal position of the mouse event on the client window of user's screen; setting ...
MouseEvent.buttons - Web APIs
if more than one button is pressed, the button values are added together to produce a new number. for example, if the secondary (2) and auxilary (4) buttons are pressed simultaneously, the value is 6 (i.e., 2 + 4). note: do not confuse this property with the mouseevent.button property. ...
MouseEvent.initMouseEvent() - Web APIs
e event's mouse button. relatedtarget the event's related eventtarget. only used with some event types (e.g., mouseover and mouseout). in other cases, pass null. ...
MouseEvent.mozInputSource - Web APIs
ty 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 unknown. moz_source_mouse 1 the event was generated by a mouse (or mouse-like device). moz_source_pen 2 the event was generated by a pen on a tablet. moz_source_eraser 3 the event was generated by an eraser on a tablet. ...
MouseEvent.relatedTarget - Web APIs
mple try moving your mouse cursor into and out of the red and blue boxes. ...
msFirstPaint - Web APIs
. syntax p = object.msfirstpaint; value an integer value that represents the time when the document began to be displayed or 0 if the document could not be loaded. the 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; ...
msPlayToPreferredSourceUri - Web APIs
msplaytopreferredsourceuri enables a playto reference (a uri or url) for streaming content 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" msplaytopreferredsourceu...
MutationObserver.MutationObserver() - Web APIs
bserver = new mutationobserver(callback) parameters callback a function which will be called on each dom change that qualifies given the observed node or subtree and options. the callback function takes as input two parameters: an array of mutationrecord objects, describing each change that occurred; and the mutationobserver which invoked the callback. see the example below for more details. return value a new mutationobserver object, configured to call the specified callback when dom mutations occur. example this example simply creates a new mutationobserver configured to watch a node and all of its children for additions and removals of elements to the tree, as well as any changes to attributes on any of the elements in the tree. the callback function fun...
MutationObserver - Web APIs
observer to begin receiving notifications through its callback function when dom changes matching the given options occur. takerecords() removes all pending notifications from the mutationobserver's notification queue and returns them in a new array of mutationrecord objects. mutation observer & customize resize event listener & demo https://codepen.io/webgeeker/full/yjrzgg/ example the following example was adapted from this blog post. // select the node that will be observed for mutations const targetnode = document.getelementbyid('some-id'); // options for the observer (which mutations to observe) const config = { attributes: true, childlist: true, subtree: true }; // callback function to execute when mutations are observed const callback = function(mutationslist, observer) { ...
NDEFReader - Web APIs
he web nfc api is an abstract interface used to read data from compatible nfc devices, e.g. nfc tags supporting ndef, when these devices are within the reader's magnetic induction field. constructor ndefreader.ndefreader() returns an ndefreader with configuration specified in the parameters or default ones if no parameters are specified. properties in addition to the properties listed below, ndefreader inherits properties from its parent interface, eventtarget. ndefreader.onreading an event handler for reading event, that notifies about availability of a new reading. ndefreader.onerror an event handler for error event which is called to notify that an error occured during reading. methods the ndefreader interface inherits the methods of eventtarget, its parent interface...
NDEFRecord.encoding - Web APIs
the encoding property ofthe ndefrecord interface is usvstring containing the name of the encoding used to encode ndef payload if it contains textual data. syntax ndefrecord.encoding value a usvstring which can be one of the following: "utf-8", "utf-16", "utf-16le" or "utf-16be". specifications specification status comment web nfc, ndefrecord.encoding draft initial definition. ...
NDEFRecord.recordType - Web APIs
"text" represents a text ndef record. "url" represents an uri ndef record. "smart-poster" represents a "smart poster" ndef record. "absolute-url" represents an absolute url ndef record. "mime" represents a mime type ndef record. "unknown" represents an unknown ndef record. ...
NavigationPreloadManager - Web APIs
and the contents of the service-worker-navigation-preload. examples feature detecting and enabling navigation preloading addeventlistener('activate', event => { event.waituntil(async function() { if (self.registration.navigationpreload) { // enable navigation preloads! await self.registration.navigationpreload.enable(); } }()); }); using a preloaded response the following example shows the implementation of a fetch event that uses a preloaded response. addeventlistener('fetch', event => { event.respondwith(async function() { // respond from the cache if we can const cachedresponse = await caches.match(event.request); if (cachedresponse) return cachedresponse; // else, use the preloaded response, if it's there const response = await even...
Navigator.clipboard - Web APIs
on. use of the asynchronous clipboard read and write methods requires that the user grant the web site or app permission to access the clipboard. this permission must be obtained from the permissions api using the "clipboard-read" and/or "clipboard-write" permissions. syntax theclipboard = navigator.clipboard; value the clipboard object used to access the system clipboard. examples the following code uses navigator.clipboard to access the system clipboard in order to read the contents of the clipboard. navigator.clipboard.readtext().then( cliptext => document.queryselector(".cliptext").innertext = cliptext); this snippet replaces the contents of the element whose class is "cliptext" with the text contents of the clipboard. perhaps this code is being used in a browser extension tha...
Navigator.connection - Web APIs
the navigator.connection read-only property returns a networkinformation object containing information about the system's connection, such as the current bandwidth of the user's device or whether the connection is metered. this could be used to select high definition content or low definition content based on the user's connection. syntax networkinformation = navigator.connection value a networkinformation object. specifications specification status comment network information apithe definition of 'navigator.connection' in that specification. draft initial specification ...
Navigator.cookieEnabled - Web APIs
he browser is configured to block third-party cookies, and navigator.cookieenabled is invoked inside a third-party iframe, it returns true in safari, edge spartan and ie (while trying to set a cookie in such scenario would fail). it returns false in firefox and chromium-based browsers. note: web browsers may prevent writing certain cookies in certain scenarios. for example, chrome 80+ does not allow creating cookies with samesite=none attribute, unless they are created over https and with secure attribute. example if (!navigator.cookieenabled) { // the browser does not support or is blocking cookies from being set. } specifications specification status comment html living standardthe definition of 'navigator.cookieenabled' in that specification. living s...
Navigator.deviceMemory - Web APIs
the devicememory read-only property of the navigator interface returns the approximate amount of device memory in gigabytes. the reported value is imprecise to curtail fingerprinting. it’s approximated by rounding down to the nearest power of 2, then dividing that number by 1024. it is then clamped within lower and upper bounds to protect the privacy of owners of very low- or high-memory devices. syntax memoryamount = navigator.devicememory value a floating point number; one of 0.25, 0.5, 1, 2, 4, 8. example const memory = navigator.devicememory console.log (`this device has at least ${memory}gib of ram.`) specifications specification status comment device memory 1the definition of 'devicememory' in that specification. editor's draft i...
Navigator.geolocation - Web APIs
note: for security reasons, when a 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. ...
Navigator.mozIsLocallyAvailable() - Web APIs
the navigator.mozislocallyavailable() method allows add-ons to determine whether or not a given resource is available. 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. example var available = navigator.mozislocallyavailable("my-image-file.png", true); if (available) { /* the offline resource is present */ } else { console.log("certain needed resources are not available offline"); } specifications not part of any specifications. ...
msSaveBlob - Web APIs
syntax navigator.mssaveblob(blob, defaultname); parameters blob a blob to be saved. defaultname the file name to be used when saving file. return value true is returned as long as the download notification bar is displayed, or false if a failure occured. notes when a site calls this method, the behavior is the same as when windows internet explorer downloads a file with the following in the header, where x-download-options removes the file open button from the browser file download dialog: content-length: <blob.size> content-type: <blob.type> content-disposition: attachment;filename=<defaultname> x-download-options: noopen specifications not part of any specifications. ...
msSaveOrOpenBlob - Web APIs
x navigator.mssaveoropenblob(blob, defaultname); parameters blob a blob to be saved. defaultname the file name to be used when saving file. return value true is returned as long as the download notification bar is displayed, or false if a failure occurred. notes when a site calls this method, the behavior is the same as when windows internet explorer downloads a file with the following in the header: content-length: <blob.size> content-type: <blob.type> content-disposition: attachment;filename=<defaultname> specifications not part of any specifications. ...
Navigator.registerContentHandler() - Web APIs
note: web sites may only register content handlers for themselves. for security reasons, it's not possible for an extension or web site to register content handlers targeting other sites. syntax navigator.registercontenthandler(mimetype, uri, title); mimetype is the desired mime type as a string. uri is the uri to the handler as a string. title is the title of the handler presented to the user as a string. ...
Navigator.share() - Web APIs
Web › API › Navigator › share
available options are: url: a usvstring representing a url to be shared. text: a usvstring representing text to be shared. title: a usvstring representing the title to be shared. files: a " frozenarray" representing the array of file to be shared. ...
Navigator.wakeLock - Web APIs
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. ...
navigator.hardwareConcurrency - Web APIs
, but each physical core is also usually able to run more than one thread at a time using advanced scheduling techniques. so a four-core cpu may offer eight logical processor cores, for example. the number of logical processor cores can be used to measure the number of threads which can effectively be run at once without them having to context switch. the browser may, however, choose to report a lower number of logical cores in order to represent more accurately the number of workers that can run at once, so don't treat this as an absolute measurement of the number of cores in the user's system. examples in this example, one worker is created for each logical processor reported by the browser and a record is created which includes a reference to the new worker as well as a boolean value in...
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. ...
NavigatorID.platform - Web APIs
syntax platform = navigator.platform value a domstring identifying the platform on which the browser is running, or an empty string if the browser declines to (or is unable to) identify the platform. platform is a string that must be an empty string or a string representing the platform on which the browser is executing. ...
NavigatorLanguage.language - Web APIs
urns a string representing the preferred language of the user, usually the language of the browser ui. syntax const lang = navigator.language value a domstring. lang stores a string representing the language version as defined in bcp 47. examples of valid language codes include "en", "en-us", "fr", "fr-fr", "es-es", etc. note that in safari on ios prior to 10.2, the country code returned is lowercase: "en-us", "fr-fr" etc. example if (/^en\b/.test(navigator.language)) { dolangselect(window.navigator.language); } specifications specification status comment html living standardthe definition of 'navigatorlanguage: language' in that specification. living standard initial definition ...
NetworkInformation.downlinkMax - Web APIs
read-only property returns the maximum downlink speed, in megabits per second (mbps), for the underlying connection technology. note: this feature is available in web workers. syntax var max = networkinformation.downlinkmax return value an unrestricted double representing the maximum downlink speed, in megabits per second (mb/s), for the underlying connection technology. examples the following example monitors the connection using the change event and logs changes as they occur. function logconnectiontype() { var connectiontype = 'not supported'; var downlinkmax = 'not supported'; if ('connection' in navigator) { connectiontype = navigator.connection.effectivetype; if ('downlinkmax' in navigator.connection) { downlinkmax = navigator.connection.downlinkmax; ...
NetworkInformation.effectiveType - Web APIs
the effectivetype read-only property of the networkinformation interface 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. syntax var effectivetype = networkinformation.effectivetype value a string containing one of 'slow-2g', '2g', '3g', or '4g'. specifications specification status comment network information apithe definition of 'effectivetype' in that specification. draft initial definition. ...
NetworkInformation.type - Web APIs
the networkinformation.type read-only property returns the type of connection a device is using to communicate with the network. note: this feature is available in web workers. syntax var type = netinfo.type return value an enumerated value that is one of the following values: "bluetooth" "cellular" "ethernet" "none" "wifi" "wimax" "other" "unknown" specifications specification status comment network information apithe definition of 'type' in that specification. draft initial definition ...
Node.baseURI - Web APIs
Web › API › Node › baseURI
simply the location of the document, but it can be affected by many factors, including the <base> element in html and the xml:base attribute in xml. syntax var nodebaseuri = node.baseuri; value a domstring representing the base url of the specified node. it may be null if unable to obtain an absolute uri. although this property is read-only, its value may change in certain situations (see below). details the base url of a document the base url of a document defaults to the document's address (as displayed by the browser and available in window.location), but it can be changed: when an html <base> tag is found in the document when the document is new (created dynamically) see the base urls section of the html living standard for details. you can use document.baseuri to obtain t...
Node.cloneNode() - Web APIs
Web › API › Node › cloneNode
n changed in the latest spec! although deep it still optional, it now defaults to false. you should always provide an explicit value for backward and forward compatibility. with gecko 28.0 (firefox 28 / thunderbird 28 / seamonkey 2.25 / firefox os 1.3)), the console warned developers not to omit the argument. starting with gecko 29.0 (firefox 29 / thunderbird 29 / seamonkey 2.26)), a shallow clone is defaulted instead of a deep clone. example let p = document.getelementbyid("para1") let p_prime = p.clonenode(true) notes cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners. it does not copy event listeners added using addeventlistener() or those assigned to element properties (e.g., node.onclick = somefunction). additionally,...
Node.isConnected - Web APIs
Web › API › Node › isConnected
* no warranty expressed or implied. use at your own risk. */ if (!('isconnected' in node.prototype)) { object.defineproperty(node.prototype, 'isconnected', { get() { return ( !this.ownerdocument || !( th...
Node.nodeType - Web APIs
Web › API › Node › nodeType
ginstruction of an xml document, such as <?xml-stylesheet … ?>. node.comment_node 8 a comment node, such as <!-- … -->. node.document_node 9 a document node. node.document_type_node 10 a documenttype node, such as <!doctype html>. node.document_fragment_node 11 a documentfragment node. deprecated node type constants the following constants have been deprecated and should not be used anymore. constant value description node.attribute_node 2 an attribute of an element. attributes no longer implement the node interface as of dom4. node.entity_reference_node 5 an xml entity reference node, such as &foo;. removed in dom4. node.entity_node 6 an xml <!entity …> n...
Node.nodeValue - Web APIs
Web › API › Node › nodeValue
perty of the node interface returns or sets the value of the current node. syntax str = node.nodevalue; node.nodevalue = str; value str is a string containing the value of the current node, if any. for the document itself, nodevalue returns null. for text, comment, and cdata nodes, nodevalue returns the content of the node. for attribute nodes, the value of the attribute is returned. ...
Node.prefix - Web APIs
Web › API › Node › prefix
<x:div onclick="console.log(this.prefix)"/> notes this will only work when a namespace-aware parser is used, i.e. when a document is served with an xml mime type. this will not work for html documents. ...
Node.removeChild() - Web APIs
Web › API › Node › removeChild
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 handler invoked in the course of trying to remove the element (e.g., blur.) errors thrown the method throws an exception in 2 different ways: if the child was in fact a child of element and so existing on the dom, but was removed the method throws the following exception: uncaught notfounderror: failed to execute 'removechild' on 'node': the node to be removed is not a child of this node. if the child doesn't exist on the dom of the page, the method throws the following exception: uncaught typeerror: failed to execute 'removechild' on 'node': parameter 1 is not of type 'node'. examples simple examples given this html: <div id="...
Node.rootNode - Web APIs
Web › API › Node › rootNode
he node.getrootnode() method. the node.rootnode read-only property returns a node object representing the topmost node in the tree, or the current node if it's the topmost node in the tree. this is found by walking backward along node.parentnode until the top is reached. syntax rootnode = node.rootnode; value a node object representing the topmost node in the tree. example running the following line in supporting browsers should return a reference to the html/document node: console.log(document.body.rootnode); notes gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. therefore a node obtained, for example, using node.firstchild or node.previoussibling may refer to a whitespace text node rather than the actual element the author int...
Node.setUserData() - Web APIs
Web › API › Node › setUserData
note that such data will not be preserved when imported via node.importnode, as with node.clonenode() and node.renamenode() operations (though node.adoptnode does preserve the information), and equality tests in node.isequalnode() do not consider user data in making the assessment. this method offers the convenience of associating data with specific nodes without needing to alter the structure of a document and in a standard fashion, but it also means that extra steps may need to be taken if one wishes to serialize the information or include the information upon clone, import, or rename operations. ...
Node.textContent - Web APIs
Web › API › Node › textContent
ontent gets the content of all elements, including <script> and <style> elements. in contrast, innertext only shows “human-readable” elements. textcontent returns every element in the node. in contrast, innertext is aware of styling and won’t return the text of “hidden” elements. moreover, since innertext takes css styles into account, reading the value of innertext triggers a reflow to ensure up-to-date computed styles. (reflows can be computationally expensive, and thus should be avoided when possible.) unlike textcontent, altering innertext in internet explorer (version 11 and below) removes child nodes from the element and permanently destroys all descendant text nodes. it is impossible to insert the nodes again into any other element or into the same element after ...
NodeIterator - Web APIs
nodeiterator.root read only returns a node representing the root node as specified when the nodeiterator was created. ...
NodeList.entries() - Web APIs
Web › API › NodeList › entries
the values are node objects. syntax list.entries(); return value returns an iterator. ...
NodeList.prototype.forEach() - Web APIs
Web › API › NodeList › forEach
ent.createelement("p"); let kid2 = document.createtextnode("hey"); let kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); let list = node.childnodes; list.foreach( function(currentvalue, currentindex, listobj) { console.log(currentvalue + ', ' + currentindex + ', ' + this); }, 'mythisarg' ); the above code results in the following: [object htmlparagraphelement], 0, mythisarg [object text], 1, mythisarg [object htmlspanelement], 2, mythisarg polyfill this polyfill adds compatibility to all browsers supporting es5: if (window.nodelist && !nodelist.prototype.foreach) { nodelist.prototype.foreach = function (callback, thisarg) { thisarg = thisarg || window; for (var i = 0; i < this.length; i++) { ...
NodeList.keys() - Web APIs
Web › API › NodeList › keys
the keys are unsigned integer. syntax nodelist.keys(); return value returns an iterator. ...
NodeList.values() - Web APIs
Web › API › NodeList › values
the values are node objects. syntax nodelist.values(); return value returns an iterator. ...
NonDocumentTypeChildNode.previousElementSibling - Web APIs
is is a list item</li> <li>this is another list item</li> <div id="div-03">here is div-03</div> <script> let el = document.getelementbyid('div-03').previouselementsibling; document.write('<p>siblings of div-03</p><ol>'); while (el) { document.write('<li>' + el.nodename + '</li>'); el = el.previouselementsibling; } document.write('</ol>'); </script> this example outputs the following into the page when it loads: siblings of div-03 1. li 2. li 3. div 4. div polyfills polyfill for internet explorer 8 this property is unsupported prior to ie9, so the following snippet can be used to add support to ie8: // source: https://github.com/alhadis/snippets/blob/master/js/polyfills/ie8-child-elements.js if(!("previouselementsibling" in document.documentelement)){ ...
NonDocumentTypeChildNode - Web APIs
implemented by element, and characterdata objects. properties there are no inherited properties. nondocumenttypechildnode.previouselementsibling read only returns the element immediately prior to this node in its parent's children list, or null if there is no element in the list prior to this node. nondocumenttypechildnode.nextelementsibling read only returns the element immediately following this node in its parent's children list, or null if there is no element in the list following this node. methods there are neither inherited nor specific methods. specifications specification status comment domthe definition of 'nondocumenttypechildnode' in that specification. living standard splitted the elementtraversal interface in parentnode, childnode, a...
Notification.Notification() - Web APIs
on's language, as specified using a domstring representing a bcp 47 language tag. see the sitepoint iso 2 letter language codes page for a simple reference. badge: a usvstring containing the url of the image used to represent the notification when there isn't enough space to display the notification itself. body: a domstring representing the body text of the notification, which is displayed below the title. tag: a domstring representing an identifying tag for the notification. icon: a usvstring containing the url of an icon to be displayed in the notification. image: a usvstring containing the url of an image to be displayed in the notification. data: arbitrary data that you want associated with the notification. this can be of any data type. vibrate: a vibration pattern for the...
Notification.close() - Web APIs
the notification removed from the screen after a fixed delay since this method will also remove the notification from any notification tray, preventing users from interacting with it after it was initially shown. a valid use for this api would be to remove a notification that is no longer relevant (e.g. the user already read the notification on the webpage in the case of a messaging app or the following song is already playing in a music app). syntax notification.close(); parameters none. returns void. examples in the following snippet, we have a simple function that when called creates an options object and then a new notification. at the end of the function, it also calls close() inside a addeventlistener() function to remove the notification when the relevant content has been read...
Notification.data - Web APIs
Web › API › Notification › data
ure is available in web workers. the data read-only property of the notification interface returns a structured clone of the notification's data, as specified in the data option of the notification() constructor. the notification's data can be any arbitrary data that you want associated with the notification. syntax var data = notification.data; value a structured clone. examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', data: 'i like peas.' } var n = new notification('test notification',options); console.log(n.data) // should return 'i like peas.' specifications specification status comment notifica...
Notification.dir - Web APIs
Web › API › Notification › dir
on of the notification() constructor. syntax var direction = notification.dir; value a domstring specifying the text direction. possible values are: auto: adopts the browser's language setting behaviour (the default.) ltr: left to right. rtl : right to left. note: most browsers seem to ignore explicit ltr and rtl settings, and just go with the browser-wide setting. examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', dir: 'rtl' } var n = new notification('test notification',options); console.log(n.dir) // should return 'rtl' specifications specification status comment notifications apithe defini...
Notification.lang - Web APIs
Web › API › Notification › lang
interface indicates the language used in the notification, as specified in the lang option of the notification() constructor. the language itself is specified using a domstring representing a bcp 47 language tag. see the sitepoint iso 2 letter language codes page for a simple reference. syntax var language = notification.lang; value a domstring specifying the language tag. examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', lang: 'en-us' } var n = new notification('test notification',options); console.log(n.lang) // should return 'en-us' specifications specification status comment notifications apithe d...
Notification.maxActions - Web APIs
maximum number of actions supported by the device and the user agent. effectively, this is the maximum number of elements in notification.actions array which will be respected by the user agent. syntax notification.maxactions value an integer number which indicates the largest number of notification actions that can be presented to the user by the user agent and the device. examples the following snippet logs the maximum number of supported actions. const maxactions = notification.maxactions; console.log('this device can display at most ' + maxactions + ' actions on each notification.'); specifications specification status comment notifications api living standard living standard ...
Notification.onclick - Web APIs
tion interface specifies an event listener to receive click events. these events occur when the user clicks on a displayed notification. syntax notification.onclick = function(event) { ... }; the default behavior is to move the focus to the viewport of the notification's related browsing context. if you don't want that behaviour, call preventdefault() on the event object. ...
Notification.permission - Web APIs
representing the current permission. the value can be: granted: the user has explicitly granted permission for the current origin to display system notifications. denied: the user has explicitly denied permission for the current origin to display system notifications. default: the user decision is unknown; in this case the application will act as if permission was denied. examples the following snippet could be used if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification. function notifyme() { // let's check if the browser supports notifications if (!("notification" in window)) { console.log("this browser do...
Notification.renotify - Web APIs
le in web workers. the renotify read-only property of the notification interface specifies whether the user should be notified after a new notification replaces an old one, as specified in the renotify option of the notification() constructor. syntax var renotify = notification.renotify; value a boolean. false is the default; true makes the notification renotify the user. examples the following snippet is intended to fire a notification that renotifies the user after it has been replaced; a simple options object is created, and then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', renotify: true } var n = new notification('test notification',options); console.log(n.renotify) // should log true specifications ...
Notification.silent - Web APIs
t read-only property of the notification interface specifies whether the notification should be silent, i.e., no sounds or vibrations should be issued, regardless of the device settings. this is specified in the silent option of the notification() constructor. syntax var silent = notification.silent; value a boolean. false is the default; true makes the notification silent. examples the following snippet is intended to fire a silent notification; a simple options object is created, and then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', silent: true } var n = new notification('test notification', options); console.log(n.silent) // should log true specifications specification status comment n...
Notification.timestamp - Web APIs
0: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: 'do you like my body?', timestamp: dts } var n = new notification('test notification',options); console.log(n.timestamp) // should log original timestamp specifications specification ...
Notification.vibrate - Web APIs
ailable in web workers. the vibrate read-only property of the notification interface specifies a a vibration pattern for the device's vibration hardware to emit when the notification fires. this is specified in the vibrate option of the notification() constructor. syntax var vibrate = notification.vibrate; value a vibration pattern, as specified in the vibration api spec. examples the following snippet is intended to create a notification that also triggers a device vibration; a simple options object is created, and then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', vibrate: [200, 100, 200] } var n = new notification('test notification',options); console.log(n.vibrate) // should log [200,100,200] specifications ...
NotificationAction - Web APIs
nly the string describing the action that is displayed to the user. notificationaction.icon read only the url of the image used to represent the notification when there is not enough space to display the notification itself. example notifications can fire notificationclick events on the serviceworkerglobalscope. here a service worker shows a notification with a single "archive" action, allowing users to perform this common task from the notification without having to open the website. the user can also click the main body of the notification to open their inbox instead. self.registration.shownotification("new mail from alice", { actions: [ { action: 'archive', title: 'archive' } ] }); self.addeventlistener('notificationclick', function(event) { event.notif...
NotificationEvent.notification - Web APIs
returns a notification object. ...
OES_standard_derivatives - Web APIs
s available as gl.fragment_shader_derivative_hint and it requires glsl #version 300 es. constants this extension exposes one new constant, which can be used in the hint() and getparameter() methods. ext.fragment_shader_derivative_hint_oes a glenum indicating the accuracy of the derivative calculation for the glsl built-in functions: dfdx, dfdy, and fwidth. ...
OfflineAudioCompletionEvent.OfflineAudioCompletionEvent() - Web APIs
iocompletionevent object instance. note: you wouldn't generally use the constructor manually. offlineaudiocompletionevents are despatched to offlineaudiocontext instances for legacy reasons. syntax var offlineaudiocompletionevent = new offlineaudiocompletionevent(type, init) parameters type optional a domstring representing the type of object to create. init optional options are as follows: renderedbuffer: the rendered audiobuffer containing the audio data. return value a new offlineaudiocompletionevent object instance. specifications specification status comment web audio apithe definition of 'offlineaudiocompletionevent()' in that specification. working draft initial definition. browser compatibility the compatibility table on ...
OfflineAudioContext.resume() - Web APIs
d. the promise resolves immediately because the offlineaudiocontext does not require the audio hardware. if the context is not currently suspended or the rendering has not started, the promise is rejected with invalidstateerror. syntax offlineaudiocontext.resume().then(function() { ... }); parameters none. returns a promise resolving to void. exceptions the promise is rejected when the following exception is encountered. invalidstateerror if the context is not currently suspended or the rendering has not started. specifications specification status comment web audio apithe definition of 'resume()' in that specification. working draft initial definition. ...
OfflineAudioContext - Web APIs
uilt from linked together audionodes. in contrast with a standard audiocontext, an offlineaudiocontext doesn't render the audio to the device hardware; instead, it generates it, as fast as it can, and outputs the result to an audiobuffer. ...
OffscreenCanvas.getContext() - Web APIs
dalpha: boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. preservedrawingbuffer: if the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author. failifmajorperformancecaveat: boolean that indicates if a context will be created if the system performance is low. return value a renderingcontext which is either a canvasrenderingcontext2d for "2d", webglrenderingcontext for "webgl" and "experimental-webgl", webgl2renderingcontext for "webgl2" and "experimental-webgl2" , or imagebitmaprenderingcontext for "bitmaprenderer". if the contexttype doesn't match a possible drawing context, null is returned. examples var offscreen = new offscre...
OffscreenCanvas - Web APIs
ansferfromimagebitmap() with the previously rendered and saved imagebitmap from the offscreencanvas, will display the imagebitmap on the canvas and transfer its ownership to the canvas. a single offscreencanvas may transfer frames into an arbitrary number of other imagebitmaprenderingcontext objects. given these two <canvas> elements <canvas id="one"></canvas> <canvas id="two"></canvas> the following code will provide the rendering using an offscreencanvas as described above. var one = document.getelementbyid("one").getcontext("bitmaprenderer"); var two = document.getelementbyid("two").getcontext("bitmaprenderer"); var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext('webgl'); // ... some drawing for the first canvas using the gl context ... // commit rendering ...
OrientationSensor.populateMatrix() - Web APIs
where: w = cos(θ/2) x = vx * sin(θ/2) y = vy * sin(θ/2) z = vz * sin(θ/2) 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. ...
OscillatorNode.detune - Web APIs
the detune property of the oscillatornode interface is an a-rate audioparam representing detuning of oscillation in cents. syntax var 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.frequen...
OscillatorNode.frequency - Web APIs
e frequency property of the oscillatornode interface is an a-rate audioparam representing the frequency of oscillation in hertz. syntax 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.
OscillatorNode.onended - Web APIs
for an applied example, check out our violent theremin demo (see app.js for relevant code). ...
OscillatorNode.setPeriodicWave() - Web APIs
used to point to a periodicwave defining a periodic waveform that can be used to shape the oscillator's output, when type is custom. this replaces the now-obsolete oscillatornode.setwavetable(). syntax oscillatornode.setperiodicwave(wave); parameters wave a periodicwave object representing the waveform to use as the shape of the oscillator's output. returns undefined example the following example illustrates simple usage of createperiodicwave(), recreating a sine wave from a periodic wave. var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); var osc = ac.createoscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createperiodicwave(real, imag); osc.setperiodicwave(wave); osc.connect(ac.destination); osc.sta...
OscillatorNode.start() - Web APIs
x oscillator.start(when); // start playing oscillator at the point in time specified by when parameters when optional an optional 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.
OscillatorNode.stop() - Web APIs
ameter is optional and defaults to 0. syntax oscillator.stop(when); // stop playing oscillator at when parameters when optional 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); oscilla...
OscillatorNode.type - Web APIs
gle wave. custom a custom waveform. you never set type to custom manually; instead, use the setperiodicwave() method to provide the 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.
PageTransitionEvent - Web APIs
the pagetransitionevent event object is available inside handler functions for the pageshow and pagehide events, fired when a document is being loaded or unloaded. ...
PaintWorklet.registerPaint - Web APIs
expects a file. syntax registerpaint(name, class); parameters name the name of the worklet class to register. class a reference to the class that implements the worklet. return value undefined exceptions typeerror thrown when one of the arguments is invalid or missing. invalidmodificationerror thrown when the a worklet already exists with the specified name. examples the following shows registering an example worklet module. this should be in a separate js file. note that registerpaint() is called without a reference to paintworklet. the file itself is loaded through css.paintworklet.addmodule() (documented here on the parent class of paintworklet, at worklet.addmodule(). /* checkboardworklet.js */ class checkerboardpainter { paint(ctx, geom, properties) { // us...
PannerNode.PannerNode() - Web APIs
onx: the pannernode.orientationx you want the pannernode to have (the default is 1.) orientationy: the pannernode.orientationy you want the pannernode to have (the default is 0.) orientationz: the pannernode.orientationz you want the pannernode to have (the default is 0.) refdistance: the pannernode.refdistance you want the pannernode to have. the default is 1, and negative values are not allowed. maxdistance: the pannernode.maxdistance you want the pannernode to have. the default is 10000, and non-positive values are not allowed. rollofffactor: the pannernode.rollofffactor you want the pannernode to have. the default is 1, and negative values are not allowed. coneinnerangle: the pannernode.coneinnerangle you want the pannernode to have (the default is 360.) coneouterangle: the ...
PannerNode.distanceModel - Web APIs
xponential: 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. syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.distancemodel = 'inverse'; value a enum — see distancemodeltype. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
PannerNode.maxDistance - Web APIs
ximum distance between the audio source and the listener, after which the volume is not reduced any further. this value is used only by the linear distance model. the maxdistance property's default value is 10000. syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.maxdistance = 10000; value a double. the default is 10000, and non-positive values are not allowed. exceptions rangeerror the property has been given a value that is outside the accepted range. 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 listener and panner (source) occupy initially, and then upd...
PannerNode.panningModel - Web APIs
hm, 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. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
PannerNode.positionX - Web APIs
ned by this property is read only; however, you can still change the value of the parameter by assigning a new value to its audioparam.value property. syntax var positionx = pannernode.positionx; pannernode.positionx.value = newpositionx; value an audioparam whose value is the x coordinate of the audio source's position, in 3d cartesian coordinates. the default value is 0. example the following example starts an oscillator, and pans it to the left after 1 second, to the right after 2 seconds, and back to the center after 3 seconds. const context = new audiocontext(); const osc = new oscillatornode(context); const panner = new pannernode(context); panner.positionx.setvalueattime(-1, context.currenttime + 1); panner.positionx.setvalueattime(1, context.currenttime + 2); panner.positi...
PannerNode.positionY - Web APIs
. the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a new value to its audioparam.value property. syntax var positiony = pannernode.positiony; pannernode.positiony.value = newpositiony; value an audioparam whose value is the y coordinate of the audio source's position, in 3d cartesian coordinates. example the following example starts an oscillator and pans it above the listener after 1 second, below the listener after 2 seconds, and back to the center after 3 seconds. note that in this case, the change will mainly affect the timbre of the oscillator, as it's a simple mono wave. const context = new audiocontext(); const osc = new oscillatornode(context); const panner = new pannernode(context); panner.pann...
PannerNode.positionZ - Web APIs
. the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a new value to its audioparam.value property. syntax var positionz = pannernode.positionz; pannernode.positionz.value = newpositionz; value an audioparam whose value is the z coordinate of the audio source's position, in 3d cartesian coordinates. example the following example starts an oscillator and moves it in front of the listener after 1 second, behind the listener after 2 seconds, and back to the listener's position after 3 seconds. note that in this case, the change will mainly affect the timbre and perceived volume of the sound. const context = new audiocontext(); const osc = new oscillatornode(context); const panner = new pannernode(context); pa...
PannerNode.refDistance - Web APIs
schedule the ramp panner.positionz.setvalueattime(0, starttime); panner.positionz.linearramptovalueattime(z_distance, starttime + note_length); osc.connect(panner) .connect(context.destination); osc.start(starttime); osc.stop(starttime + note_length); }; // this tone should decay immediately and fairly quickly scheduletesttone(1, context.currenttime); // this tone should decay slower and later than the previous one scheduletesttone(4, context.currenttime + note_length); // this tone should decay only slightly, and only start decaying fairly late scheduletesttone(7, context.currenttime + note_length * 2); after running this code, the resulting waveforms should look something like this: specifications specification status comment web audio apithe ...
PannerNode.setOrientation() - Web APIs
ay from the listener can be very quiet or even silent. the three parameters x, y and z are unitless and describe a direction vector in 3d space using the right-hand cartesian coordinate system. the default value of the direction vector is (1, 0, 0). syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.setorientation(1,0,0); returns void. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
PannerNode.setPosition() - Web APIs
n the audiocontext.listener attribute.) the three parameters x, y and z are unitless and describe the source's position in 3d space using the right-hand cartesian coordinate system. the setposition() method's default value of the position is (0, 0, 0). syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.setposition(0,0,0); returns void. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
PannerNode.setVelocity() - Web APIs
conform with the doppler effect due to the relative speed. as the vector controls both the direction of travel and its velocity, the three parameters x, y and z are expressed in meters per second. the default value of the velocity vector is (0, 0, 0). syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.setvelocity(0,0,17); returns void. 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 listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
PannerNode - Web APIs
nernode.setvelocity() defines the velocity vector of the audio source — how fast it is moving and in what direction. in a previous version of the specification, the pannernode had a velocity that could pitch up or down audiobuffersourcenodes connected downstream. this feature was not clearly specified and had a number of issues, so it was removed from the specification. examples in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a character around inside a game world...
ParentNode.lastElementChild - Web APIs
ementchild moved to parentnode. this is a fairly technical change that shouldn't affect compatibility. syntax const element = node.lastelementchild example <ul id="foo"> <li>first (1)</li> <li>second (2)</li> <li>third (3)</li> </ul> <script> const foo = document.getelementbyid('foo'); console.log(foo.lastelementchild.textcontent); // logs: third (3) </script> polyfill the code below adds support of lastelementchild() to document and documentfragment in internet explorer and safari. // overwrites native 'lastelementchild' prototype. // returns array instead of htmlcollection. ;(function(constructor) { if(constructor && constructor.prototype && constructor.prototype.lastelementchild == null) { object.defineproperty(constructor.prototype, 'lastelementchild', { ...
PasswordCredential - Web APIs
the passwordcredential constructor creates a new passwordcredential object. in supporting browsers, an instance of this class may be passed the credential from the init object for global fetch. syntax var mycredential = new passwordcredential(passwordcredentialdata) var mycredential = new passwordcredential(htmlformelement) parameters either of the following: passwordcredentialdata a passwordcredentialdata dictionary containing the following fields: iconurl: (optional) the url of a user's avatar image. id: the id of the user signing in. name: (optional) the name of the user signing in. password: the password of the user signing in. htmlformelement a reference to an htmlformelement with appropriate input fields. the form should, at the very least, contain an id and ...
PasswordCredential.additionalData - Web APIs
ta in the objects will be added to the request body and sent to the remote endpoint with the credentials. syntax passwordcredential.additionaldata = formdata formdata = passwordcredential.additionaldata passwordcredential.additionaldata = urlsearchparams ulrsearchparams = passwordcredential.additionaldata value one of a formdata instance, a urlsearchparams instance, or null. example the following example creates a formdata object with an appended csrf token. it then stores the form object in the additionaldata parameter, before sending it to server in a call to fetch. //the options object was previously created. navigator.credentials.get(options).then(function(creds) { if (creds.type == 'password') { var form = new formdata(); var csrf_token = document.queryselector('csrf_to...
PaymentAddress.addressLine - Web APIs
properties of paymentaddress. these lines may include the street name, house number, apartment number, rural delivery route, descriptive instructions, or post office box. syntax var paymentaddresslines = paymentaddress.addressline; value an array of domstring objects, each containing one line of the address. ...
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". ...
PaymentDetailsBase - Web APIs
entdetailsmodifier objects, each describing a modifier for particular payment method identifiers. for example, you can use one to adjust the total payment amount based on the selected payment method ("5% cash discount!"). shippingoptionsoptional an array of paymentshippingoption objects, each describing one available shipping option from which the user may choose. derived dictionaries the following dictionaries include paymentdetailsbase. paymentdetailsinit provides payment information when calling the paymentrequest() constructor. paymentdetailsupdate provides updated payment details while the payment user interface is being handled. this can be delivered to the payment interface using either paymentdetailsupdateevent.updatewith() or by returning it from the optional detailsupdate...
PaymentDetailsUpdate.error - Web APIs
des an error message to be displayed if the specified information doesn't offer any valid shipping options. syntax errorstring = paymentdetailsupdate.error; paymentdetailsupdate.error = errorstring; value a domstring specifying the string to display to the user if the information specified in the paymentdetailsupdate doesn't provide any valid shipping options. this happens if both of the following are true: the paymentrequest specifies using its requestshipping property that shipping information is required. the paymentdetailsupdate object specifies no valid shipping options in its shippingoptions list. this message can be used to explain to the user why they cannot submit their payment as currently specified—whether that's because the selected products cannot be shipped to thei...
PaymentDetailsUpdate - Web APIs
with() method or by using the paymentrequest.show() method's detailspromise parameter to provide a promise that returns a paymentdetailsupdate that updates the payment information before the user interface is even enabled for the first time. properties the paymentdetailsupdate dictionary is based on the paymentdetailsbase dictionary, and inherits its properties, which are included in the list below. displayitems optional an array of paymentitem objects, each describing one line item for the payment request. these represent the line items on a receipt or invoice. error optional a domstring specifying an error message to present to the user. when calling updatewith(), including error in the updated data causes the user agent to display the text as a general error message. for address f...
PaymentMethodChangeEvent - Web APIs
bout a paymentmethodchange event. syntax paymentmethodchangeevent = new paymentmethodchangeevent(type, options); parameters type a domstring which must contain the string paymentmethodchange, the name of the only type of event which uses the paymentmethodchangeevent interface. options optional an optional paymentmethodchangeeventinit dictionary which may contain zero or more of the following properties: methodname optional a domstring containing the payment method identifier for the payment handler being used. this is an empty string by default. methoddetails optional an object providing payment method-specific information describing the changes made to the payment, or null if there is no additional information available or required. this is null by default. retur...
PaymentMethodChangeEvent - Web APIs
s fired by some payment handlers when the user switches payment instruments (e.g., a user selects a "store" card to make a purchase while using apple pay). constructor paymentmethodchangeevent() creates and returns a new paymentmethodchangeevent object, optionally initialized with values taken from a given paymentmethodchangeeventinit dictionary. properties in addition to the properties below, this interface includes properties inherited from paymentrequestupdateevent. methoddetails read only secure context an object containing payment method-specific data useful when handling a payment method change. if no such information is available, this value is null. methodname read only secure context a domstring containing the payment method identifier, a string which uniquely identif...
PaymentRequest.abort() - Web APIs
the paymentrequest.abort() method of the paymentrequest interface causes the user agent to end the payment request and to remove any user interface that might be shown. syntax paymentrequest.abort(); returns void. parameters none examples the following example sets up a timeout to clear the payment request that might have been abandoned or neglected. var request = new paymentrequest(supportedinstruments, details, options); var paymenttimeout = window.settimeout(() => { window.cleartimeout(paymenttimeout); request.abort().then(() => { print('payment timed out after 20 minutes.'); }).catch(() => { print('unable to abort, because the user is currently in the process ' + 'of paying.'); }); }, 20 * 60 * 1000); /* 20 minutes */ specifications spe...
PaymentRequest.canMakePayment() - Web APIs
eturns a promise to a boolean that resolves to true if the user agent supports any of the payment methods supplied when instantiating the request using the paymentrequest constructor. if the payment can't be processed, the promise receives a value of false. note: if you call this too often, the browser may reject the returned promise with a domexception. parameters none examples in the following example, is excerpted from a demo that asynchronously builds a paymentrequest object for both apple pay and credit cards. it wraps the call to canmakepayment() in feature detection, and calls an appropriate callback depending on the resolution of the promise. async function initpaymentrquest() { const details = { total: { label: "total", amount: { currency: "usd", ...
PaymentRequest.onmerchantvalidation - Web APIs
chant validate themselves. this event is not be fired by all payment handlers. in particular, it's used by apple pay. syntax paymentrequest.onmerchantvalidation = eventhandlerfunction; value an event handler function which is to be called whenever the merchantvalidation event is fired at the paymentrequest, indicating that the payment handler requires the merchant to validate themselves as allowed to use this payment handler. examples an example merchant validation handler for the paymentrequest object request looks like this: request.onmerchantvalidation = ev => { ev.complete(async () => { const merchantserverurl = window.location.origin + '/validation?url=' + encodeuricomponent(ev.validationurl); // get validation data, and complete validation; return await fet...
PaymentRequest.onpaymentmethodchange - Web APIs
within the same payment handler. the paymentmethodchange event is triggered by a user-agent controlled interaction (i.e., the end-user switches from a debit to a credit card in the payment ui). to make sure you receive the event, you should add event listeners to paymentrequest object after instantiation, but before you call show(). examples an example payment method change handler is shown below; this example handles changes made to the payment method when using apple pay, specifically: request.onpaymentmethodchange = ev => { const { type: cardtype } = ev.methoddetails; const newstuff = {}; if (ev.methodname === "https://apple.com/apple-pay") { switch (cardtype) { case "store": // do apple pay specific handling for store card... // methoddetails contains ...
PaymentRequest.shippingAddress - Web APIs
d-only property of the paymentrequest interface returns the shipping address provided by the user. it is null by default. syntax var paymentaddress = paymentrequest.shippingaddress; example generally, the user agent will fill the shippingaddress property value. you can trigger this by setting paymentoptions.requestshipping to true when calling the paymentrequest constructor. in the example below, the cost of shipping varies by geography. when the paymentrequest.onshippingaddresschange is called, updatedetails() is called to update the details of the paymentrequest, using shippingaddress to set the correct shipping cost. // initialization of paymentrequest arguments are excerpted for the sake of // brevity. var payment = new paymentrequest(supportedinstruments, details, options); paym...
PaymentRequest.shippingOption - Web APIs
g options are provided. this attribute is only populated if the constructor is called with the requestshipping flag set to true. if requestshipping was false (or missing), shippingoption returns null, even the developer provides a selected a shipping option. syntax // returns the id of the selected paymentshippingoption var shippingoption = request.shippingoption; example in the example below, the paymentrequest.onshippingoptionchange and the paymentrequest.onshippingaoptionchange events are dispatched. in each calls to updatedetails() are made, one using a promise, and the other with a plain js object. this demotrates synchrounous and asynchronous updates to a payment sheet. const request = new paymentrequest(methoddata, details, options); // async update to details request.onship...
PaymentRequestEvent() - Web APIs
the paymentrequestevent constructor creates a new paymentrequestevent object which is a constructor for a paymentrequestevent which is the object passed to a payment handler when a paymentrequest is made.. syntax var paymentrequestevent = new paymentrequesteventy(type, options) parameters type must always be 'paymentrequest'. options optional options are as follows: instrumentkey: a paymentinstrument object reflecting the payment instrument selected by the user or an empty string if the user has not registered or chosen a payment instrument. methoddata: an array of paymentmethoddata objects containing payment method identifers for the payment methods that the web site accepts and any associated payment method specific data. modifiers: an array of objects containing change...
PaymentRequestEvent.respondWith() - Web APIs
syntax paymentrequestevent.respondwith( // promise that resolves with a paymentresponse. ) parameters promise a promise that resolves with a paymentresponse object. return value a paymentresponse object. ...
PaymentRequestEvent - Web APIs
in where the paymentrequest object was initialized. totalread only returns the total amount being requested for payment. methods openwindow() opens the specified url in a new window, if and only if the given url is on the same origin as the calling page. it returns a promise that resolves with a reference to a windowclient. respondwith() prevents the default event handling and allows you to provide a promise for a paymentresponse object yourself. specifications specification status comment payment handler apithe definition of 'paymentrequestevent' in that specification. working draft initial definition. ...
PaymentRequestUpdateEvent - Web APIs
pping option. also available using the onshippingoptionchange event handler property. constructor 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 ...
PaymentResponse.details - Web APIs
turns a json-serializable object that provides a payment method specific message used by the merchant to process the transaction and determine a successful funds transfer. 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(). in a real-world implementation this data would then be sent to a payment server. payment.show().then(paymentresponse => { var paymentdata = { // payment method string method: paymentresponse.methodname, // payment details as you requested details: paymentresponse.
PaymentResponse.methodName - Web APIs
l used by the payment handler to process payments. syntax var methodname = paymentresponse.methodname; value a domstring uniquely identifying the payment handler being used to process the payment. this may be either a standardized identifier, or a url used by the payment processor to handle payments. see merchant validation in payment processing concepts for more information. example the following example extracts the method name from the paymentresponse object to the promise returned from paymentrequest.show(). in a real-world implementation this data would then be sent to a payment server. payment.show().then(paymentresponse => { var paymentdata = { // payment method string method: paymentresponse.methodname, // payment details as you requested details: paymentrespo...
PaymentResponse.onpayerdetailchange - Web APIs
e paymentresponse when the user makes changes to their personal information while filling out a payment request form. syntax paymentresponse.onpayerdetailchange = eventhandlerfunction; value an event handler function which is called to handle the payerdetailchange event when the user makes changes to their personal information while editing a payment request form. examples in the example below, onpayerdetailchange is used to set up a listener for the payerdetailchange event in order to validate the information entered by the user, requesting that any mistakes be corrected // options for paymentrequest(), indicating that shipping address, // payer email address, name, and phone number all be collected. const options = { requestshipping: true, requestpayeremail: true, requestpaye...
PaymentResponse: payerdetailchange event - Web APIs
sure that the values are valid. if any are invalid, appropriate error messages should be configured and the retry() method should be called on the paymentresponse to ask the user to update the invalid entries. bubbles no cancelable no interface paymentrequestupdateevent event handler property onpayerdetailchange examples in the example below, onpayerdetailchange is used to set up a listener for the payerdetailchange event in order to validate the information entered by the user, requesting that any mistakes be corrected // options for paymentrequest(), indicating that shipping address, // payer email address, name, and phone number all be collected. const options = { requestshipping: true, requestpayeremail: true, requestpaye...
PaymentResponse.shippingAddress - Web APIs
d by the user. syntax var shippingaddress = paymentrequest.shippingaddress; value a paymentaddress object providing details comprising the shipping address provided by the user. example generally, the user agent will fill the shippingaddress property for you. you can trigger this by setting paymentoptions.requestshipping to true when calling the paymentrequest constructor. in the example below, the cost of shipping varies by geography. when the paymentrequest.onshippingaddresschange is called, updatedetails() is called to update the details of the paymentrequest, using shippingaddress to set the correct shipping cost. // initialization of paymentrequest arguments are excerpted for brevity. var payment = new paymentrequest(supportedinstruments, details, options); request.addeventlist...
PaymentResponse.shippingOption - Web APIs
the shippingoption read-only property of the paymentrequest interface returns the id attribute of the shipping option selected by the user. this option is only present when the requestshipping option is set to true in the paymentoptions object passed to the paymentrequest constructor. syntax var shippingoption = paymentrequest.shippingoption; example in the example below, the paymentrequest.onshippingaoptionchange event is called. it calls updatedetails() to toggle the shipping method between "standard" and "express". // initialization of paymentrequest arguments are excerpted for brevity. var payment = new paymentrequest(supportedinstruments, details, options); request.addeventlistener('shippingoptionchange', function(evt) { evt.updatewith(new promise(function(resolve, reject) { ...
Pbkdf2Params - Web APIs
on'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.derivekey(). specifications specifica...
performance.clearMarks() - Web APIs
of "mark" will be removed from the performance entry buffer. note: this feature is available in web workers. syntax performance.clearmarks(); performance.clearmarks(name); arguments name optional a domstring representing the name of the timestamp. if this argument is omitted, all performance entries with an entry type of "mark" will be removed. return value void example the following example shows both uses of the clearmarks() method. // create a small helper to show how many performancemark entries there are. function logmarkcount() { console.log( "found this many entries: " + performance.getentriesbytype("mark").length ); } // create a bunch of marks. performance.mark("squirrel"); performance.mark("squirrel"); performance.mark("monkey"); performance.mark("monke...
performance.clearMeasures() - Web APIs
will be removed from the performance entry buffer. note: this feature is available in web workers. syntax performance.clearmeasures(); performance.clearmeasures(name); arguments name optional a domstring representing the name of the timestamp. if this argument is omitted, all performance entries with an entry type of "measure" will be removed. return value void example the following example shows both uses of the clearmeasures() method. // create a small helper to show how many performancemeasure entries there are. function logmeasurecount() { console.log( "found this many entries: " + performance.getentriesbytype("measure").length ); } // create a bunch of measures. performance.measure("from navigation"); performance.mark("a"); performance.measure("from mark a"...
performance.mark() - Web APIs
Web › API › Performance › mark
triesbyname() 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 entries. const allentries = performance.getentriesbytype("mark"); console.log(allentri...
Performance.onresourcetimingbufferfull - Web APIs
l 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. 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 ...
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. 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); sp...
Performance - Web APIs
related information for the current page. it's part of the high resolution time api, but is enhanced by the performance timeline api, the navigation timing api, the user timing api, and the resource timing api. 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. 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 tim...
PerformanceEntry.duration - Web APIs
erformance 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 performance entries via the mark() method performance.mark("begin"); do_work(50000); performance.mark("end"); // use getentries() to iterate th...
PerformanceEntry.startTime - Web APIs
r 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.mark("begin"); do_work(50000); performance.mark("end"); // use getentries() to iterate t...
PerformanceEntry.toJSON() - Web APIs
the tojson() method is a serializer; it returns a json representation of the performance entry object. note: this feature is available in web workers. syntax json = perfentry.tojson(); arguments none return value json a json object that is the serialization of the performanceentry object. example the following example shows the use of the tojson() method. 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("begin"); do_work(50000); performance.mark("end"); // use getentries() to iterate through the each entry var p = performance.getentries(); for (var i=0; i <...
PerformanceLongTaskTiming - Web APIs
the performancelongtasktiming interface of the the long tasks api reports instances of long tasks. ...
PerformanceNavigation.type - Web APIs
d in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancenavigation.type read-only property returns an unsigned short containing a constant describing how the navigation to this page was done. possible values are: value constant name meaning 0 type_navigate the page was accessed by following a link, a bookmark, a form submission, a script, or typing the url in the address bar. 1 type_reload the page was accessed by clicking the reload button or via the location.reload() method. 2 type_back_forward the page was accessed by navigating into the history. 255 type_reserved any other way. syntax type = performancenavigation.type; spe...
PerformanceNavigation - Web APIs
current document was done. an object of this type can be obtained by calling the performance.navigation read-only attribute. properties the performancenavigation interface doesn't inherit any properties. performancenavigation.type read only an unsigned short which indicates how the navigation to this page was done. possible values are: type_navigate (0) the page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the url in the address bar. type_reload (1) the page was accessed by clicking the reload button or via the location.reload() method. type_back_forward (2) the page was accessed by navigating into the history. type_reserved (255) any other way. performancenavigation.redirectcount read only an unsigned short re...
PerformanceNavigationTiming.domComplete - Web APIs
eturns 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 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. function print_nav_timing_data() { // use getentriesbytype() to just get the "navigation" events var perfentries = 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 = " +...
PerformanceNavigationTiming.domContentLoadedEventEnd - Web APIs
the domcontentloadedeventend read-only property returns a timestamp representing 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. function print_nav_timing_data() { // use getentriesbytype() to just get the "navigation" events var perfentries = 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 = " +...
PerformanceNavigationTiming.domContentLoadedEventStart - Web APIs
ly property returns a timestamp representing the time value equal to the 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. function print_nav_timing_data() { // use getentriesbytype() to just get the "navigation" events var perfentries = 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 = " +...
PerformanceNavigationTiming.domInteractive - Web APIs
mestamp 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. function print_nav_timing_data() { // use getentriesbytype() to just get the "navigation" events var perfentries = 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 = " +...
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. function print_nav_timing_data() { // use getentriesbytype() to just get the "navigation" events var perfentries = 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 comple...
PerformanceNavigationTiming.loadEventStart - Web APIs
the loadeventstart read-only property 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. function print_nav_timing_data() { // use getentriesbytype() to just get the "navigation" events var perfentries = 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.domcontentloadedevent...
PerformanceNavigationTiming.redirectCount - Web APIs
the redirectcount property returns a timestamp representing 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. function print_nav_timing_data() { // use getentriesbytype() to just get the "navigation" events var perfentries = 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.domconte...
PerformanceNavigationTiming.type - Web APIs
the type read-only property returns a string representing the type of navigation. the value must be one of the following: navigate navigation started by clicking a link, entering the url in the browser's address bar, form submission, or initializing through a script operation other than reload and back_forward as listed below. reload navigation is through the 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. function print_nav_timing_data() { // use gete...
PerformanceNavigationTiming.unloadEventEnd - Web APIs
representing the time value equal to the time immediately after the user 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. function print_nav_timing_data() { // use getentriesbytype() to just get the "navigation" events var perfentries = 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 = " +...
PerformanceNavigationTiming.unloadEventStart - Web APIs
epresenting the time value equal to the time immediately before the user 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. function print_nav_timing_data() { // use getentriesbytype() to just get the "navigation" events var perfentries = 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 = " +...
PerformanceObserver.observe() - Web APIs
omstring objects, each naming one entry type; the type names are documented in performance entry type names in performanceentry.entrytype. when a matching performance entry is recorded, the performance observer's callback function—set when creating the performanceobserver—is invoked. syntax observer.observe(options); parameters options a performanceobserverinit dictionary with the following possible members: entrytypes: an array of domstring objects, each specifying one performance entry type to observe. may not be used together with the "type" or "buffered" options. type: a single domstring specifying exactly one performance entry type to observe. may not be used together with the entrytypes option. buffered: a boolean flag to indicate whether buffered entries should b...
PerformanceObserverEntryList.getEntries() - Web APIs
meter in the callback). this method is exposed to window and worker interfaces. syntax general syntax: entries = list.getentries(); entries = list.getentries(performanceentryfilteroptions); specific usage: entries = list.getentries({name: "entry_name", entrytype: "mark"}); parameters performanceentryfilteroptionsoptional is a performanceentryfilteroptions dictionary, having the following fields: "name", the name of a performance entry. "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. re...
PerformanceResourceTiming.connectEnd - Web APIs
to the server to retrieve the resource. the timestamp value includes the time interval to establish the transport connection, as well as other time intervals such as ssl handshake and socks authentication. note: this feature is available in web workers. syntax resource.connectend; return value a domhighrestimestamp representing the time after a connection is established. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_start_and_end_properties(p[i]); } } function print_start_and_end_properties(perfentry) { // print...
PerformanceResourceTiming.connectStart - Web APIs
tart read-only property returns the timestamp immediately before the user agent starts establishing the connection to the server to retrieve the resource. note: this feature is available in web workers. syntax resource.connectstart; return value a domhighrestimestamp immediately before the browser starts to establish the connection to the server to retrieve the resource. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_start_and_end_properties(p[i]); } } function print_start_and_end_properties(perfentry) { // print...
PerformanceResourceTiming.decodedBodySize - Web APIs
s. if the resource is retrieved from an application cache or local resources, it returns the size of the payload after removing any applied content-codings. note: this feature is available in web workers. syntax resource.decodedbodysize; return value the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings. example the following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the *size properties and print their values // if supported. if ("decodedbodysize" in perfentry) console.log("decodedbodysize = " + perfentry.decodedbodysize); else console.log("decodedbodysize = not supported"); if ("encodedbodysize" in...
PerformanceResourceTiming.domainLookupEnd - Web APIs
formation in cache, domainlookupstart and domainlookupend represent the times when the user agent starts and ends the domain data retrieval from the cache. note: this feature is available in web workers. syntax resource.domainlookupend; return value a domhighrestimestamp representing the time immediately after the browser finishes the domain name lookup for the resource. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_start_and_end_properties(p[i]); } } function print_start_and_end_properties(perfentry) { // print...
PerformanceResourceTiming.domainLookupStart - Web APIs
the domainlookupstart read-only property returns the timestamp immediately before the browser starts the domain name lookup for the resource. note: this feature is available in web workers. syntax resource.domainlookupstart; return value a domhighrestimestamp immediately before the browser starts the domain name lookup for the resource. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_start_and_end_properties(p[i]); } } function print_start_and_end_properties(perfentry) { // print timestamps of the performanceentr...
PerformanceResourceTiming.encodedBodySize - Web APIs
in web workers. if the resource is retrieved from an application cache or a local resource, it must return the size of the payload body before removing any applied content-codings. syntax resource.encodedbodysize; return value a number representing the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. example the following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the performanceentry.*size properties and print their values // if supported. if ("decodedbodysize" in perfentry) console.log("decodedbodysize = " + perfentry.decodedbodysize); else console.log("decodedbodysize = not supported"); if ("en...
PerformanceResourceTiming.fetchStart - Web APIs
tely before the browser starts to fetch the resource. if there are http redirects the property returns the time immediately before the user agent starts to fetch the final resource in the redirection. note: this feature is available in web workers. syntax resource.fetchstart; return value a domhighrestimestamp immediately before the browser starts to fetch the resource. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_start_and_end_properties(p[i]); } } function print_start_and_end_properties(perfentry) { // print...
PerformanceResourceTiming.initiatorType - Web APIs
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. ...
PerformanceResourceTiming.nextHopProtocol - Web APIs
blished, this property returns the alpn protocol id of the tunneled protocol. otherwise, this property returns the alpn protocol id of the first hop to the proxy. note: this feature is available in web workers. syntax resource.nexthopprotocol; return value a string representing the network protocol used to fetch the resource, as identified by the alpn protocol id (rfc7301). example the following example uses the nexthopprotocol property. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_nexthopprotocol(p[i]); } } function print_nexthopprotocol(perfentry) { var value = "nexthopprotocol" in perfentry; if (value) console.log("next...
PerformanceResourceTiming.redirectStart - Web APIs
the redirectstart read-only property returns a timestamp representing the start time of the fetch which that initiates the redirect. if there are http redirects when fetching the resource and if any of the redirects are not from the same origin as the current document, but the timing allow check algorithm passes for each redirected resource, this property returns the starting time of the fetch that initiates the redirect; otherwise, zero is returned. note: this feature is available in web workers. syntax resource.redirectstart; return value a timestamp representing the start time of the fetch which initiates the redirect. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { //...
PerformanceResourceTiming.requestStart - Web APIs
ort connection fails and the browser retires the request, the value returned will be the start of the retry request. there is no end property for requeststart. note: this feature is available in web workers. syntax resource.requeststart; return value a domhighrestimestamp representing the time immediately before the browser starts requesting the resource from the server example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_start_and_end_properties(p[i]); } } function print_start_and_end_properties(perfentry) { // print...
PerformanceResourceTiming.responseEnd - Web APIs
the last byte of the resource or immediately before the transport connection is closed, whichever comes first. note: this feature is available in web workers. syntax resource.responseend; return value a domhighrestimestamp immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_start_and_end_properties(p[i]); } } function print_start_and_end_properties(perfentry) { // print...
PerformanceResourceTiming.responseStart - Web APIs
the responsestart read-only property returns a timestamp immediately after the browser receives the first byte of the response from the server, cache, or local resource. note: this feature is available in web workers. syntax resource.responsestart; return value a domhighrestimestamp immediately after the browser receives the first byte of the response from the server. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_start_and_end_properties(p[i]); } } function print_start_and_end_properties(perfentry) { // print t...
PerformanceResourceTiming.secureConnectionStart - Web APIs
is not used, the property returns zero. note: this feature is available in web workers. syntax resource.secureconnectionstart; return value if the resource is fetched over a secure connection, a domhighrestimestamp immediately before the browser starts the handshake process to secure the current connection. if a secure connection is not used, this property returns zero. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_start_and_end_properties(p[i]); } } function print_start_and_end_properties(perfentry) { // print...
PerformanceResourceTiming.transferSize - Web APIs
ined by rfc7230). note: this feature is available in web workers. if the resource is fetched from a local cache, or if it is a cross-origin resource, this property returns zero. syntax resource.transfersize; return value a number representing the size (in octets) of the fetched resource. the size includes the response header fields plus the response payload body (rfc7230). example the following example, the value of size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the performanceentry.*size properties and print their values // if supported. if ("decodedbodysize" in perfentry) console.log("decodedbodysize = " + perfentry.decodedbodysize); else console.log("decodedbodysize = not supported"); if ("encode...
PerformanceResourceTiming.workerStart - Web APIs
mediately before dispatching the fetchevent if a service worker thread is already running, or immediately before starting the service worker thread if it is not already running. 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. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_start_and_end_properties(p[i]); } } function print_start_and_end_properties(perfentry) { // print...
PeriodicWave - Web APIs
periodicwave.periodicwave() creates a new periodicwave object instance using the default values for all properties. if you wish to establish custom property values at the outset, use the audiocontext.createperiodicwave() factory method instead. properties none; also, periodicwave doesn't inherit any properties. methods none; also, periodicwave doesn't inherit any methods. example the following example illustrates simple usage of createperiodicwave(), to create a periodicwave object containing a simple sine wave. var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); var osc = ac.createoscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createperiodicwave(real, imag, {disablenormalization: true}); osc.setperiodicwa...
Permissions API - Web APIs
the permissions api provides a consistent programmatic way to query the status of api permissions attributed to the current context. for example, the permissions api can be used to determine if permission to access a particular api has been granted or denied. 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). the permissions api provides the tools to allow developers to implement a better user experience as far as permissions are concerned. the permissions property has been made available on the navigator object, both in the ...
PhotoCapabilities.fillLightMode - Web APIs
off no fill light will be used. flash always use the device's fill light. ...
PhotoCapabilities - Web APIs
only returns a mediasettingsrange object indicating the image height range supported by the user agent. photocapabilities.imagewidth read only returns a mediasettingsrange object indicating the image width range supported by the user agent. photocapabilities.filllightmode read only returns an array of available fill light options. options may include auto, off, or flash. example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities() to modify the size of an input range. this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream. const input = document.queryselector('input[type="range"]'); var imagecapture; navigator.mediadevices.getuse...
PointerEvent.PointerEvent() - Web APIs
the pointerevent() constructor creates a new synthetic and untrusted pointerevent object instance. syntax event = new pointerevent(type, pointereventinit); arguments type is a domstring representing the name of the event (see pointerevent event types). pointereventinitoptional is a pointereventinit dictionary, having the following fields: pointerid — optional and defaulting to 0, of type long, that sets the value of the instance's pointerevent.pointerid. width — optional and defaulting to 1, of type double, that sets the value of the instance's pointerevent.width. height — optional and defaulting to 1, of type double, that sets the value of the instance's pointerevent.height. pressure — optional and defaulting to 0, of type float, that sets the value of the in...
PointerEvent.pointerId - Web APIs
pointerevent interface is an identifier assigned to a given pointer event. the identifier is unique, being different from the identifiers of all other active pointer events. since the value may be randomly generated, it is not guaranteed to convey any particular meaning. syntax var id = pointerevent.pointerid; return value id the pointer event's unique identifier number. example the following code snippet compares a previously saved pointerid with the one of the pointerdown event that was just fired. let id; // let's assume that this is a previously saved pointerid target.addeventlistener('pointerdown', function(event) { // compare previous event's id that was cached // to current event's id and handle accordingly if (id === event.pointerid) process_event(event); }, false);...
PointerEvent.pointerType - Web APIs
"pen" the event was generated by a pen or stylus device. "touch" the event was generated by a touch, such as a finger. ...
PointerEvent - Web APIs
uch, etc.) pointerevent.isprimary read only indicates if the pointer represents the primary pointer of this pointer type. methods pointerevent.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 cal...
PopStateEvent - Web APIs
ent. note: browsers used to handle the popstate event differently on page load, but now they behave the same. firefox never emitted a popstate event on page load. chrome did until version 34, while safari did until version 10.0. syntax window.onpopstate = funcref; funcref is a handler function. ...
PositionOptions.enableHighAccuracy - Web APIs
on the other hand, if false (the default value), the device can take the liberty to save resources by responding more quickly and/or using less power. ...
PositionOptions.timeout - Web APIs
the default value is infinity, meaning that getcurrentposition() won't return until the position is available. ...
ProcessingInstruction - Web APIs
with "xml", as xml-prefixed processing-instruction target names are reserved by the xml specification for particular, standard uses (see, for example, <?xml-stylesheet ?>). the processinginstruction interface inherits methods and properties from node. ...
ProgressEvent.initProgressEvent() - Web APIs
ard process. it has been deprecated and removed from most implementation. do not use it anymore, use the standard constructor, progressevent(), to create a synthetic progressevent syntax progress.initprogressevent(typearg, canbubblearg, cancelablearg, lengthcomputable, loaded, total); parameters typearg is a domstring identifying the specific type of animation event that occurred. the following values are allowed: value meaning loadstart the operation has started. progress the operation still is in progress. error the operation failed and didn't complete. abort the operation was cancelled and didn't complete. load the operation completed. loadend the operation stoppe...
PromiseRejectionEvent - Web APIs
events which are sent to the global script context when javascript promises are rejected. these events are particularly useful for telemetry and debugging purposes. for details on promise rejection events, see promise rejection events in using promises. ...
PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() - Web APIs
eyed the consent of the user to disclose such an authenticator existed. examples publickeycredential.isuserverifyingplatformauthenticatoravailable() .then(function(available){ if(available){ // we can proceed with the creation of a publickeycredential // with this authenticator } else { // use another kind of authenticator or a classical login/password // workflow } }).catch(function(err){ // something went wrong console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'isuserverifyingplatformauthenticatoravailable' in that specification. recommendation initial definition. ...
PublicKeyCredentialCreationOptions.authenticatorSelection - Web APIs
authenticatorselection, an optional property of the publickeycredentialcreationoptions dictionary, is an object giving criteria to filter out the authenticators to be used for the creation operation. syntax authenticatorselection = publickeycredentialcreationoptions.authenticatorselection value an object with the following properties: authenticatorattachmentoptional a string which is either "platform" or "cross-platform". the former describes an authenticator which is bound to the client and which is generally not removable. the latter describes a device which may be used across different platform (such as a usb or nfc device). requireresidentkeyoptional a boolean which indicated that the credential private key must be stored in the authenticator, the client or in a clien...
PublicKeyCredentialCreationOptions.extensions - Web APIs
t how the user was verified (e.g. fingerprint, pin, pattern), how the key is protected, how the matcher (tool used for the authentication operation) is protected. biometricperfbounds object with two numerical properties: far and frr biometric authenticator performance bounds. the client must not use any authenticator with false acceptance rate (far) and false rejection rate (frr) below the inputs. the client outputs true if this was taken into account. note: extensions are optional and different browsers may recognize different extensions. all extensions are optional for the client to process them: if a browser does not know a given extension, that will not cause any failure, the extension simply will not be processed. examples var publickey = { extensions:{ uv...
PublicKeyCredentialCreationOptions.pubKeyCredParams - Web APIs
scribing the desired features of the credential to be created. these objects define the type of public-key and the algorithm used for cryptographic signature operations. if this array contains multiple elements, they are sorted by descending order of preference. syntax pubkeycredparams = publickeycredentialcreationoptions.pubkeycredparams value an array whose elements are objects with the following properties: type a string describing type of public-key credential to be created. as of this writing (march 2019), only "public-key" may be used. alg a numeric identifier for the algorithm to be used to generate the key pair. the links between identifier and algorithms are defined in this iana registry (e.g. -7 indicates the elliptic curve algorithm ecdsa with sha-256). though those el...
PublicKeyCredentialCreationOptions.user - Web APIs
ctionary is an object describing the user account for which the credentials are generated (via navigator.credentials.create()). syntax useraccount = publickeycredentialcreationoptions.user properties displayname a domstring which is human readable and intended for display. it may be the full name of the user (e.g. "john doe"). this is not intended to store the login of the user (see name below). icon optional an url as a usvstring value which points to an image resource which can be the avatar image for the user. id a buffersource uniquely identifying a given user. this an opaque identifier which can be used by the authenticator to link the user account with its corresponding credentials. this value will later be used when fetching the credentials in authenticatorassertionresponse.
PushEvent.data - Web APIs
Web › API › PushEvent › data
the data read-only property of the pushevent interface returns a reference to a pushmessagedata object containing data sent to the pushsubscription. syntax var mypushdata = pushevent.data; value a pushmessagedata object. examples the following example takes data from a pushevent and displays it on all of the service workers' clients. self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/new-notification.png"; var notification = new notification(title, { body: message,...
PushEvent - Web APIs
Web › API › PushEvent
ion server to a pushsubscription. constructor pushevent.pushevent() creates a new pushevent object. properties inherits properties from its parent, extendableevent. additional properties: pushevent.data read only returns a reference to a pushmessagedata object containing data sent to the pushsubscription. methods inherits methods from its parent, extendableevent. examples the following example takes data from a pushevent and displays it on all of the service worker's clients. self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "something has happened"; var message = data.message || "here...
PushManager.getSubscription() - Web APIs
ption? serviceworkerregistration.pushmanager.getsubscription() .then(function(subscription) { // enable any ui which subscribes / unsubscribes from // push messages. ...
PushManager.permissionState() - Web APIs
es are 'prompt', 'denied', or 'granted'. note: as of firefox 44, the permissions for notifications and push have been merged. if permission is granted for notifications, push will also be enabled. syntax pushmanager.permissionstate(options).then(function(pushmessagingstate) { ... }); parameters options optional an object containing optional configuration parameters. it can have the following properties: uservisibleonly: a boolean indicating that the returned push subscription will only be used for messages whose effect is made visible to the user. applicationserverkey: a public key your push server will use to send messages to client apps via a push server. this value is part of a signing key pair generated by your application server and usable with elliptic curve digital si...
PushManager.registrations() - Web APIs
tions method is used to ask the system about existing push endpoint registrations. syntax var request = navigator.push.registrations(); return a domrequest object to handle the success or failure of the method call. if the method call is successful, the request's result will be an array of pushregistration objects. pushregistration those objects are anonymous javascript objects with the following properties: pushendpoint a string representing the url of the endpoint. version the current version that the push endpoint is at. example var req = navigator.push.registrations(); req.onsuccess = function(e) { if (req.result.length > 0) { for (var i = 0, l = req.result.length; i < l; i++) { console.log("existing registration", req.result[i].pushendpoint, req.result[i].ver...
PushManager.unregister() - Web APIs
push.unregister(pushendpoint); properties pushendpoint a pushendpoint to be unregistered. return a domrequest object to handle the success or failure of the method call. if the method call is successful, the request's result will be a pushregistration object representing the endpoint that has been unregistered. pushregistration those objects are anonymous javascript objects with the following properties: pushendpoint a string representing the url of the unregistered endpoint. version undefined when unregister.onsuccess is called. example var req = navigator.push.unregister(pushendpoint); req.onsuccess = function(e) { var endpoint = req.result; debug("unregistered endpoint: " + endpoint ); } req.onerror = function(e) { debug("error unregistering the endpoint: " + js...
PushMessageData - Web APIs
messages received through the push api are sent encrypted by push services and then automatically decrypted by browsers before they are made accessible through the methods of the pushmessagedata interface. properties none. methods pushmessagedata.arraybuffer() extracts the data as an arraybuffer object. ...
PushSubscription.getKey() - Web APIs
n secret, as described in message encryption for web push. returns an arraybuffer. example reg.pushmanager.getsubscription() .then(function(subscription) { // enable any ui which subscribes / unsubscribes from // push messages. ...
PushSubscription.options - Web APIs
applicationserverkey: a public key your push server will use to send messages to client apps via a push server. ...
PushSubscription - Web APIs
an instance of this interface can be serialized. properties pushsubscription.endpoint read only a usvstring containing the endpoint associated with the push subscription. pushsubscription.expirationtime read only a domhighrestimestamp of the subscription expiration time associated with the push subscription, if there is one, or null otherwise. pushsubscription.options read only an object containing the options used to create the subscription. ...
Web Push API Notifications best practices - Web APIs
t 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 interaction-requiring ones very sparingly, since they can be the most annoying. your notifications should be assistive, not disruptive. building trust some studies have shown that as many as 60% of push notifications are blocked. allowing your site to push notifications in realtime requires trust. you can build trust by having a well-designed website that provides good content that shows respect for the user, and a clear value to accepting push notifications. browser mitigations because of abuses of push notifications in the past, web browser developers have begun to implement strategies to help mitigate this problem. for exa...
RTCConfiguration.iceServers - Web APIs
performance and how many servers get used for negotiation before a connection is established. if the list of servers is changed while a connection is already active by calling the the rtcpeerconnection method setconfiguration(), no immediate effect occurs. however, the new list of servers is used for any future renegotiation, such as while handling an ice restart. examples the configuration below opens a new peer connection, specifying two servers for the ice agent to use for negotiation. the first one, stun:stun.services.mozilla.com, requires authentication, so the username and password are provided. the second server has two urls: stun:stun.example.com and stun:stun-1.example.com. var configuration = { iceservers: [{ urls: "stun:stun.services.mozilla.com", ...
RTCDTMFSender.insertDTMF() - Web APIs
ueued 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 specification status comment webr...
RTCDTMFSender.toneBuffer - Web APIs
e buffer is a string which can contain any combination of the characters that are permitted by the dtmf standard. dtmf tone characters the digits 0-9 these characters represent the digit keys on a telephone keypad. the letters a-d these characters represent the "a" through "d" keys which are part of the dtmf standard but not included on most telephones. these are not interpreted as digits. lower-case "a"-"d" automatically gets converted to upper-case. the pound/hash sign ("#") and the asterisk ("*") these correspond to the similarly-labeled keys which are typically on the bottom row of the telephone keypad. the comma (",") this character instructs the dialing process to pause for two seconds before sending the next character in the buffer. all other characters are unrecognized a...
RTCDataChannel.binaryType - Web APIs
the default is "blob". when a binary message is received on the data channel, the resulting message event's messageevent.data property is an object of the type specified by the binarytype. ...
RTCDataChannel.close() - Web APIs
is not instantaneous. most of the process of closing the connection is handled asynchronously; you can detect when the channel has finished closing by watching for a close event on the data channel. the sequence of events which occurs in response to this method being called: rtcdatachannel.readystate is set to "closing". a background task is established to handle the remainder of the steps below, and close() returns to the caller. the transport layer deals with any buffered messages; the protocol layer decides whether to send them or discard them. the underlying data transport is closed. the rtcdatachannel.readystate property is set to "closed". if the transport was closed with an error, the rtcdatachannel is sent a networkerror event. a close event is sent to the channel. in fir...
RTCDataChannel: close event - Web APIs
nel instance must be created. bubbles no cancelable no interface event event handler property rtcdatachannel.onclose examples this example sets up a handler for the close event for the rtcdatachannel named dc; its responsibility in this example is to update user interface elements to reflect that there is no longer an ongoing call, and to allow a new call to be started. dc.addeventlistener("close", ev => { messageinputbox.disabled = true; sendbutton.disabled = true; connectbutton.disabled = false; disconnectbutton.disabled = true; }, false); all this code does in response to receiving the close event is to disable an input box and its "send" button, and to enable the button used to start a call (while disabling the one that e...
RTCDataChannel.maxPacketLifeTime - Web APIs
this limits how long the browser can continue to attempt to transmit and retransmit the message before giving up. syntax var lifetime = adatachannel.maxpacketlifetime; value the number of milliseconds over which the browser may continue to attempt to transmit the message until it either succeeds or gives up. if not set when rtcpeerconnection.createdatachannel() was called to create the data channel, this value is null. ...
RTCDataChannel.negotiated - Web APIs
the webrtc layer (false). the default is false. see creating a data channel in using webrtc data channels for further information about this property. syntax var negotiated = adatachannel.negotiated; value true if the 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 webrt...
RTCDataChannel.onerror - Web APIs
orevent object describing the error which occurred. syntax rtcdatachannel.onerror = function; value a function which the browser will call to handle the error event when it occurs on the data channel. this function receives as its only input an errorevent object describing the event which was received. that event object, in turn, describes the error that took place. example in the example below, a data channel is established, and an onerror handler is added to it. the error handler passes information about the error to a ui library's alert box function to present an error message to the user. let pc = new rtcpeerconnection(); let dc = pc.createdatachannel("playercontrol"); dc.onerror = function(event) { myuilibrary.doalertbox({ 'network error', // alert title 'the err...
RTCDataChannel.onopen - Web APIs
syntax rtcdatachannel.onopen = function; value a function which the browser will call to handle the open event. the function receives as its only input parameter the event itself, of type event. ...
RTCDataChannelEvent() - Web APIs
levent by hand; these events are normally created and sent by the webrtc layer itself. syntax var event = new rtcdatachannelevent(type, rtcdatachanneleventinit); parameters type a domstring which specifies the name of the event. there is only one type of rtcdatachannelevent, so this will always be "datachannel". rtcdatachanneleventinit a rtcdatachanneleventinit dictionary, which has following fields: "channel" of type rtcdatachannel, representing the data channel being concerned by the event. "bubbles", optional, inherited from eventinit. indicates if the event must bubble or not. default is false. "cancelable", optional, inherited from eventinit. indicates if the event can be canceled or not. default is false. value a new rtcdatachannelevent configured as specified.
RTCDataChannelEvent.channel - Web APIs
the read-only property rtcdatachannelevent.channel returns the rtcdatachannel associated with the event. syntax var channel = rtcdatachannelevent.channel; value a rtcdatachannel 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 communi...
RTCDtlsTransport.state - Web APIs
the state read-only property of the rtcdtlstransport interface provides information which describes a datagram transport layer security (dtls) transport state. syntax let mystate = dtlstransport.state; value a string whose value is taken from the rtcdtlstransportstate enumerated type. its value is one of the following: new the initial state when dtls has not started negotiating yet. connecting dtls is in the process of negotiating a secure connection and verifying the remote fingerprint. connected dtls has completed negotiation of a secure connection and verified the remote fingerprint. closed the transport has been closed intentionally as the result of receipt of a close_notify alert, or calling rtcpeerconnection.close(). failed the transport has failed as the result of an e...
RTCDtlsTransport - Web APIs
features of the dtls transport include the addition of security to the underlying transport; the rtcdtlstransport interface can be used to obtain information about the underlying transport and the security added to it by the dtls layer. ...
RTCError - Web APIs
Web › API › RTCError
dard domexception interface that describes general dom errors. constructor rtcerror() creates and returns a new rtcerror object initialized with the properties of the provided rtcerrorinit dictionary and, optionally, a string to use as the value of the error's message property. properties in addition to the properties defined by the parent interface, domexception, rtcerror includes the following properties: errordetail read only a domstring specifying the webrtc-specific error code identifying the type of error that occurred. receivedalert read only an unsigned long integer value indicating the fatal dtls error which was received from the network. only valid if the errordetail string is dtls-failure. if null, no dtls error was received. sctpcausecode read only if errordeta...
RTCErrorEvent - Web APIs
the webrtc api's rtcerrorevent interface represents an error sent to a webrtc object. it's based on the standard event interface, but adds rtc-specific information describing the error, as shown below. constructor rtcerrorevent() creates and returns a new rtcerrorevent object. properties in addition to the standard properties available on the event interface, rtcerrorevent also includes the following: error read only an rtcerror object specifying the error which occurred; this object includes the type of error that occurred, information about where the error occurred (such as which line number in the sdp or what sctp cause code was at issue). methods no additional methods are provided beyond any found on the parent interface, event. description there are other data types us...
RTCIceCandidate.relatedAddress - Web APIs
ess can also be used by quality-of-service (qos) mechanisms. here's an sdp attribute line (a-line) describing an ice candidate discovered by the stun server: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 6502 typ srflx raddr 192.168.2.77 rport 32768 generation 0 the remote address, relatedaddress, is the dotted quad (for ipv4) or colon-delineated 64-bit address (for ipv6) immediately following the text "raddr", or "192.168.2.77". example in this example, the candidate's type is checked, and then debugging output is presented, based on the candidate type, including the candidate's ip and relatedaddress. switch(candidate.type) { case "host": console.log("host candidate's ip address is " + candidate.ip); break; case "srflx": console.log("server reflexive candidate's ...
RTCIceCandidate.relatedPort - Web APIs
omitted for security reasons, but if present can be a useful tool during debugging. see the example, which shows a bit of this. here's an sdp attribute line (a-line) describing an ice candidate discovered by the stun server: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 6502 typ srflx raddr 192.168.2.77 rport 32768 generation 0 the remote port, relatedport, is the number immediately following the "rport" label on the a-line, or 32768. example in this example, the candidate's type is checked, and then debugging output is presented, based on the candidate type, including the candidate's type, address (ip and port), and related address (relatedaddress and relatedport). var ip = candidate.ip; var port = candidate.port; var relip = candidate.relatedaddress; var relport = candidate.re...
RTCIceCandidate. toJSON() - Web APIs
which it's called into json in the form of an rtcicecandidateinit object. syntax json = rtcicecandidate.tojson(); return value an object conforming to the rtcicecandidateinit dictionary, whose members' values are set to the corresponding values in the rtcicecandidate object. you can then get a stringified version of the object by calling stringify() on the returned object. see the example below. example this simple example obtains a json string representing an rtcicecandidate found in the variable candidate. var jsonstring = candidate.tojson().stringify(); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.tojson()' in that specification. candidate recommendation initial de...
RTCIceCandidatePairStats.availableOutgoingBitrate - Web APIs
mingbitrate. 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 support computing a sender-side estimate of the outgoing bit rate. the rtcicecandidatepair described by this object has never been used. the candidate pair was once in use, but no longer is. the value returned is calculated by adding up the available bit rate for every rtp stream using the connection described by this candidate pair. the...
RTCIceCandidatePairStats.circuitBreakerTriggerCount - Web APIs
configuration. a circuit breaker trigger is fired each time the connection times out or otherwise needs to be halted automatically. syntax cbtcount = rtcicecandidatepairstats.circuitbreakertriggercount; value an integer value indicating the number of times the circuit-breaker has been triggered for the 5-tuple used by this connection. a 5-tuple defining a tcp connection is made up of the following data: the source ip address. the source port number. the destination ip address. the destination port number. network protocol. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcicecandidatepairstats.circuitbreakertriggercount' in that specification. candidate recommendation initial specification...
RTCIceCandidatePairStats.consentExpiredTimestamp - Web APIs
s indicates when the current stun bindings — the mapping of the ip address and port configurations for both peers on the webrtc connection — are due to expire. if this time has arrived or passed, the bindings have expired. syntax consentexpiration = rtcicecandidatepairstats.consentexpiredtimestamp; value a domhighrestimestamp object that indicates the time at which the stun binding that allows the two peers described by this rtcicecandidatepair to communicate will expire (or the time at which the binding did expire, if the time has passed). this property's value is undefined if there have been no stun binding responses yet on the candidate pair. this is only possible if responsesreceived is 0. specifications specification status comment identifiers for w...
RTCIceCandidatePairStats.nominated - Web APIs
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). specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcicecandidatepairstats.nominated' in that specification. candidate recommendation initial specification. ...
RTCIceCandidateStats.priority - Web APIs
iority = 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. ...
RTCIceCandidateStats - Web APIs
address optional a string containing the address of the candidate. this value may be an ipv4 address, an ipv6 address, or a fully-qualified domain name. this property was previously named ip and only accepted ip addresses. ...
RTCIceCredentialType - Web APIs
o an ice server identified by an rtciceserver object. values oauth the rtciceserver requires the use of oauth 2.0 to authenticate in order to use the ice server described. this process is detailed in rfc 7635. this property was formerly called token. password the rtciceserver requires a username and password to authenticate prior to using the described ice server. obsolete values the following values are no longer part of the webrtc specification, but were in the past. token authenticating with the ice server requires the use of an oauth 2.0 token as defined in rfc 7635. this value has been renamed to oauth. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecredentialtype' in th...
RTCIceServer.url - Web APIs
Web › API › RTCIceServer › url
sed while negotiating connections. it was removed from the specification in june 2013 but is still broadly used in older examples and books, so we include documentation here to help adapt old code to new browsers. this property has been removed from the specification; while it's still supported by many browsers, it should no longer be used. you should instead use the newer urls property, which allows you to optionally specify multiple urls for the server. try to update any existing code to use that property instead. syntax var iceserver = { ... url = iceserverurl, ... }; var serverurl = iceserver.url; iceserver.url = iceserverurl; the value of this property is a domstring containing the full url of a server to use dur...
RTCIceTransport.state - Web APIs
which the ice agent currently is operating. 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...
RTCIceTransport: statechange event - Web APIs
he state can be used to determine how far through the process of examining, verifying, and selecting a valid candidate pair is prior to successfully connecting the two peers for webrtc communications. 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. let icetransport = pc.getsenders()[0].transport.icetransport; icetransport.addeventlistener("statechange", ev => { if (icetransport.state === "failed") { handlefailure(pc); } }, false); the same code, using the onstatechange event handler property, looks like this:...
RTCIceTransport - Web APIs
the rtcicetransport interface provides access to information about the ice transport layer over which the data is being sent and received. this is particularly useful if you need to access state information about the connection. properties the rtcicetransport interface inherits properties from its parent, eventtarget. it also offers the following properties: component read only the ice component being used by the transport. the value is one of the strings from the rtcicetransport enumerated type: "rtp" or "rtsp". gatheringstate read only a domstring indicating which gathering state the ice agent is currently in. the value is one of those included in the rtcicegathererstate enumerated type: "new", "gathering", or "complete". role read only returns a domstring whose value is one o...
RTCIdentityErrorEvent.idp - Web APIs
it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
RTCIdentityErrorEvent.loginUrl - Web APIs
it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
RTCIdentityErrorEvent - Web APIs
it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
RTCIdentityEvent.assertion - Web APIs
it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
RTCIdentityEvent - Web APIs
it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. properties a rtcidentityevent being an event, this event also implements these properties. ...
RTCInboundRtpStreamStats.pliCount - Web APIs
lue an integer value indicating the number of times a pli packet was sent by the rtcrtpreceiver to the sender. these are sent by the receiver's decoder to notify the encoder (the sender) that an undefined amount of coded video data, which may span frame boundaries, has been lost. this information is only available for video streams. this may trigger the sender to send a full frame in order to allow the receiver to re-synchronize, since lost data may be an irrecoverable situation for decoding media. however, the primary purpose of this message is to allow the sender to consider techniques to mitigate network performance issues. this is often achieved by methods such as increasing the compression, lowering resolution, or finding other ways to reduce the bit rate of the stream. specifications...
RTCNetworkType - Web APIs
cellular the connection uses a cellular data service to connect. this includes all cellular data services including edge (2g), hspa (3g), lte (4g), and nr (5g). ethernet the described connection uses an ethernet network. ...
RTCOutboundRtpStreamStats - Web APIs
averagertcpinterval a floating-point value indicating the average rtcp interval between two consecutive compound rtcp packets. ...
RTCPeerConnection.addStream() - Web APIs
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. ...
RTCPeerConnection.addTrack() - Web APIs
. from then on, new tracks are added to that stream. you could also just create a new stream for each track received: pc.ontrack = ev => { if (ev.streams && ev.streams[0]) { videoelem.srcobject = ev.streams[0]; } else { let inboundstream = new mediastream(ev.track); videoelem.srcobject = inboundstream; } } associating 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(). for example, consider this function that an application might use to begin streaming a device's camera and microphone input over an rtcpeerconne...
RTCPeerConnection.addTransceiver() - Web APIs
object that conforms to the rtcrtptransceiverinit dictionary which provides any options that you may wish to specify when creating the new transceiver. possible values are: direction optional the new transceiver's preferred directionality. this value is used to initialize the new rtcrtptransceiver object's rtcrtptransceiver.direction property. sendencodings optional a list of encodings to allow when sending rtp media from the rtcrtpsender. each entry is of type rtcrtpencodingparameters. streams optional a list of mediastream objects to add to the transceiver'srtcrtpreceiver; when the remote peer's rtcpeerconnection's track event occurs, these are the streams that will be specified by that event. exceptions typeerror a string was specified as trackorkind which is not valid. th...
RTCPeerConnection.canTrickleIceCandidates - Web APIs
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(remoteoffer) .then(_ => pc.createanswer()) .then(answer => pc.setlocaldescription(answer)) .then(_ => if (pc.cantrickleicecandidates) { return pc.localdescription; } return new promise(r => { pc.addeventlistener('icegatheringstatechange...
RTCPeerConnection.connectionState - Web APIs
y the connectionstate property. this state essentially represents the aggregate state of all ice transports (which are of type rtcicetransport or rtcdtlstransport) being used by the connection. constant description "new" at least one of the connection's ice transports (rtcicetransports or rtcdtlstransports) are in the "new" state, and none of them are in one of the following states: "connecting", "checking", "failed", or "disconnected", or all of the connection's transports are in the "closed" state. "connecting" one or more of the ice transports are currently in the process of establishing a connection; that is, their rtciceconnectionstate is either "checking" or "connected", and no transports are in the "failed" state. <<< make this a link once i kno...
RTCPeerConnection.createAnswer() - Web APIs
ize the answer; this is based on the rtcansweroptions dictionary. deprecated parameters in older code and documentation, you may see a callback-based version of this function. this has been deprecated and its use is strongly discouraged. you should update any existing code to use the promise-based version of createanswer() instead. the parameters for this form of createanswer() are described below, to aid in updating existing code. successcallback an rtcsessiondescriptioncallback which will be passed a single rtcsessiondescription object describing the newly-created answer. failurecallback an rtcpeerconnectionerrorcallback which will be passed a single domexception object explaining why the request to create an answer failed. options optional an optional rtcofferoptions object...
RTCPeerConnection.createDataChannel() - Web APIs
egotiationneeded event. syntax datachannel = rtcpeerconnection.createdatachannel(label[, options]); parameters label a human-readable name for the channel. this string may not be longer than 65,535 bytes. options optional an rtcdatachannelinit dictionary providing configuration options for the data channel rtcdatachannelinit dictionary the rtcdatachannelinit dictionary provides the following fields, any of which may be included in the object passed as the options parameter in order to configure the data channel to suit your needs: ordered optional indicates whether or not messages sent on the rtcdatachannel are required to arrive at their destination in the same order in which they were sent (true), or if they're allowed to arrive out-of-order (false). default: true. maxpacke...
RTCPeerConnection.getIdentityAssertion() - Web APIs
nnection.getidentityassertion() method initiates the gathering of an identity assertion. this has an effect only if the signalingstate is not "closed". the method returns immediately. if the assertion cannot be generated, an idpassertionerror will be sent to the object. it is not expected for the application dealing with the rtcpeerconnection: this is automatically done; an explicit call only allows to anticipate the need. syntax pc.getidentityassertion(); there is neither parameter nor return value for this method. example var pc = new peerconnection(); pc.getidentityassertion(); // not mandatory, but we know that we will need it in the future. specifications specification status comment identity for webrtcthe definition of 'rtcpeerconnection.getide...
RTCPeerConnection.getStreamById() - Web APIs
motestreams properties. if you have code that uses stream, you will need to update, since browsers have begun to remove support for stream. syntax var mediastream = pc.getstream(id); parameters id is a domstring corresponding to the stream to return. example var stream = pc.getstreambyid(mytrackid); if (stream) { console.log("found stream: " + stream.id); } polyfill running the following code before any other code will create rtcpeerconnection.prototype.getstreambyid() if it's not natively available. // from: https://bugs.chromium.org/p/chromium/issues/detail?id=698163&desc=5#c10 rtcpeerconnection.prototype.getstreambyid = function(id) { try { var localstreams = this.getlocalstreams(); var remotestreams = this.getremotestreams(); var i; for (i = 0; i < local...
RTCPeerConnection.getTransceivers() - Web APIs
r objects being used to send and receive data on the connection. syntax transceiverlist = rtcpeerconnection.gettransceivers(); parameters none. return value an array of the rtcrtptransceiver objects representing the transceivers handling sending and receiving all media on the rtcpeerconnection. the list is in the order in which the transceivers were added to the connection. example the following snippet of code stops all transceivers associated with an rtcpeerconnection. pc.gettransceivers().foreach(transceiver => { transceiver.stop(); }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.gettransceivers()' in that specification. candidate recommendation ...
RTCPeerConnection.iceConnectionState - Web APIs
"new" the ice agent is gathering addresses or is waiting to be given remote candidates through calls to rtcpeerconnection.addicecandidate() (or both). "checking" the ice agent has been given one or more remote candidates and is checking pairs of local and remote candidates against one another to try to find a compatible match, but has not yet found a pair which will allow the peer connection to be made. it's possible that gathering of candidates is also still underway. "connected" a usable pairing of local and remote candidates has been found for all components of the connection, and the connection has been established. it's possible that gathering is still underway, and it's also possible that the ice agent is still checking candidates against one ano...
RTCPeerConnection: icecandidateerror event - Web APIs
the valid stun error code range: 701. error 701 indicates that none of the ice candidates were able to successfully make contact with the stun or turn server. the 701 error is fired only once per server url from the list of available stun or turn servers provided when creating the rtcpeerconnection. these errors occur only when the connection's ice gathering state is gathering. example the following example establishes a handler for icecandidateerrors that occur on the rtcpeerconnection pc. this handler looks specifically for 701 errors that indicate that candidates couldn't reach the stun or turn server. when this happens, the server url and the error message are passed to a function called reportconnectfail() to log or output the connection failure. pc.addeventlistener("icecandidateer...
RTCPeerConnection.onicecandidate - Web APIs
has finished. this message should not be sent to the remote peer. when this happens, the connection's icegatheringstate has also changed to complete. you don't need to watch for this explicitly; instead, if you need to sense the end of signaling, you should watch for a icegatheringstatechange event indicating that the ice negotiation has transitioned to the complete state. example the example below, which is based on the code from the article signaling and video calling, sets up a handler for icecandidate events to send the candidates to the remote peer. pc.onicecandidate = function(event) { if (event.candidate) { // send the candidate to the remote peer } else { // all ice candidates have been sent } } notice that the end of negotiation is detected here when the event's can...
RTCPeerConnection.oniceconnectionstatechange - Web APIs
onstate 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.iceconnectionstate === "closed") { // handle the failure } }; ...
RTCPeerConnection.restartIce() - Web APIs
after restartice() returns, the offer returned by the next call to createoffer() is automatically configured to trigger ice restart on both the local peer (once the local peer has been set) and on the remote peer, once the offer is sent across your signaling mechanism and the remote peer has set its description as well. ...
RTCPeerConnection.signalingState - Web APIs
erconnection.setlocaldescription(). your code will be more reliable if you watch for mismatched states like this and handle them gracefully. this value may also be useful during debugging, for example. in addition, when the value of this property changes, a signalingstatechange event is sent to the rtcpeerconnection instance. syntax var state = rtcpeerconnection.signalingstate; value the allowed values are those included in the enum rtcsignalingstate. rtcsignalingstate enum the rtcsignalingstate enum specifies the possible values of rtcpeerconnection.signalingstate, which indicates where in the process of signaling the exchange of offer and answer the connection currently is. constant description "stable" there is no ongoing exchange of offer and answer u...
RTCPeerConnectionIceErrorEvent - Web APIs
tion object. constructor rtcpeerconnectioniceerrorevent() creates and returns a new rtcpeerconnectioniceerrorevent object, with its type and other properties initialized as specified in the parameters. you will not normally create an object of this type yourself. properties the rtcpeerconnectioniceerrorevent interface includes the properties found on the event interface, as well as the following properties: address read only a domstring providing the local ip address used to communicate with the stun or turn server being used to negotiate the connection, or null if the local ip address has not yet been exposed as part of a local ice candidate. errorcode read only an unsigned integer value stating the numeric stun error code returned by the stun or turn server. if no host candi...
RTCPeerConnectionIceEvent() - Web APIs
the rtcpeerconnectioniceevent() constructor creates a new rtcpeerconnectioniceevent. syntax var event = new rtcpeerconnectioniceevent(type, options); parameters type is a domstring containing the name of the event, like "icecandidate". options a dictionary of type rtcpeerconnectioninit, which may contain one or more of the following fields: "candidate" (optional, default is null): a rtcicecandidate representing the ice candidate being concerned by the event. if null, the event indicates the end of candidate gathering. "url" (optional, default is null): the url of the stun or turn server which was used to gather the candidate. if the candidate was not gathered by a stun or turn server, this value must be null. "bubbles" (optional, default is false): inherited from eventin...
RTCRemoteOutboundRtpStreamStats - Web APIs
the webrtc statistics model's rtcremoteoutboundrtpstreamstats dictionary extends the underlying rtcsentrtpstreamstats dictionary with properties measuring metrics specific to outgoing rtp streams. properties in addition to the properties defined by rtcsentrtpstreamstats and its underlying rtcrtpstreamstats and rtcstats dictionaries, rtcremoteoutboundrtpstreamstats defines the following properties. localid a domstring which is used to find the local rtcinboundrtpstreamstats object which shares the same synchronization source (ssrc). remotetimestamp a domhighrestimestamp specifying the timestamp (on the remote device) at which the statistics in the rtcremoteoutboundrtpstreamstats object were sent by the remote endpoint. this is different from the timestamp found in the base rtcstats di...
RTCRtpCapabilities - Web APIs
ties object contains an array of objects conforming to rtcrtpcodeccapability (each 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 de...
RTCRtpEncodingParameters - Web APIs
tx only used for an rtcrtpsender whose kind is audio, this property indicates whether or not to use discontinuous transmission (a feature by which a phone is turned off or the microphone muted automatically in the absence of voice activity). the value is taken from the enumerated string type rtcdtxstatus. maxbitrate an unsigned long integer indicating the maximum number of bits per second to allow for this encoding. other parameters may further constrain the bit rate, such as the value of maxframerate or transport or physical network limitations. maxframerate a double-precision floating-point value specifying the maximum number of frames per second to allow for this encoding. ptime an unsigned long integer value indicating the preferred duration of a media packet in milliseconds. this ...
RTCRtpReceiver.getCapabilities() static function - Web APIs
e for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. example the function below returns a boolean indicating whether or not the device supports receiving h.264 video on a webrtc connection. since rtcrtpreceiver.getcapabilities() actually only indicates probable support, attempting to receive h.264 video might still fail even after getting a positive response from this function. function canreceiveh264() { let capabilities = rtcrtpreceiver.getcapabilities("video"); c...
RTCRtpSendParameters.encodings - Web APIs
tx only used for an rtcrtpsender whose kind is audio, this property indicates whether or not to use discontinuous transmission (a feature by which a phone is turned off or the microphone muted automatically in the absence of voice activity). the value is taken from the enumerated string type rtcdtxstatus. maxbitrate an unsigned long integer indicating the maximum number of bits per second to allow for this encoding. other parameters may further constrain the bit rate, such as the value of maxframerate or transport or physical network limitations. maxframerate a double-precision floating-point value specifying the maximum number of frames per second to allow for this encoding. ptime an unsigned long integer value indicating the preferred duration of a media packet in milliseconds. this ...
RTCRtpSender.getCapabilities() static function - Web APIs
e for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. example the function below returns a boolean indicating whether or not the device supports sending h.264 video on an rtcrtpsender. since rtcrtpsender.getcapabilities() actually only indicates probable support, h.264 support might still fail even after getting a positive response from this function. function cansendh264() { let capabilities = rtcrtpsender.getcapabilities("video"); capabilities.codecs.foreach((codec...
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.pliCount - Web APIs
t; value an integer value indicating the number of times a pli packet was sent by the stream's receiver to the sender. a pli message is used by video decoders (running on the receiving end of the stream) to notify the encoder (the sender) that an undefined amount of coded video data, which may span frame boundaries, has been lost. this may trigger the sender to send a full frame in order to allow the receiver to re-synchronize, since lost data may be an irrecoverable situation for decoding media. however, the primary purpose of this message is to allow the sender to consider techniques to mitigate network performance issues. this is often achieved by methods such as increasing the compression, lowering resolution, or finding other ways to reduce the bit rate of the stream. note: this va...
RTCRtpSynchronizationSource - Web APIs
e (ssrc). a synchronization source is a single source that shares timing and sequence number space. 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. properties also implements the properties of rtcrtpcontributingsource. voiceactivityflag optional a boolean value indicating whether or not voice activity is included in the last rtp packet played from the source. if the peer has indicated that it's not supporting voice activity detection, this field is not provided. specifications specification status comment ...
RTCRtpTransceiver.currentDirection - Web APIs
nality using direction property. 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. each describes how the transceiver's associated rtcrtpsender and rtcrtpreceiver behave as shown in the table below. value rtcrtpsender behavior rtcrtpreceiver behavior "sendrecv" offers to send rtp data, and will do so if the other peer accepts the connection and at least one of the sender's encodings is active1. offers to receive rtp data, and does so if the other peer accepts. "sendonly" offers to send rtp data, and will do so if the other peer accepts the conn...
RTCRtpTransceiver.setCodecPreferences() - Web APIs
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 availreceivecodecs = transceiver.receiver.getcapabilities("video").codecs; specifications specification status comment webrtc 1.0: real-time communication between br...
RTCRtpTransceiverDirection - Web APIs
irection type is an enumerated set of strings which are used to describe the directionality of a rtcrtptransceiver instance. both the preferred direction and the currentdirection properties are of this type. values the rtcrtptransceiverdirection type is an enumeration of string values. each describes how the transceiver's associated rtcrtpsender and rtcrtpreceiver behave as shown in the table below. value rtcrtpsender behavior rtcrtpreceiver behavior "sendrecv" offers to send rtp data, and will do so if the other peer accepts the connection and at least one of the sender's encodings is active1. offers to receive rtp data, and does so if the other peer accepts. "sendonly" offers to send rtp data, and will do so if the other peer accepts the conn...
RTCRtpTransceiverInit - Web APIs
transceiverinit dictionary is used when calling the webrtc function rtcpeerconnection.addtransceiver() to provide configuration options for the new transceiver. properties direction optional the new transceiver's preferred directionality. this value is used to initialize the new rtcrtptransceiver object's rtcrtptransceiver.direction property. sendencodings optional a list of encodings to allow when sending rtp media from the rtcrtpsender. each entry is of type rtcrtpencodingparameters. streams optional a list of mediastream objects to add to the transceiver'srtcrtpreceiver; when the remote peer's rtcpeerconnection's track event occurs, these are the streams that will be specified by that event. specifications specification status comment webrtc 1.0: real-...
RTCSctpTransport.state - Web APIs
the state read-only property of the rtcsctptransport interface provides information which describes a stream control transmission protocol (sctp) transport state. syntax var mystate = sctptransport.state; value a string whose value is taken from the rtcsctptransportstate enumerated type. its value is one of the following: connecting the initial state when the connection is being estabilished. connected the connection is open for data transmission. closed the connection is closed and can no longer be used. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcsctptransport.state' in that specification. candidate recommendation initial definition. ...
RTCSessionDescription() - Web APIs
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 rtcsdptype enum; it must have one of the following values: this enum defines strings that describe the current state of the session description, as used in the type property. the session description's type will be specified using one of these values. value description answer the sdp contained in t...
RTCSessionDescription.type - Web APIs
"answer", the description is the definitive choice in an offer/answer exchange. ...
RTCStatsReport - Web APIs
e was taken for this statistics object. type a domstring indicating the type of statistics the object contains, taken from the enum type rtcstatstype. the statistic categories the type gives the name of the statistic category represented by the object, and is how you locate the specific type of data you need. the statistic category names are members of the enumerated type rtcstatstype, as follows: 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. the active candidate pair is deleted after the transport switches to another candidate pair; this chang...
RTCTrackEvent() - Web APIs
n't need to use this constructor, as rtctrackevent objects are created by webrtc and delivered to your rtcpeerconnector's ontrack event handler as appropriate. syntax trackevent = new rtctrackevent(eventinfo); parameters eventinfo an object based on the rtctrackeventinit dictionary, providing information about the track which has been added to the rtcpeerconnection. this object has the following properties: receiver the rtcrtpreceiver which is being used to receive the track's media. streams optional an array of mediastream objects representing each of the streams that comprise the event's corresponding track. track the mediastreamtrack the event is associated with. transceiver the rtcrtptransceiver associated with the event. return value a new rtctrackevent describing a t...
RTCTrackEventInit.transceiver - Web APIs
syntax var trackeventinit = { receiver: rtpreceiver, track: mediastreamtrack, streams: [videostream], transceiver: rtptransceiver }; var rtptransceiver = trackeventinit.transceiver; value the rtcrtptransceiver which pairs the receiver with a sender and other properties which establish a single bidirectional srtp stream for use by the track associated with the rtctrackevent. ...
RTCTrackEventInit - Web APIs
streams optional an array of mediastream objects representing each of the streams that comprise the event's corresponding track. ...
RadioNodeList - Web APIs
the radionodelist interface represents a collection of radio elements in a <form> or a <fieldset> element. ...
Range.commonAncestorContainer - Web APIs
of each piece of selected text, and triggers an animation to highlight them. html <ul> <li>strings <ul> <li>cello</li> <li>violin <ul> <li>first chair</li> <li>second chair</li> </ul> </li> </ul> </li> <li>woodwinds <ul> <li>clarinet</li> <li>oboe</li> </ul> </li> </ul> css the .highlight class created below uses a set of css @keyframes to animate a fading outline. .highlight { animation: highlight linear 1s; } @keyframes highlight { from { outline: 1px solid #f00f; } to { outline: 1px solid #f000; } } body { padding: 1px; } javascript document.addeventlistener('pointerup', e => { const selection = window.getselection(); if (selection.type === 'range') { for (let i = 0; i < ...
Range.compareNode() - Web APIs
Web › API › Range › compareNode
ode starts before and ends after the range node_inside (3) node starts after and ends before the range, i.e. the node is completely selected by the range. warning: this method has been removed from gecko 1.9 (firefox 3) and will not exist in future versions of firefox, which was the only browser implementing it; you should switch to range.compareboundarypoints() as soon as possible. ...
Range.getBoundingClientRect() - Web APIs
on the returned value. syntax boundingrect = range.getboundingclientrect() example html <div id="highlight"></div> <p>this example positions a "highlight" rectangle behind the contents of a range. the range's content <b>starts here</b> and continues on until it <b>ends here</b>. ...
Range.selectNodeContents() - Web APIs
e = document.getelementsbytagname("div")[0]; range.selectnodecontents(referencenode); live sample this example lets the user select and deselect a paragraph with buttons. document.createrange(), range.selectnodecontents(), and selection.addrange() are used to select the content. window.getselection() and selection.removeallranges() are used to deselect it. ...
Range.setEnd() - Web APIs
Web › API › Range › setEnd
e start and end points both set to the specified end position. syntax range.setend(endnode, endoffset); parameters endnode the node inside which the range should end. endoffset an integer greater than or equal to zero representing the offset for the end of the range from the start of endnode. return value undefined. exceptions exceptions are thrown as domexception objects of the following types: invalidnodetypeerror the node specified by endnode is a doctype node; range endpoints cannot be located inside a doctype node. indexsizeerror the value specified by endoffset is either greater than or equal to the length of the node or is less than zero. usage notes if the endnode is a node of type text, comment, or cdatasection, then endoffset is the number of characters from ...
Range.setStart() - Web APIs
Web › API › Range › setStart
the range.setstart() method sets the start position of a range. if the startnode is a node of type text, comment, or cdatasection, then startoffset is the number of characters from the start of startnode. for other node types, startoffset is the number of child nodes between the start of the startnode. setting the start point below (lower in the document) the end point will result in a collapsed range with the start and end points both set to the specified start position. syntax range.setstart(startnode, startoffset); parameters startnode the node where the range should start. startoffset an integer greater than or equal to zero representing the offset for the start of the range from the start of startnode. examples highlight part of an element this example uses the range.set...
Range.toString() - Web APIs
Web › API › Range › toString
the range.tostring() method is a stringifier returning the text of the range. alerting the contents of a range makes an implicit tostring() call, so comparing range and text through an alert dialog is ineffective. syntax text = range.tostring(); example html <p>this example logs <b>everything</b> between the bold <b>words</b>. look at the output below.</p> <p id="log"></p> javascript const range = document.createrange(); range.setstartbefore(document.getelementsbytagname('b').item(0), 0); range.setendafter(document.getelementsbytagname('b').item(1), 0); document.getelementbyid('log').textcontent = range.tostring(); result specifications specification status comment domthe definition of 'range.tostring()' in that specification. living standard no ch...
ReadableByteStreamController - Web APIs
byte stream controllers are for byte streams. constructor none. readablebytestreamcontroller instances are created automatically during readablestream construction. properties readablebytestreamcontroller.byobrequest read only returns the current byob pull request. readablebytestreamcontroller.desiredsize read only returns the desired size required to fill the stream's internal queue. methods readablebytestreamcontroller.close() closes the associated stream. ...
ReadableStream.getReader() - Web APIs
readablestreamdefaultreader being created that can read individual chunks from a stream. return value a readablestreamdefaultreader or readablestreambyobreader object instance, depending on the mode value. exceptions rangeerror the provided mode value is not "byob" or undefined. typeerror the stream you are trying to create a reader for is not a readablestream. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). each chunk is read sequentially and output to the ui, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. f...
ReadableStream.pipeThrough() - Web APIs
iping to a closed stream failed, or with any error that occurs during canceling the source. signal: if set to an abortsignal object, ongoing pipe operations can then be aborted via the corresponding abortcontroller. return value the readable side of the transformstream. exceptions typeerror the writable and/or readable property of transformstream are undefined. examples in the following example (see unpack chunks of a png for the full code running live, and png-transform-stream for the source code), an image is fetched and its body retrieved as a readablestream. next, we log the contents of the readable stream, use pipethrough() to send it to a new function that creates a gray-scaled version of the stream, then log the new stream's contents too. // fetch the original image f...
ReadableStreamBYOBReader.read() - Web APIs
the read() method of the readablestreambyobreader interface returns a promise providing access to the next chunk in the byte stream's internal queue. syntax var promise = readablestreambyobreader.read(view); parameters view the view to be read into. return value a promise, which fulfills/rejects with a result depending on the state of the stream. the different possibilities are as follows: if a chunk is available, the promise will be fulfilled with an object of the form { value: thechunk, done: false }. if the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. if the stream becomes errored, the promise will be rejected with the relevant error. exceptions typeerror the source object is not a readablestreamby...
ReadableStreamBYOBReader - Web APIs
the readablestreambyobreader interface of the streams 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...
ReadableStreamBYOBRequest - Web APIs
constructor none. readablestreambyobrequest instance is created automatically by readablebytestreamcontroller as needed. properties readablestreambyobrequest.view read only returns the current view. methods readablestreambyobrequest.respond() xxx readablestreambyobrequest.respondwithnewview() xxx examples tbd. ...
ReadableStreamDefaultController.close() - Web APIs
re read, the stream will become closed. if you want to completely get rid of the stream and discard any enqueued chunks, you'd use readablestream.cancel() or readablestreamdefaultreader.cancel(). syntax readablestreamdefaultcontroller.close(); parameters none. return value undefined. exceptions typeerror the source object is not a readablestreamdefaultcontroller. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream. a cancel() function is also provided to stop the generation if readablestream.cancel() is called for any reason. when a button is pressed, the generation is stopped,...
ReadableStreamDefaultController.enqueue() - Web APIs
the enqueue() method of the readablestreamdefaultcontroller interface enqueues a given chunk in the associated stream. syntax readablestreamdefaultcontroller.enqueue(chunk); parameters chunk the chunk to enqueue. return value undefined. exceptions typeerror the source object is not a readablestreamdefaultcontroller. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream — see controller.enqueue(string). a cancel() function is also provided to stop the generation if readablestream.cancel() is called for any reason. when a button is pressed, the generation is stopped, the stre...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
dablestream.getreader() method. syntax var readablestreamdefaultreader = new readablestreamdefaultreader(stream); parameters stream the readablestream to be read. return value an instance of the readablestreamdefaultreader object. exceptions typeerror the supplied stream parameter is not a readablestream, or it is already locked for reading by another reader. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). each chunk is read sequentially and output to the ui, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. f...
ReadableStreamDefaultReader.cancel() - Web APIs
m.cancel()). syntax var promise = readablestreamdefaultreader.cancel(reason); parameters reason optional a domstring providing a human-readable reason for the cancellation. return value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the source object is not a readablestreamdefaultreader, or the stream has no owner. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (this code is based on our simple random stream example). each chunk is read sequentially and output to the ui, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. w...
ReadableStreamDefaultReader.read() - Web APIs
the read() method of the readablestreamdefaultreader interface returns a promise providing access to the next chunk in the stream's internal queue. syntax var promise = readablestreamdefaultreader.read(); parameters none. return value a promise, which fulfills/rejects with a result depending on the state of the stream. the different possibilities are as follows: if a chunk is available, the promise will be fulfilled with an object of the form { value: thechunk, done: false }. if the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. if the stream becomes errored, the promise will be rejected with the relevant error. exceptions typeerror the source object is not a readablestreamdefaultreader, or the stream has no ...
RelativeOrientationSensor.RelativeOrientationSensor() - Web APIs
he device's physical orientation. 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. syntax var relativeorientationsensor = new relativeorientationsensor([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called. a whole number or decimal may be used, the latter for frequencies less than a second. the actual reading frequency depends device hardware and consequently may be less than requested. referenceframe: either 'device' or 'screen'. the defau...
RelativeOrientationSensor - Web APIs
relativeorientationsensor() creates a new relativeorientationsensor object. properties no specific properties; inherits methods from its ancestors orientationsensor and sensor. event handlers no specific event handlers; inherits methods from its ancestor, sensor. methods no specific methods; inherits methods from its ancestors orientationsensor and sensor. examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an relativeorientationsensor with a frequency of 60 times a second. note that the intel demo this is based on uses the absoluteoreintationsensor. on each reading it uses orientationsensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceframe: 'device' }; const sensor =...
ReportingObserver() - Web APIs
ck a callback function that runs when the observer starts to collect reports (i.e. via reportingobserver.observe()). the callback function is given two parameters: reports: a sequence of report objects representing the reports collected in the observer's report queue. this is probably the most common way to retrieve the reports. observer: a reference to the same reportingobserver object, allowing for recursive report collection, etc. options optional an reportingobserveroptions object allowing you to set the options for creating the object. the available options are: types: an array of strings representing the types of report to be collected by this observer. available types include deprecation, intervention, and crash (although this last type usually isn't retrievable via a ...
ReportingObserver - Web APIs
constructor reportingobserver() creates a new reportingobserver object instance, which can be used to collect and access reports. properties this interface has no properties defined on it. methods reportingobserver.disconnect() stops a reporting observer that had previously started observing from collecting reports. reportingobserver.observe() instructs a reporting observer to start collecting reports in its report queue. reportingobserver.takerecords() returns the current list of reports contained in the observer's report queue, and empties the queue. events this interface has no events that fire on it. ...
ReportingObserverOptions - Web APIs
properties types an array of strings representing the types of report to be collected by this observer. available types include deprecation, intervention, and crash. buffered a boolean that defines whether the reports that were generated before the observer was able to be created should be observable (true) or not (false). ...
Request.integrity - Web APIs
Web › API › Request › integrity
the integrity read-only property of the request interface contains the subresource integrity value of the request. syntax var myintegrity = request.integrity; value the subresource integrity value of the request (e.g., sha256-bpfbw7ivv8q2jlit13fxdyae2tjllusrsz273h2nfse=). if an integrity has not been specified, the property returns ''. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request integrity value in a variable: var myrequest = new request('flowers.jpg'); var myintegrity = myrequest.integrity; specifications specification status comment fetchthe definition of 'integrity' in that specification. living standard initial definit...
Request.method - Web APIs
Web › API › Request › method
the method read-only property of the request interface contains the request's method (get, post, etc.) syntax var mymethod = request.method; value a bytestring indicating the method of the request. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the method of the request in a variable: var myrequest = new request('flowers.jpg'); var mymethod = myrequest.method; // get specifications specification status comment fetchthe definition of 'method' in that specification. living standard initial definition ...
Request.redirect - Web APIs
Web › API › Request › redirect
the redirect read-only property of the request interface contains the mode for how redirects are handled. syntax var myredirect = request.redirect; value a requestredirect enum value, which can be one the following strings: follow error manual if not specified when the request is created, it takes the default value of follow. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request redirect value in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.redirect; specifications specification status comment fetchthe definition of 'redirect' in that specification. living standard initial definition ...
Request.referrer - Web APIs
Web › API › Request › referrer
the referrer read-only property of the request interface is set by the user agent to be the referrer of the request. (e.g., client, no-referrer, or a url.) note: if referrer's value is no-referrer, it returns an empty string. syntax var myreferrer = request.referrer; value a domstring representing the request's referrer. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrer; // returns "about:client" by default specifications specification status comment fetchthe definition of 'referrer' in that specification. living standard i...
Request.url - Web APIs
Web › API › Request › url
the url read-only property of the request interface contains the url of the request. syntax var myurl = request.url; value a usvstring indicating the url of the request. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the url of the request in a variable: var myrequest = new request('flowers.jpg'); var myurl = myrequest.url; // "http://mdn.github.io/fetch-examples/fetch-request/flowers.jpg" specifications specification status comment fetchthe definition of 'url' in that specification. living standard initial definition ...
ResizeObserver.unobserve() - Web APIs
the unobserve() method of the resizeobserver interface ends the observing of a specified element or svgelement. syntax void unobserve(target); parameters target a reference to an element or svgelement to be unobserved. return value void. exceptions none. ...
ResizeObserver - Web APIs
order box minus the padding and border width. 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. it does this by only processing elements deeper in the dom in subsequent frames. implementations should, if they follow the specification, invoke resize events before paint and after layout. constructor resizeobserver() creates and returns a new resizeobserver object. properties none. methods resizeobserver.disconnect() unobserves all observed element targets of a particular observer. resizeobserver.observe() initiates the observing of a specified element. resizeobserver.unobserve() ends the obser...
ResizeObserverEntry.contentBoxSize - Web APIs
or width. inlinesize the length of the observed element's content box in the inline dimension. for boxes with a horizontal writing-mode, this is the horizontal dimension, or width; if the 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. examples the following snippet is taken from the resize-observer-border-radius.html (see source) example. this example includes a green box, sized as a percentage of the viewport size. when the viewport size is changed, the box's rounded corners change in 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; t...
ResizeObserverEntry.contentRect - Web APIs
and may be deprecated in future versions. syntax var contentrect = resizeobserverentry.contentrect; value a domrectreadonly object containing the new size of the element indicated by the target property. if the target is an html element, the returned contentrect is the element's content box. if the target is an svgelement, the returned contentrect is the svg's bounding box. 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 resizeobserverentry.contentboxsize property — if so, it uses that to get the sizing data it needs. if not, it uses contentrect. const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentbo...
ResizeObserverEntry.target - Web APIs
the target read-only property of the resizeobserverentry interface returns a reference to the element or svgelement that is being observed. syntax var element = resizeobserverentry.target; var svgelement = resizeobserverentry.target; value an element or svgelement representing the element being observed. examples the following snippet is taken from the resize-observer-border-radius.html (see source) example. this example includes a green box, sized as a percentage of the viewport size. when the viewport size is changed, the box's rounded corners change in 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 siz...
Response.headers - Web APIs
Web › API › Response › headers
the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response headers value to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.headers); // returns a headers{} object response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'headers' in that specification. living standard init...
Response.ok - Web APIs
Web › API › Response › ok
using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note: at the top of the fetch() block we log the response ok value to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.ok); // returns true if the response returned successfully response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'ok' in that specification. living st...
Response.status - Web APIs
Web › API › Response › status
the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response status value to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.status); // returns 200 response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'status' in that specification. living standard initial definition ...
Response.statusText - Web APIs
request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response statustext value to the console. ...
Response.url - Web APIs
Web › API › Response › url
ect using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response url to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.url); // returns /docs/web/api/response/flowers.jpg response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'url' in that specification. living standard...
SVGAltGlyphDefElement - Web APIs
the svgaltglyphdefelement interface corresponds to the <altglyphdef> element. ...
format - Web APIs
ment.format property is a domstring that defines the format of the given font. it has the same meaning as the 'format' property of svgglyphrefelement property. if the font is in one of the formats listed in css2([css2], section15.3.5), then its value is the corresponding <string> parameter of the font. syntax string = myglyph.format; myglyph.format = string; value the format values listed below are taken from css2([css2], section15.3.5). string font format examples of common extensions truedoc-pfr truedoc™ portable font resource .pfr embedded-opentype embedded opentype .eot type-1 postscript™ type 1 .pfb, .pfa truetype truetype .ttf opentype opentype, including truetype open .ttf ...
SVGAltGlyphItemElement - Web APIs
the svgaltglyphitemelement interface corresponds to the <altglyphitem> element. ...
SVGAnimateColorElement - Web APIs
the svganimatecolorelement interface corresponds to the <animatecolor> element. ...
SVGAnimateElement - Web APIs
the svganimateelement interface corresponds to the <animate> element. ...
SVGAnimateMotionElement - Web APIs
the svganimatemotionelement interface corresponds to the <animatemotion> element. ...
SVGAnimateTransformElement - Web APIs
the svganimatetransformelement interface corresponds to the <animatetransform> element. ...
SVGAnimationElement: beginEvent event - Web APIs
mples animated circle <svg xmlns="http://www.w3.org/2000/svg" width="300px" height="100px"> <title>svg smil animate with path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animatemotion path="m 0 0 h 300 z" dur="5s" repeatcount="indefinite" /> </circle> </svg> <hr> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgelem = document.queryselector('svg'); let animateelem = document.queryselector('animatemotion'); let list = document.queryselector('ul'); animateelem.addeventlistener('beginevent', () => { let listitem = document.createelement('li'); listitem.textcontent = 'beginevent fired'; list.appendchild(listitem); }) animateelem.addeventlistener('repeateve...
SVGAnimationElement: endEvent event - Web APIs
s="http://www.w3.org/2000/svg" width="300px" height="100px"> <title>svg smil animate with path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animatemotion path="m 0 0 h 300 z" dur="5s" repeatcount="indefinite" /> </circle> </svg> <hr> <button>stop animation</button> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgelem = document.queryselector('svg'); let animateelem = document.queryselector('animatemotion'); let list = document.queryselector('ul'); let btn = document.queryselector('button'); animateelem.addeventlistener('beginevent', () => { let listitem = document.createelement('li'); listitem.textcontent = 'beginevent fired'; list.appendchild(listitem); ...
SVGAnimationElement: repeatEvent event - Web APIs
mples animated circle <svg xmlns="http://www.w3.org/2000/svg" width="300px" height="100px"> <title>svg smil animate with path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animatemotion path="m 0 0 h 300 z" dur="5s" repeatcount="indefinite" /> </circle> </svg> <hr> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgelem = document.queryselector('svg'); let animateelem = document.queryselector('animatemotion'); let list = document.queryselector('ul'); animateelem.addeventlistener('beginevent', () => { let listitem = document.createelement('li'); listitem.textcontent = 'beginevent fired'; list.appendchild(listitem); }) animateelem.addeventlistener('repeateven...
SVGAnimationElement - Web APIs
the svganimationelement interface is the base interface for all of the animation element interfaces: svganimateelement, svgsetelement, svganimatecolorelement, svganimatemotionelement and svganimatetransformelement. ...
SVGCircleElement - Web APIs
the svgcircleelement interface is an interface for the <circle> element. ...
SVGClipPathElement - Web APIs
the svgclippathelement interface provides access to the properties of <clippath> elements, as well as methods to manipulate them. ...
SVGComponentTransferFunctionElement - Web APIs
the svgcomponenttransferfunctionelement interface defines a base interface used by the component transfer function interfaces. ...
SVGCursorElement - Web APIs
the svgcursorelement interface 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. ...
SVGDescElement - Web APIs
the svgdescelement interface corresponds to the <desc> element. ...
SVGElement: abort event - Web APIs
this basically implements the standard abort dom event. ...
SVGEllipseElement - Web APIs
the svgellipseelement interface provides access to the properties of <ellipse> elements. ...
SVGExternalResourcesRequired - Web APIs
the svgexternalresourcesrequired interface defines an interface which applies 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. ...
SVGFEColorMatrixElement - Web APIs
the svgfecolormatrixelement interface corresponds to the <fecolormatrix> element. ...
SVGFEComponentTransferElement - Web APIs
the svgfecomponenttransferelement interface corresponds to the <fecomponenttransfer> element. ...
SVGFECompositeElement - Web APIs
the svgfecompositeelement interface corresponds to the <fecomposite> element. ...
SVGFEConvolveMatrixElement - Web APIs
the svgfeconvolvematrixelement interface corresponds to the <feconvolvematrix> element. ...
SVGFEDiffuseLightingElement - Web APIs
the svgfediffuselightingelement interface corresponds to the <fediffuselighting> element. ...
SVGFEDisplacementMapElement - Web APIs
the svgfedisplacementmapelement interface corresponds to the <fedisplacementmap> element. ...
SVGFEDistantLightElement - Web APIs
the svgfedistantlightelement interface corresponds to the <fedistantlight> element. ...
SVGFEDropShadowElement - Web APIs
the svgfedropshadowelement interface corresponds to the <fedropshadow> element. ...
SVGFEFloodElement - Web APIs
the svgfefloodelement interface corresponds to the <feflood> element. ...
SVGFEFuncAElement - Web APIs
the svgfefuncaelement interface corresponds to the <fefunca> element. ...
SVGFEFuncBElement - Web APIs
the svgfefuncbelement interface corresponds to the <fefuncb> element. ...
SVGFEFuncGElement - Web APIs
the svgfefuncgelement interface corresponds to the <fefuncg> element. ...
SVGFEFuncRElement - Web APIs
the svgfefuncrelement interface corresponds to the <fefuncr> element. ...
SVGFEGaussianBlurElement - Web APIs
the svgfegaussianblurelement interface corresponds to the <fegaussianblur> element. ...
SVGFEImageElement - Web APIs
the svgfeimageelement interface corresponds to the <feimage> element. ...
SVGFEMergeElement - Web APIs
the svgfemergeelement interface corresponds to the <femerge> element. ...
SVGFEMergeNodeElement - Web APIs
the svgfemergenodeelement interface corresponds to the <femergenode> element. ...
SVGFEMorphologyElement - Web APIs
the svgfemorphologyelement interface corresponds to the <femorphology> element. ...
SVGFEOffsetElement - Web APIs
the svgfeoffsetelement interface corresponds to the <feoffset> element. ...
SVGFEPointLightElement - Web APIs
the svgfepointlightelement interface corresponds to the <fepointlight> element. ...
SVGFESpecularLightingElement - Web APIs
the svgfespecularlightingelement interface corresponds to the <fespecularlighting> element. ...
SVGFESpotLightElement - Web APIs
the svgfespotlightelement interface corresponds to the <fespotlight> element. ...
SVGFETileElement - Web APIs
the svgfetileelement interface corresponds to the <fetile> element. ...
SVGFETurbulenceElement - Web APIs
the svgfeturbulenceelement interface corresponds to the <feturbulence> element. ...
SVGFilterElement - Web APIs
the svgfilterelement interface provides access to the properties of <filter> elements, as well as methods to manipulate them. ...
SVGFilterPrimitiveStandardAttributes - Web APIs
the svgfilterprimitivestandardattributes interface defines the set of dom attributes that are common across the filter primitive interfaces. ...
SVGFontElement - Web APIs
the svgfontelement interface corresponds to the <font> elements. object-oriented access to the attributes of the <font> element via the svg dom is not possible. ...
SVGFontFaceElement - Web APIs
the svgfontfaceelement interface corresponds to the <font-face> elements. object-oriented access to the attributes of the <font-face> element via the svg dom is not possible. ...
SVGFontFaceFormatElement - Web APIs
the svgfontfaceformatelement interface corresponds to the <font-face-format> elements. object-oriented access to the attributes of the <font-face-format> element via the svg dom is not possible. ...
SVGFontFaceNameElement - Web APIs
the svgfontfacenameelement interface corresponds to the <font-face-name> elements. object-oriented access to the attributes of the <font-face-name> element via the svg dom is not possible. ...
SVGFontFaceSrcElement - Web APIs
the svgfontfacesrcelement interface corresponds to the <font-face-src> elements. object-oriented access to the attributes of the <font-face-src> element via the svg dom is not possible. ...
SVGFontFaceUriElement - Web APIs
the svgfontfaceurielement interface corresponds to the <font-face-uri> elements. object-oriented access to the attributes of the <font-face-uri> element via the svg dom is not possible. ...
SVGForeignObjectElement - Web APIs
the svgforeignobjectelement interface 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. ...
SVGGeometryElement - Web APIs
the svggeometryelement interface represents svg elements whose rendering is defined by geometry with an equivalent path, and which can be filled and stroked. this includes paths and the basic shapes. ...
SVGGlyphElement - Web APIs
the svgglyphelement interface corresponds to the <glyph> element. 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. ...
SVGGradientElement - Web APIs
the svggradient interface is a base interface used by svglineargradientelement and svgradialgradientelement. ...
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. ...
SVGGraphicsElement - Web APIs
the svggraphicselement interface represents svg elements whose primary purpose is to directly render graphics into a group. ...
SVGHKernElement - Web APIs
the svghkernelement interface corresponds to the <hkern> elements. 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. ...
SVGLineElement - Web APIs
the svglineelement interface 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. ...
SVGMPathElement - Web APIs
the svgmpathelement interface corresponds to the <mpath> element. ...
SVGMarkerElement - Web APIs
methods this also inherits methods from its parent, svgelement, and implements properties from svgstylable. setorienttoangle(in svgangle angle) void sets the value of attribute orient to the given angle. exceptions: a domexception with code no_modification_allowed_err is raised when the object itself is read only. setorienttoauto() void sets the value of attribute orient to 'auto'. exceptions: a domexception with code no_modification_allowed_err is raised when the object itself is read only. ...
SVGMaskElement - Web APIs
the svgmaskelement interface provides access to the properties of <mask> elements, as well as methods to manipulate them. ...
SVGMatrix - Web APIs
Web › API › SVGMatrix
s the transformation [1 0 0 -1 0 0] and returns the resulting matrix as svgmatrix. svgmatrix.skewx() post-multiplies a skewx transformation on the current matrix and returns the resulting matrix as svgmatrix. svgmatrix.skewy() post-multiplies a skewy transformation on the current matrix and returns the resulting matrix as svgmatrix. exceptions a domexception with the code no_modification_allowed_err is raised when attempting updating a read-only attribute or when the object itself is read-only. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgmatrix' in that specification. recommendation initial definition ...
SVGMeshElement - Web APIs
the svgmeshelement interface provides access to the properties of <mesh> elements. ...
SVGMetadataElement - Web APIs
the svgmetadataelement interface corresponds to the <metadata> element. ...
SVGMissingGlyphElement - Web APIs
the svgmissingglyphelement interface corresponds to the <missing-glyph> elements. object-oriented access to the attributes of the <missing-glyph> element via the svg dom is not possible. ...
SVGNumber - Web APIs
Web › API › SVGNumber
the svgnumber interface corresponds to the <number> basic data type. an svgnumber object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. properties svgnumber.value a float representing the number. note: if the svgnumber is read-only, a domexception with the code no_modification_allowed_err is raised on an attempt to change the value. methods this interface doesn't provide any specific methods. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgnumber' in that specification. candidate recommendation no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgnumber' in that specification. recommen...
SVGPathElement - Web APIs
the svgpathelement interface corresponds to the <path> element. ...
SVGPatternElement - Web APIs
the svgpatternelement interface corresponds to the <pattern> element. ...
SVGPolygonElement - Web APIs
the svgpolygonelement interface provides access to the properties of <polygon> elements, as well as methods to manipulate them. ...
SVGPolylineElement - Web APIs
the svgpolylineelement interface provides access to the properties of <polyline> elements, as well as methods to manipulate them. ...
SVGPreserveAspectRatio - Web APIs
tion align unsigned short the type of the alignment value as specified by one of the svg_preserveaspectratio_* constants defined on this interface. meetorslice unsigned short the type of the meet-or-slice value as specified by one of the svg_meetorslice_* constants defined on this interface. exceptions on setting: a domexception with code no_modification_allowed_err is raised on an attempt to change the value of an attribute on a read only object. methods the svgpreserveaspectratio interface do not provide any specific methods. 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. ...
SVGRadialGradientElement - Web APIs
the svgradialgradientelement interface corresponds to the <radialgradient> element. ...
SVGRect - Web APIs
Web › API › SVGRect
imum 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. ...
SVGRectElement - Web APIs
the svgrectelement interface provides access to the properties of <rect> elements, as well as methods to manipulate them. ...
SVGRenderingIntent - Web APIs
the svgrenderingintent interface defines the enumerated list of possible values for rendering-intent attributes or descriptors. ...
SVGSetElement - Web APIs
the svgsetelement interface corresponds to the <set> element. ...
SVGSolidcolorElement - Web APIs
the svgsolidcolorelement interface corresponds to the <solidcolor> element. ...
SVGStopElement - Web APIs
the svgstopelement interface corresponds to the <stop> element. ...
SVGSwitchElement - Web APIs
the svgswitchelement interface corresponds to the <switch> element. ...
SVGSymbolElement - Web APIs
the svgsymbolelement interface corresponds to the <symbol> element. ...
SVGTRefElement - Web APIs
the svgtrefelement interface corresponds to the <tref> elements. 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. ...
SVGTextContentElement - Web APIs
svgtextcontentelement interface is implemented by elements that support rendering child text content. it is inherited by various text-related interfaces, such as svgtextelement, svgtspanelement, svgtrefelement, svgaltglyphelement and svgtextpathelement. ...
SVGTextElement - Web APIs
the svgtextelement interface corresponds to the <text> elements. ...
SVGTextPathElement - Web APIs
the svgtextpathelement interface corresponds to the <textpath> element. ...
SVGTextPositioningElement - Web APIs
the svgtextpositioningelement interface is implemented by elements that support attributes that position individual text glyphs. it is inherited by svgtextelement, svgtspanelement, svgtrefelement and svgaltglyphelement. ...
SVGTitleElement - Web APIs
the svgtitleelement interface corresponds to the <title> element. ...
SVGURIReference - Web APIs
the svgurireference interface is used to reflect the href attribute and the deprecated xlink:href attribute. ...
SVGUnitTypes - Web APIs
the svgunittypes interface defines a commonly used 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. ...
SVGVKernElement - Web APIs
the svgvkernelement interface corresponds to the <vkern> elements. object-oriented access to the attributes of the <vkern> element via the svg dom is not possible. ...
SVGZoomAndPan - Web APIs
the svgzoomandpan interface is used to reflect the zoomandpan attribute, and is mixed in to other interfaces for elements that support this attribute. ...
Screen.colorDepth - Web APIs
Web › API › Screen › colorDepth
the screen.colordepth read-only property returns the color depth of the screen. per the cssom, some implementations return 24 for compatibility reasons. see the browser compatibility section for those that don't. syntax bitdepth = window.screen.colordepth; example // check the color depth of the screen if ( window.screen.colordepth < 8) { // use low-color version of page } else { // use regular, colorful page } specification specification status comment css object model (cssom) view modulethe definition of 'screen.colordepth' in that specification. working draft ...
Screen.lockOrientation() - Web APIs
the lockorientation() method of the screen interface locks the screen into a specified orientation. the screenorientation.lock() method should be used instead. note: this method only works for installed web apps or for web pages in full-screen mode. syntax lockallowed = window.screen.lockorientation(orientation); parameters orientation the orientation into which to lock the screen. this is either a string or an array of strings. passing several strings lets the screen rotate only in the selected orientations. the following strings represent the possible orientation requirements you may specify: portrait-primary it represents the orientation of the screen when it is in its primary portrait mode. a screen is considered in its primary portrait mode if the device is held in its...
Screen - Web APIs
Web › API › Screen
event() dispatches an event to this eventtarget. additional methods in mozilla chrome codebase mozilla includes a couple of extensions for use by js-implemented event targets to implement onevent properties. see also webidl bindings. void seteventhandler(domstring type, eventhandler handler) eventhandler geteventhandler(domstring type) example if (screen.pixeldepth < 8) { // use low-color version of page } else { // use regular, colorful page } specification specification status comment css object model (cssom) view modulethe definition of 'screen' in that specification. working draft initial definition. ...
ScreenOrientation.lock() - Web APIs
specifications specification status comment screen orientation apithe definition of 'lock()' in that specification. ...
ScriptProcessorNode.bufferSize - Web APIs
kers. the buffersize property of the scriptprocessornode interface returns an integer representing both the input and output buffer size, in sample-frames. its value can be a power of 2 value in the range 256–16384. syntax var audioctx = new audiocontext(); var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); value an integer. example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through ea...
ScriptProcessorNode.onaudioprocess - Web APIs
criptprocessornode interface represents the eventhandler to be called for the audioprocess event that is dispatched to scriptprocessornode node types. an event of type audioprocessingevent will be dispatched to the event handler. syntax var audioctx = new audiocontext(); var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); scriptnode.onaudioprocess = function() { ... } example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through ea...
ScrollToOptions.behavior - Web APIs
the behavior property of the scrolltooptions dictionary specifies whether the scrolling should animate smoothly, or happen instantly in a single jump. this is actually defined on the scrolloptions dictionary, which is implemented by scrolltooptions. syntax behavior: scrollbehavior value an enum, the value of which can be one of the following: smooth: the scrolling animates smoothly. auto: the scrolling happens in a single jump. examples in our scrolltooptions example (see it live) we include a form that allows the user to enter three values — two numbers representing the left and top properties (i.e. the positions to scroll to along the x and y axes), and a checkbox indicating whether they want smooth scrolling enabled or not. when the form is submitted, an event handler is ...
ScrollToOptions.left - Web APIs
the positions to scroll to along the x and y axes), and a checkbox indicating whether they want smooth scrolling enabled or not. ...
ScrollToOptions.top - Web APIs
the positions to scroll to along the x and y axes), and a checkbox indicating whether they want smooth scrolling enabled or not. ...
SecurityPolicyViolationEvent.SecurityPolicyViolationEvent() - Web APIs
tes a new securitypolicyviolationevent 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 s...
Selection.deleteFromDocument() - Web APIs
. syntax sel.deletefromdocument() parameters none. example this example lets you delete selected text by clicking a button. upon clicking the button, the window.getselection() method gets the selected text, and the deletefromdocument() method removes it. html <p>try highlighting some of the text in this paragraph. ...
Selection.rangeCount - Web APIs
nly property returns the number of ranges in the selection. before the user has clicked a freshly loaded page, the rangecount is 0. after the user clicks on the page, rangecount is 1, even if no selection is visible. a user can normally only select one range at a time, so the rangecount will usually be 1. scripting can be used to make the selection contain more than one range. gecko browsers allow multiple selections across table cells. firefox allows to select multiple ranges in the document by using ctrl+click (unless the click within an element with display: table-cell). syntax value = sel.rangecount example the following example will show the rangecount every second. select text in the browser to see it change. html <table> <tr><td>a.1<td>a.2 <tr><td>b.1<td>b.2 <tr><td>c.1...
Sensor - Web APIs
Web › API › Sensor
rface cannot be used directly. instead it provides properties, event handlers, and methods accessed by interfaces that inherit from it. 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. interfaces based on sensor below is a list of interfaces based on the sensor interface. accelerometer ambientlightsensor gyroscope linearaccelerationsensor magnetometer orientationsensor properties sensor.activated read only returns a boolean indicating whether the sensor is active. sensor.hasreading read only returns a boolean indicating whether the sensor has a reading. sensor.timestamp read only returns...
ServiceWorker.state - Web APIs
syntax someurl = serviceworker.state value a serviceworkerstate definition (see the spec.) 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. ...
ServiceWorker - Web APIs
operties the serviceworker interface inherits properties from its parent, worker. serviceworker.scripturl read only returns the serviceworker serialized script url defined as part of serviceworkerregistration. the url must be on the same origin as the document that registers the serviceworker. serviceworker.state read only returns the state of the service worker. it returns one of 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 — ...
ServiceWorkerContainer.startMessages() - Web APIs
sent via client.postmessage()). this can be used to react to sent messages earlier, even before that page's content has finished loading. explanation by default, all messages sent from a page's controlling service worker to the page (using client.postmessage()) are queued while the page is loading, and get dispatched once the page's html document has been loaded and parsed (i.e. after the domcontentloaded event fires). ...
ServiceWorkerContainer - Web APIs
document url. the method returns a promise that resolves to a serviceworkerregistration or undefined. serviceworkercontainer.getregistrations() returns all serviceworkerregistration objects associated with a serviceworkercontainer in an array. the method returns a promise that resolves to an array of serviceworkerregistration. serviceworkercontainer.startmessages() explicitly 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 acti...
ServiceWorkerGlobalScope: activate event - Web APIs
the activate event of the serviceworkerglobalscope interface is fired when a serviceworkerregistration acquires a new serviceworkerregistration.active worker. bubbles no cancelable no interface extendableevent event handler property serviceworkerglobalscope.onactivate examples the following snippet shows how you could use an activate event handler to upgrade a cache. globalscope.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waituntil( caches.foreach(function(cache, cachename) { if (cachewhitelist.indexof(cachename) == -1) { return caches.delete(cachename); } }) ); }); you can also set up the event handler using the serviceworkerglobalscope.onactivate property: gl...
ServiceWorkerGlobalScope: contentdelete event - Web APIs
the contentdelete event of the serviceworkerglobalscope interface is fired when an item is removed from the indexed content via the user agent. bubbles no cancelable no interface contentindexevent event handler property oncontentdelete examples the following example uses a contentdelete event handler to remove cached content related to the deleted index item. self.addeventlistener('contentdelete', event => { event.waituntil( caches.open('cache-name').then(cache => { return promise.all([ cache.delete(`/icon/${event.id}`), cache.delete(`/content/${event.id}`) ]) }) ); }); you can also set up the event handler using the serviceworkerglobalscope.ondelete property: s...
ServiceWorkerGlobalScope: install event - Web APIs
the install event of the serviceworkerglobalscope interface is fired when a serviceworkerregistration acquires a new serviceworkerregistration.installing worker. ...
ServiceWorkerGlobalScope: message event - Web APIs
ceived. 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. // in the page being controlled if (navigator.serviceworker) { navigator.serviceworker.register('service-worker.js'); navigator.serviceworker.addeventlistener('message', event => { // event is a messageevent object console.log(`the service worker...
ServiceWorkerGlobalScope.onactivate - Web APIs
the onactivate property of the serviceworkerglobalscope interface is an event handler fired whenever an activate event occurs (when the service worker activates). this happens after installation, when the page to be controlled by the service worker refreshes. syntax serviceworkerglobalscope.onactivate = function(event) { ... }; examples the following snippet shows how you could use an activate event handler to upgrade a cache. then.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waituntil( caches.foreach(function(cache, cachename) { if (cachewhitelist.indexof(cachename) == -1) { return caches.delete(cachename); } }) ); }); specifications specification status comment service workersthe definit...
ServiceWorkerGlobalScope.oncontentdelete - Web APIs
the oncontentdelete property of the serviceworkerglobalscope interface is an event handler fired when an item is removed from the indexed content via the user agent. syntax serviceworkerglobalscope.oncontentdelete = function(event) { ... }; examples the following example uses a contentdelete event handler to remove cached content related to the deleted index item. self.addeventlistener('contentdelete', event => { event.waituntil( caches.open('cache-name').then(cache => { return promise.all([ cache.delete(`/icon/${event.id}`), cache.delete(`/content/${event.id}`) ]) }) ); }); specifications specification status comment unknownthe definition of 'contentdelete' in that specification. unknown initial defini...
ServiceWorkerGlobalScope.oninstall - Web APIs
the oninstall property of the serviceworkerglobalscope interface is an event handler fired whenever an install event occurs (when the service worker installs). this happens before activation. syntax serviceworkerglobalscope.oninstall = function(event) { ... ...
ServiceWorkerGlobalScope.onmessage - Web APIs
for the message event, service workers use the extendablemessageevent interface which extends the extendableevent interface. note: messages received from service worker contexts (e.g. ...
ServiceWorkerGlobalScope.onpush - Web APIs
the serviceworkerglobalscope.onpush event of the serviceworkerglobalscope interface is fired whenever a push message is received by a service worker via a push server. syntax serviceworkerglobalscope.onpush = function(pushevent) { ... } self.addeventlistener('push', function(pushevent) { ... }) example the following example takes data from a pushevent and displays it on all of the service worker's clients. the data payload of the push message is available in the event object's data property (pushevent.data, which contains a pushmessagedata object.) self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "...
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
do something }); returns a promise that immediately resolves with undefined. example while self.skipwaiting() can be called at any point during the service worker's execution, it will only have an effect if there's a newly installed service worker that might otherwise remain in the waiting state. therefore, it's common to call self.skipwaiting() from inside of an installevent handler. the following example causes a newly installed service worker to progress into the activating state, regardless of whether there is already an active service worker. self.addeventlistener('install', function(event) { // the promise that skipwaiting() returns can be safely ignored. self.skipwaiting(); // perform any other actions required for your // service worker to install, potentially inside ...
ServiceWorkerMessageEvent.ServiceWorkerMessageEvent() - Web APIs
ageevent interface, for consistency with other web messaging features. the serviceworkermessageevent() constructor creates a new serviceworkermessageevent object instance. syntax var myswme = new serviceworkermessageevent(type, init); parameters type a domstring that defines the type of the message event being created. init optional an initialisation object, which should contain the following parameters: data: the event's data — this can be any type. origin: a domstring that defines the origin of the corresponding service worker's environment settings object. lasteventid: a domstring that defines the last event id of the event source. source: the serviceworker or messageport that sent the message. ports: an array containing the messageport objects connected to the cha...
ServiceWorkerMessageEvent.data - Web APIs
modern browsers, this property has been deprecated. service worker messages will now use the messageevent interface, for consistency with other web messaging features. the data read-only property of the serviceworkermessageevent interface returns the event's data. it can be any data type. syntax var mydata = serviceworkermessageeventinstance.data; value any data type. examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent. navigator.serviceworker.ready.then(function(reg) { ... // set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = ...
ServiceWorkerMessageEvent.lastEventId - Web APIs
precated. service worker messages will now use the messageevent interface, for consistency with other web messaging features. the lasteventid read-only property of the serviceworkermessageevent interface represents, in server-sent events, the last event id of the event source. syntax var mylasteventid = serviceworkermessageeventinstance.lasteventid; value a domstring. examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent. navigator.serviceworker.ready.then(function(reg) { ... // set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = ...
ServiceWorkerMessageEvent.origin - Web APIs
perty has been deprecated. service worker messages will now use the messageevent interface, for consistency with other web messaging features. the origin read-only property of the serviceworkermessageevent interface returns the origin of the service worker's environment settings object. syntax var myorigin = serviceworkermessageeventinstance.origin; value a domstring. examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent. navigator.serviceworker.ready.then(function(reg) { ... // set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = ...
ServiceWorkerMessageEvent.ports - Web APIs
now use the messageevent interface, for consistency with other web messaging features. the ports read-only property of the serviceworkermessageevent interface returns an array of messageport objects connected with the message channel the message is being sent through. syntax var myports = serviceworkermessageeventinstance.ports; value an array of messageport objects. examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent. navigator.serviceworker.ready.then(function(reg) { ... // set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = ...
ServiceWorkerMessageEvent.source - Web APIs
es will now use the messageevent interface, for consistency with other web messaging features. the source read-only property of the serviceworkermessageevent returns a reference to the serviceworker object of the associated service worker that sent the message. syntax var mysource = serviceworkermessageeventinstance.source; value a serviceworker or messageport object. examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent. navigator.serviceworker.ready.then(function(reg) { ... // set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = ...
ServiceWorkerRegistration.index - Web APIs
syntax var a contentindex object = serviceworkerregistration.index; value a contentindex object examples you can access the property from either your main script or the registered service worker. ...
ServiceWorkerRegistration.unregister() - Web APIs
ercontainer.register() with the same scope.) the service worker will finish any ongoing operations before it is unregistered. note: this feature is available in web workers. syntax serviceworkerregistration.unregister().then(function(boolean) { }); parameters none. return value promise resolves with a boolean indicating whether the service worker has unregistered or not. ...
ServiceWorkerRegistration.update() - Web APIs
rker is not byte-by-byte identical to the current worker, it installs the new worker. the fetch of the worker bypasses any browser caches if the previous fetch occurred over 24 hours ago. note: this feature is available in web workers. syntax serviceworkerregistration.update(); parameters none. return value a promise that resolves with a serviceworkerregistration object. ...
SharedWorker.port - Web APIs
Web › API › SharedWorker › port
the port property of the sharedworker interface returns a messageport object used to communicate and control the shared worker. syntax myworker.port; value a messageport object. example the following code snippet shows creation of a sharedworker object using the sharedworker() constructor. multiple scripts can then access the worker through a messageport object accessed using the sharedworker.port property — the port is started using its start() method: var myworker = new sharedworker('worker.js'); myworker.port.start(); for a full example, see our basic shared worker example (run shared worker.) specifications specification status comment html living standardthe definition of 'abstractworker.onerror' in that specification. living standard ...
SharedWorker - Web APIs
s parent, eventtarget, and implements methods from abstractworker. example in our basic shared worker example (run shared worker), we have two html pages, each of which uses some javascript to perform a simple calculation. the different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows. the following code snippet shows creation of a sharedworker object using the sharedworker() constructor. both scripts contain this: var myworker = new sharedworker('worker.js'); both scripts then access the worker through a messageport object created using the sharedworker.port property. if the onmessage event is attached using addeventlistener, the port is manually started using its start() method: myw...
SharedWorkerGlobalScope.close() - Web APIs
the close() method of the sharedworkerglobalscope interface discards any tasks queued in the sharedworkerglobalscope's event loop, effectively 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 - Web APIs
ers, windowbase64, and windoweventhandlers. sharedworkerglobalscope.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 ...
Slottable - Web APIs
Web › API › Slottable
properties slottable.assignedslot read only returns the <slot> the node is inserted in. methods none. specifications specification status comment domthe definition of 'slottable' in that specification. living standard 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. ...
SourceBuffer.appendWindowEnd - Web APIs
he sourcebuffer. coded media frames with timestamps wthin this range will be appended, whereas those outside the range will be filtered out. the default value of appendwindowend is positive infinity. syntax var myappendwindowend = sourcebuffer.appendwindowend; sourcebuffer.appendwindowend = 120.0; value a double, indicating the end time of the append window, in seconds. exceptions the following exceptions may be thrown when setting a new value for this property. exception explanation invalidaccesserror an attempt was made to set the value to less than or equal to sourcebuffer.appendwindowstart, or nan. invalidstateerror this sourcebuffer object is being updated (i.e. its sourcebuffer.updating property is currently true), or this sourcebuffer h...
SourceBuffer.appendWindowStart - Web APIs
will be appended, whereas those outside the range will be filtered out. the default value of appendwindowstart is the presentation start time, which is the beginning time of the playable media. syntax var myappendwindowstart = sourcebuffer.appendwindowstart; sourcebuffer.appendwindowstart = 2.0; value a double, indicating the start time of the append window, in seconds. exceptions the following exceptions may be thrown when setting a new value for this property. exception explanation invalidaccesserror an attempt was made to set the value to less than 0, or a value greater than or equal to sourcebuffer.appendwindowend. invalidstateerror this sourcebuffer object is being updated (i.e. its sourcebuffer.updating property is currently true), or th...
SourceBuffer.mode - Web APIs
Web › API › SourceBuffer › mode
uence mode. you can, however, change the value from segments to sequence. it just means the play order will be fixed, and new timestamps generated to reflect this. this property cannot be changed during while the sourcebuffer is processing either an appendbuffer() or remove() call. syntax var mymode = sourcebuffer.mode; sourcebuffer.mode = 'sequence'; value a domstring. exceptions the following exceptions may be thrown when setting a new value for this property. exception explanation invalidaccesserror an attempt was made to set the value to segments when the initial value is sequence. invalidstateerror the sourcebuffer object is being updated (i.e. its sourcebuffer.updating property is currently true), the last media segment appended to this ...
SourceBuffer.timestampOffset - Web APIs
the timestampoffset property of the sourcebuffer interface controls the offset applied to timestamps inside media segments that are appended to the sourcebuffer. the initial value of timestampoffset is 0. syntax var myoffset = sourcebuffer.timestampoffset; sourcebuffer.timestampoffset = 2.5; value a double, with the offset amount expressed in seconds. exceptions the following exceptions may be thrown when setting a new value for this property. exception explanation invalidstateerror one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e. their sourcebuffer.updating property is currently true), a media segment inside the sourcebuffer is currently being parsed, or this sourcebuffer has been removed from the m...
SourceBuffer.trackDefaults - Web APIs
the trackdefaults property of the sourcebuffer interface specifies the default values to use if kind, label, and/or language information is not available in the initialization segment of the media to be appended to the sourcebuffer. syntax var mytrackdefaults = sourcebuffer.trackdefaults; sourcebuffer.trackdefaults = mytrackdefaultlist; value a trackdefaultlist object. exceptions the following exceptions may be thrown when setting a new value for this property. exception explanation invalidstateerror one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e. their sourcebuffer.updating property is currently true), or this sourcebuffer has been removed from the mediasource. example tbd ...
SourceBufferList: indexed property getter - Web APIs
[].) syntax var mysourcebuffer = sourcebufferlist[index]; parameters index the index position of the sourcebuffer object you want to return. return value a sourcebuffer object. exceptions no specific exceptions are thrown, but if the supplied index is great than or equal to sourcebufferlist.length, the operation will return undefined. example tbd. ...
SpeechGrammar.SpeechGrammar() - Web APIs
= aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var newgrammar = new speechgrammar(); newgrammar.src = '#jsgf v1.0; grammar names; public <name> = chris | kirsty | mike;' speechrecognitionlist[1] = newgrammar; // should add the new speechgrammar object...
SpeechGrammar.src - Web APIs
Web › API › SpeechGrammar › src
= aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; console.log(speechrecognitionlist[0].src); // should return the same as the contents of the grammar variable console.log(speechrecognitionlist[0].weight); // should return 1 - the same as the weight set ...
SpeechGrammar.weight - Web APIs
= aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; console.log(speechrecognitionlist[0].src); // should return the same as the contents of the grammar variable console.log(speechrecognitionlist[0].weight); // should return 1 - the same as the weight set ...
SpeechGrammar - Web APIs
= aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; console.log(speechrecognitionlist[0].src); // should return the same as the contents of the grammar variable console.log(speechrecognitionlist[0].weight); // should return 1 - the same as the weight set ...
SpeechGrammarList.SpeechGrammarList() - Web APIs
draft ...
SpeechGrammarList.addFromString() - Web APIs
draft ...
SpeechGrammarList.addFromURI() - Web APIs
specifications specification status comment web speech apithe defin...
SpeechGrammarList.length - Web APIs
specifications specification status comment web speech apithe definition of 'length' in that specification. draft ...
SpeechRecognition() - Web APIs
specifications specification status comment ...
SpeechRecognition.abort() - Web APIs
= aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); document.body.onclick = function() { recognition.start(); console.log('ready to receive a color command.')...
SpeechRecognition.continuous - Web APIs
specifications specification status comment w...
SpeechRecognition.grammars - Web APIs
specifications specification status comment ...
SpeechRecognition.interimResults - Web APIs
specifications specification status comment ...
SpeechRecognition.lang - Web APIs
specifications specification status comment ...
SpeechRecognition.maxAlternatives - Web APIs
specifications specification status comment ...
SpeechRecognition.start() - Web APIs
= aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); document.body.onclick = function() { recognition.start(); console.log('ready to receive a color command.')...
SpeechRecognition.stop() - Web APIs
= aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); document.body.onclick = function() { recognition.start(); console.log('ready to receive a color command.')...
SpeechRecognition - Web APIs
= aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; var diagnostic = document.queryselector('.output'); var bg = document.query...
SpeechRecognitionEvent.results - Web APIs
the results read-only property of the speechrecognitionevent interface returns a speechrecognitionresultlist object representing all the speech recognition results for the current session. specifically this object will contain all final results that have been returned, followed by the current best hypothesis for all interim results. when subsequent result events are fired, interim results may be overwritten by a newer interim result or by a final result — they may even be removed, if they are at the end of the "results" array and the array length decreases. final results on the other hand will not be overwritten or removed. syntax var myresults = event.results; value a speechrecognitionresultlist object. examples this code is excerpted from our speech color changer examp...
SpeechRecognitionEvent - Web APIs
s speechrecognitionevent also inherits properties from its parent interface, event. speechrecognitionevent.emma read only returns an extensible multimodal annotation markup language (emma) — xml — representation of the result. speechrecognitionevent.interpretation read only returns the semantic meaning of what the user said. speechrecognitionevent.resultindex read only returns the lowest index value result in the speechrecognitionresultlist "array" that has actually changed. speechrecognitionevent.results read only returns a speechrecognitionresultlist object representing all the speech recognition results for the current session. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitioneve...
SpeechRecognitionResult.item() - Web APIs
syntax var myalternative = speechrecognitionresultinstance[0]; returns a speechrecognitionalternative object. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0. ...
SpeechRecognitionResult - Web APIs
this is the final time this result will be returned; if not, then this result is an interim result, and may be updated later on. speechrecognitionresult.length read only returns the length of the "array" — the number of speechrecognitionalternative objects contained in the result (also referred to as "n-best alternatives".) methods speechrecognitionresult.item a standard getter that allows speechrecognitionalternative objects within the result to be accessed via array syntax. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a ...
SpeechRecognitionResultList.item() - Web APIs
syntax var myresult = speechrecognitionresultlistinstance[0]; returns a speechrecognitionresult object. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0. ...
SpeechRecognitionResultList - Web APIs
nitionresultlist interface of the web speech api represents a list of speechrecognitionresult objects, or a single one if results are being captured in continuous mode. properties speechrecognitionresultlist.length read only returns the length of the "array" — the number of speechrecognitionresult objects in the list. methods speechrecognitionresultlist.item a standard getter that allows speechrecognitionresult objects in the list to be accessed via array syntax. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so i...
SpeechSynthesis.onvoiceschanged - Web APIs
ples 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 of voices when speechsynthesis.getvoices() is fired. with chrome however, you have to wait for the event to fire before populating the list, hence the bottom if statement seen below. var voices = []; function populatevoicelist() { voices = synth.getvoices(); for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribut...
SpeechSynthesisUtterance.SpeechSynthesisUtterance() - Web APIs
the speechsynthesisutterance() constructor of the speechsynthesisutterance interface returns a new speechsynthesisutterance object instance. syntax var utterthis = new speechsynthesisutterance(text); parameters text a domstring containing the text that will be synthesized when the utterance is spoken.. examples the following snippet is excerpted from our speech synthesizer demo. 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.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selecte...
SpeechSynthesisUtterance.pitch - Web APIs
the pitch property of the speechsynthesisutterance interface 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.ge...
SpeechSynthesisUtterance.rate - Web APIs
the rate property of the speechsynthesisutterance interface gets and sets the speed at which the utterance will be spoken at. if unset, a default value of 1 will be used. syntax var myrate = speechsynthesisutteranceinstance.rate; speechsynthesisutteranceinstance.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 ...
SpeechSynthesisUtterance.volume - Web APIs
the volume property of the speechsynthesisutterance interface gets and sets the volume that the utterance will be spoken at. if not set, the default value 1 will be used. syntax var myvolume = speechsynthesisutteranceinstance.volume; speechsynthesisutteranceinstance.volume = 0.5; value a float that represents the volume value, between 0 (lowest) and 1 (highest.) 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.preventdefault(); var utterthis = new speechsynthesisut...
SpeechSynthesisVoice.localService - Web APIs
the localservice read-only property of the speechsynthesisvoice interface returns a boolean indicating whether the voice is supplied by a local speech synthesizer service (true), or a remote speech synthesizer service (false.) this property is provided to allow differentiation in the case that some voice options are provided by a remote service; it is possible that remote voices might have extra latency, bandwidth or cost associated with them, so such distinction may be useful. syntax var amilocal = speechsynthesisvoiceinstance.localservice; value a boolean. examples for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += '...
SpeechSynthesisVoice - Web APIs
read only a boolean indicating whether the voice is supplied by a local speech synthesizer service (true), or a remote speech synthesizer service (false.) speechsynthesisvoice.name read only returns a human-readable name that represents the voice. speechsynthesisvoice.voiceuri read only returns the type of uri and location of the speech synthesis service for this voice. examples the following snippet is excerpted from our speech synthesiser demo. function populatevoicelist() { voices = synth.getvoices(); for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.setattribute('data-lang', ...
StereoPannerNode.StereoPannerNode() - Web APIs
of the web audio api creates a new stereopannernode object which is an audionode that represents a simple stereo panner node that can be used to pan an audio stream left or right. syntax var stereopannernode = stereopannernode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options optional options are as follows: pan: a floating point number in the range [-1,1] indicating the position of an audionode in an output image. the value -1 represents full left and 1 represents full right. the default value is 0. return value a new stereopannernode object instance. specifications specification status comment web audio apithe definition of 'stereopannernode()' in that specifi...
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. ...
Storage.clear() - Web APIs
Web › API › Storage › clear
function populatestorage() { localstorage.setitem('bgcolor', 'red'); localstorage.setitem('font', 'helvetica'); localstorage.setitem('image', 'migato.png'); localstorage.clear(); } note: for a real world example, see our web storage demo. ...
Storage.getItem() - Web APIs
Web › API › Storage › getItem
erface, when passed a key name, will return that key's value, or null if the key does not exist, in the given storage object. syntax var avalue = storage.getitem(keyname); parameters keyname a domstring containing the name of the key you want to retrieve the value of. return value a domstring containing the value of the key. if the key does not exist, null is returned. example the following function retrieves three data items from local storage, then uses them to set custom styles on a page. function setstyles() { var currentcolor = localstorage.getitem('bgcolor'); var currentfont = localstorage.getitem('font'); var currentimage = localstorage.getitem('image'); document.getelementbyid('bgcolor').value = currentcolor; document.getelementbyid('font').value = currentfont...
Storage.length - Web APIs
Web › API › Storage › length
the length read-only property of the storage interface returns the number of data items stored in a given storage object. syntax length = storage.length; return value the number of items stored in the storage object. example the following function adds three data items to the local storage for the current domain, then returns the number of items in the storage: function populatestorage() { localstorage.setitem('bgcolor', 'yellow'); localstorage.setitem('font', 'helvetica'); localstorage.setitem('image', 'cats.png'); return localstorage.length; // should return 3 } note: for a real world example, see our web storage demo. specifications specification status comment html living standardthe definition of 'storage.length' in that specification. liv...
Storage.removeItem() - Web APIs
he given storage object if it exists. the storage interface of the web storage api provides access to a particular domain's session or local storage. if there is no item associated with the given key, this method will do nothing. syntax storage.removeitem(keyname); parameters keyname a domstring containing the name of the key you want to remove. return value undefined. example the following function creates three data items inside local storage, then removes the image data item. function populatestorage() { localstorage.setitem('bgcolor', 'red'); localstorage.setitem('font', 'helvetica'); localstorage.setitem('image', 'mycat.png'); localstorage.removeitem('image'); } we can do the same for the session storage. function populatestorage() { sessionstorage.setitem('bgc...
Storage.setItem() - Web APIs
Web › API › Storage › setItem
you want to create/update. keyvalue a domstring containing the value you want to give the key you are creating/updating. return value undefined. exceptions setitem() may throw an exception if the storage is full. particularly, in mobile safari (since ios 5) it always throws when the user enters private mode. (safari sets the quota to 0 bytes in private mode, unlike other browsers, which allow storage in private mode using separate data containers.) hence developers should make sure to always catch possible exceptions from setitem(). example the following function creates three data items inside local storage. function populatestorage() { localstorage.setitem('bgcolor', 'red'); localstorage.setitem('font', 'helvetica'); localstorage.setitem('image', 'mycat.png'); } note: to ...
Storage - Web APIs
Web › API › Storage
to manipulate, for instance, the session storage for a domain, a call to window.sessionstorage is made; whereas for local storage the call is made to window.localstorage. properties storage.length read only returns an integer representing the number of data items stored in the storage object. methods storage.key() when passed a number n, this method will return the name of the nth key in the storage. ...
StorageEvent - Web APIs
a storageevent is sent to a window when a storage area it has access to is changed within the context of another document. ...
Using writable streams - Web APIs
like this: const stream = new writablestream({ start(controller) { }, write(chunk,controller) { }, close(controller) { }, abort(reason) { } }, { highwatermark, size() }); the constructor takes two objects as parameters. the first object is required, and creates a model in javascript of the underlying sink the data is being written to. the second object is optional, and allows you to specify a custom queueing strategy to use for your stream, which takes the form of an instance of bytelengthqueuingstrategy or countqueuingstrategy. the first object can contain up to four members, all of which are optional: start(controller) — a method that is called once, immediately after the writablestream is constructed. inside this method, you should include code that sets up ...
StylePropertyMap - Web APIs
the stylepropertymap interface of the the css typed object model api provides a representation of a css declaration block that is an alternative to cssstyledeclaration. ...
SubmitEvent - Web APIs
defines the object used to represent an html form's submit event. this event is fired at the <form> when the form's submit action is invoked. constructor submitevent() creates and returns a new submitevent object whose type and other options are configured as specified. note that currently, the only valid type for a submitevent is submit. properties in addition to the properties listed below, this interface inherits the properties of its parent interface, event. submitter read only an htmlelement 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 assortm...
SubtleCrypto.decrypt() - Web APIs
rams object. key is a cryptokey containing the key to be used for decryption. if using rsa-oaep, this is the privatekey property of the cryptokeypair object. data is a buffersource containing the data to be decrypted (also known as ciphertext). return value result is a promise that fulfills with an arraybuffer containing the plaintext. exceptions the promise is rejected when the following exceptions are encountered: invalidaccesserror raised when the requested operation is not valid for the provided key (e.g. invalid encryption algorithm, or invalid key for the specified encryption algorithm). operationerror raised when the operation failed for an operation-specific reason (e.g. algorithm parameters of invalid sizes, or there was an error decrypting the ciphertext). sup...
SubtleCrypto.encrypt() - Web APIs
aes-cbc, pass an aescbcparams object. to use aes-gcm, pass an aesgcmparams object. key is a cryptokey containing the key to be used for encryption. data is a buffersource containing the data to be encrypted (also known as the plaintext). return value result is a promise that fulfills with an arraybuffer containing the "ciphertext". exceptions the promise is rejected when the following exceptions are encountered: invalidaccesserror raised when the requested operation is not valid for the provided key (e.g. invalid encryption algorithm, or invalid key for the specified encryption algorithm). operationerror raised when the operation failed for an operation-specific reason (e.g. algorithm parameters of invalid sizes, or aes-gcm plaintext longer than 2³⁹−256 bytes)...
SubtleCrypto.generateKey() - Web APIs
vekey: the key may be used in deriving a new key. derivebits: the key may be used in deriving bits. wrapkey: the key may be used to wrap a key. unwrapkey: the key may be used to unwrap a key. return value result is a promise that fulfills with a cryptokey (for symmetric algorithms) or a cryptokeypair (for public-key algorithms). exceptions the promise is rejected when the following exception is encountered: syntaxerror raised when the result is a cryptokey of type secret or private but keyusages is empty. syntaxerror raised when the result is a cryptokeypair and its privatekey.usages attribute is empty. examples note: you can try the working examples on github. rsa key pair generation this code generates an rsa-oaep encryption key pair. see the complete code...
SubtleCrypto.sign() - Web APIs
Web › API › SubtleCrypto › sign
": "hmac" }. key is a cryptokey object containing the key to be used for signing. if algorithm identifies a public-key cryptosystem, this is the private key. data is an arraybuffer or arraybufferview object containing the data to be signed. return value signature is a promise that fulfills with an arraybuffer containing the signature. exceptions the promise is rejected when the following exception is encountered: invalidaccesserror raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. supported algorithms the web crypto api provides four algorithms that can be used for signing and signature verification. three of these algorithms — rsassa-pkcs1-v1_5, rsa-pss,...
SubtleCrypto.verify() - Web APIs
it is the secret key for a symmetric algorithm and the public key for a public-key system. signature is a arraybuffer containing the signature to verify. data is a arraybuffer containing the data whose signature is to be verified. return value result is a promise that fulfills with a boolean: true if the signature is valid, false otherwise. exceptions the promise is rejected when the following exception is encountered: invalidaccesserror raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. supported algorithms the verify() method supports the same algorithms as the sign() method. examples note: you can try the working examples out on github. rs...
SyncEvent.SyncEvent() - Web APIs
the syncevent() constructor creates a new syncevent object. syntax var mysyncevent = new syncevent(type, init) parameters type the type of the event. init optional an options object containing any custom settings that you want to apply to the event object. options are as follows: tag: a developer-defined unique identifier for this syncevent. lastchance: a boolean indicating that the user agent will not make further synchronization attempts after the current attempt. ...
SyncEvent - Web APIs
Web › API › SyncEvent
the syncevent interface represents a sync action that is dispatched on the serviceworkerglobalscope of a serviceworker. this interface inherits from the extendableevent interface. ...
SyncManager.register() - Web APIs
manager.register method of the syncmanager 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 be...
TaskAttributionTiming - Web APIs
ng 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. ...
Text.isElementContentWhitespace - Web APIs
xt.textcontent). putting any property that represents the textual content of the text node into test() should do the same work just like the three example above. the text.iselementcontentwhitespace read-only property returns a boolean flag indicating whether or not the text node's content consists solely of whitespace. syntax b = textnode.iselementcontentwhitespace; example in the example below, we create a node with mixed display and whitespace characters and the attribute is false. var tn = document.createtextnode("hello world"); tn.iselementcontentwhitespace; /* evaluates to false */ for a node that is all whitespace characters, the iselementcontentwhitespace evaluates to true. var ws = document.createtextnode(" \t \r\n ") ws.iselementcontentwhitespace; /* evaluates to true */...
Text.splitText() - Web APIs
Web › API › Text › splitText
ffset the index immediately before which to break the text node. return value returns a newly created text node that contains the text after the specified offset point. exceptions thrown a domexception with a value of index_size_err is thrown if the specified offset is negative or is greater than the number of 16-bit units in the node's text; a domexception with a value of no_modification_allowed_err is thrown if the node is read-only. example in this example, the text of a <p> is split into two text nodes, and a <u> is inserted between them. html <p>foobar</p> javascript const p = document.queryselector('p'); // get contents of <p> as a text node const foobar = p.firstchild; // split 'foobar' into two text nodes, 'foo' and 'bar', // and save 'bar' as a const const bar = foobar.
TextDecoder() - Web APIs
coderoptions dictionary with the property: fatal a boolean flag indicating if the textdecoder.decode() method must throw a domexception with the "encodingerror" value when an coding error is found. it defaults to false. example var textdecoder1 = new textdecoder("iso-8859-2"); var textdecoder2 = new textdecoder(); var textdecoder3 = new textdecoder("csiso2022kr", {fatal: true}); // allows encodingerror exception to be thrown. var textdecoder4 = new textdecoder("iso-2022-cn"); // throw a typeerror exception. specifications specification status comment encodingthe definition of 'textdecoder()' in that specification. living standard initial definition. ...
TextDecoder.prototype.decode() - Web APIs
the specific method for that textdecoder object. syntax b1 = decoder.decode(buffer, options); b2 = decoder.decode(buffer); b3 = decoder.decode(); parameters buffer optional is either an arraybuffer or an arraybufferview containing the text to decode. options optional is a textdecodeoptions dictionary with the property: stream a boolean flag indicating that additional data will follow in subsequent calls to decode(). set to true if processing the data in chunks, and false for the final chunk or if the data is not chunked. it defaults to false. example this example encodes and decodes the euro symbol, €. html <p>encoded value: <span id="encoded-value"></span></p> <p>decoded value: <span id="decoded-value"></span></p> javascript const encoder = new textencoder(); co...
TextDecoder.prototype.encoding - Web APIs
the textdecoder.prototype.encoding read-only property returns a domstring containing the name of the decoding algorithm used by the specific decoder. it can be one of the following values: the recommended encoding for the web: 'utf-8'. the legacy single-byte encodings: 'ibm866', 'iso-8859-2', 'iso-8859-3', 'iso-8859-4', 'iso-8859-5', 'iso-8859-6', 'iso-8859-7', 'iso-8859-8'', 'iso-8859-8i', 'iso-8859-10', 'iso-8859-13', 'iso-8859-14', 'iso-8859-15', 'iso-8859-16', 'koi8-r', 'koi8-u', 'macintosh', 'windows-874', 'windows-1250', 'windows-1251', 'windows-1252', 'windows-1253', 'windows-1254', 'windows-1255', 'windows-1256', 'windows-1257', 'windows-1258', or 'x-mac-cyrillic'. the legacy multi-byte chinese (simplified) encodings: 'gbk', 'gb18030', and 'hz-gb-2312'. the legacy multi-byte...
TextEncoder.prototype.encodeInto() - Web APIs
(function(window){ "use strict"; var log = math.log; var ln2 = math.ln2; var clz32 = math.clz32 || function(x) {return 31 - log(x >>> 0) / ln2 | 0}; var fromcharcode = string.fromcha...
TextEncoder.encoding - Web APIs
the textencoder.encoding read-only property returns a domstring containing the name of the encoding algorithm used by the specific encoder. it can only have the following value utf-8. syntax b = encoder.encoding; specifications specification status comment encodingthe definition of 'textencoder.encoding' in that specification. living standard initial definition. ...
TextMetrics.width - Web APIs
Web › API › TextMetrics › width
the read-only width property of the textmetrics interface contains the text's advance width (the width of that inline box) in css pixels. examples given this <canvas> element: <canvas id="canvas"></canvas> ... you can get a textmetrics object using the following code: const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let text = ctx.measuretext('foo'); // textmetrics object text.width; // 16; specifications specification html living standardthe definition of 'textmetrics.width' in that specification. ...
TextTrack.mode - Web APIs
Web › API › TextTrack › mode
his value to switch modes. 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. the text track mode is one of the values listed below, under text track mode constants. text track mode constants the text track mode—sometimes identified using the idl enum texttrackmode—must be one of the following values: disabled the text track is currently disabled. while the track's presence is exposed in the dom, the user agent is otherwise ignoring it. no cues are active, no events are being fired, and the user agent won't attempt ...
TimeEvent - Web APIs
Web › API › TimeEvent
the timeevent interface, a part of svg smil animation, provides specific contextual information associated with time events. ...
Touch.force - Web APIs
Web › API › Touch › force
is known, the absolute pressure represented by the force attribute, and the sensitivity in levels of pressure, may vary. example this example illustrates using the touch interface's touch.force property. this property is a relative value of pressure applied, in the range 0.0 to 1.0, where 0.0 is no pressure, and 1.0 is the highest level of pressure the touch device is capable of sensing. in following code snippet, the touchstart event handler iterrates through the targettouches list and logs the force value of each touch point but the code could invoke different processing depending on the value. 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++) {...
Touch.pageX - Web APIs
Web › API › Touch › pageX
t. example this example illustrates how to access the touch object's touch.pagex and touch.pagey properties. the touch.pagex property is the horizontal coordinate of a touch point relative to the viewport (in css pixels), including any scroll offset. the touch.pagey property is the vertical coordinate of a touch point relative to the viewport (in css pixels), including any scroll offset. in following simple code snippet, we assume the user initiates one or more touch contacts on the source element, moves the touch points and then releases all contacts with the surface. when the touchmove event handler is invoked, each touch point's touch.pagex and touch.pagey coordinates are accessed via the event's touchevent.changedtouches list. // register a touchmove listeners for the 'source' element...
Touch.pageY - Web APIs
Web › API › Touch › pageY
t. example this example illustrates how to access the touch object's touch.pagex and touch.pagey properties. the touch.pagex property is the horizontal coordinate of a touch point relative to the viewport (in css pixels), including any scroll offset. the touch.pagey property is the vertical coordinate of a touch point relative to the viewport (in css pixels), including any scroll offset. in following simple code snippet, we assume the user initiates one or more touch contacts on the source element, moves the touch points and then releases all contacts with the surface. when the touchmove event handler is invoked, each touch point's touch.pagex and touch.pagey coordinates are accessed via the event's touchevent.changedtouches list. // register a touchmove listeners for the 'source' element...
Touch.radiusX - Web APIs
Web › API › Touch › radiusX
by the touch point's touch.rotationangle. likewise, the touch.radiusy property is the radius of the ellipse which most closely circumscribes the touching area (e.g. finger, stylus) along the axis perpendicular to that indicated by touch.rotationangle. the touch.rotationangle is the angle (in degrees) that the ellipse described by radiusx and radiusy is rotated clockwise about its center. the following simple code snippet, registers a single handler for the touchstart, touchmove and touchend events. when the src element is touched, the element's width and height will be calculate based on the touch point's radiusx and radiusy values and the element will then be rotated using the touch point's rotationangle. <div id="src"> ... </div> var src = document.getelementbyid("src"); src.addeventl...
Touch.screenX - Web APIs
Web › API › Touch › screenX
elative to the screen, not including any scroll offset. example this example illustrates how to access the touch object's touch.screenx and touch.screeny properties. the touch.screenx property is the horizontal (x) coordinate of a touch point relative to the screen in css pixels. the touch.screeny property is the vertical coordinate of a touch point relative to the screen in css pixels. in following simple code snippet, we assume the user initiates multiple touch contacts on an element with an id of source and then releases contacts with the surface. when the touchstart event handler is invoked, each touch point's touch.screenx and touch.screeny coordinates are accessed. // register a touchstart listeners for the 'source' element var src = document.getelementbyid("source"); src.addevent...
Touch.target - Web APIs
Web › API › Touch › target
st practice is to attach the touch listeners directly to the target. syntax var el = touchpoint.target; return value el the target element of the touch object. example this example illustrates how to access the touch object's touch.target property. the touch.target property is an element (eventtarget) on which a touch point is started when contact is first placed on the surface. in following simple code snippet, we assume the user initiates one or more touch contacts on the source element. when the touchstart event handler for this element is invoked, each touch point's touch.target property is accessed via the event's touchevent.targettouches list. // register a touchmove listener for the 'source' element var src = document.getelementbyid("source"); src.addeventlistener('touchs...
TouchEvent() - Web APIs
the touchevent() constructor creates a new touchevent. syntax event = new touchevent(typearg, toucheventinit); values typearg is a domstring representing the name of the event. toucheventinit optional is a toucheventinit dictionary, having the following fields: "touches", optional and defaulting to [], of type touch[], that is a list of objects for every point of contact currently touching the surface. "targettouches", optional and defaulting to [], of type touch[], that is a list of objects for every point of contact that is touching the surface and started on the element that is the target of the current event. "changedtouches", optional and defaulting to [], of type touch[], that is a list of objects for every point of contact which contributed to the event.
TouchEvent.altKey - Web APIs
Web › API › TouchEvent › altKey
true. otherwise, it is false. this property is read only . syntax var altenabled = touchevent.altkey; return value altenabled true if the alt key is enabled for this event; and false if the alt is not enabled. example this example illustrates how to access the touchevent key modifier properties: touchevent.altkey, touchevent.ctrlkey, touchevent.metakey and touchevent.shiftkey. in following code snippet, the touchstart event handler logs the state of the event's modifier keys. someelement.addeventlistener('touchstart', function(e) { // log the state of this event's modifier keys console.log("altkey = " + e.altkey); console.log("ctrlkey = " + e.ctrlkey); console.log("metakey = " + e.metakey); console.log("shiftkey = " + e.shiftkey); }, false); specifications ...
TouchEvent.targetTouches - Web APIs
nt as the current target element. example this example illustrates the touchevent object's touchevent.targettouches property. the touchevent.targettouches property is a touchlist object that includes those tps that are currently touching the surface and started on the element that is the target of the current event. as such, the targettouches list is a strict subset of the touches list. in following code snippet, the function compares the length of the touches list to the the length of the targettouches list and returns true if the lengths are the same and returns false otherwise. function touches_in_target(ev) { // return true if all of the touches are within the target element; // otherwise return false. return (ev.touches.length == ev.targettouches.length ? true : false); } sp...
TouchEvent.touches - Web APIs
nts that are still in contact with the touch surface, regardless of whether or not they've changed or what 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.leng...
TrackDefault.TrackDefault() - Web APIs
or the sourcebuffer to use when an initialization segment does not contain kind information for a new track. bytestreamtrackid optional a domstring specifying the id of the specific track that the sourcebuffer should apply to. if not specified, this value will be an empty string and the sourcebuffer can contain any tracks of the specified type. errors when this constructor is invoked, the following errors can occur: error explanation invalidaccesserror the supplied language is not a valid language code, e.g. en-us. typeerror there are values specified in the kinds array that do not apply to the specified type. example tbd ...
TrackDefaultList.TrackDefault() - Web APIs
[].) syntax var mytrackdefault = trackdefaultlist[index]; parameters index the index position of the trackdefault object you want to return. returns a trackdefault object. ...
TrackDefaultList - Web APIs
lts property. constructor trackdefaultlist() constructs and returns a new trackdefaultlist object. properties inherits properties from its parent interface, eventtarget. trackdefaultlist.length read only returns the number of trackdefault objects in the list. methods inherits properties from its parent interface, eventtarget. trackdefaultlist.trackdefault() this getter allows the trackdefault objects in the list to be accessed with an array operator (i.e. [].) examples tbd. ...
TrackEvent() - Web APIs
ect describing an event which occurred on a list of tracks (audiotracklist, videotracklist, or texttracklist). syntax trackevent = new trackevent(type, eventinfo); parameters type the type of track event which is described by the object: "addtrack" or "removetrack". eventinfo optional an optional dictionary providing additional information configuring the new event; it can contain the following fields in any combination: track optional the track to which the event refers; this is null by default, but should be set to a videotrack, audiotrack, or texttrack as appropriate given the type of track. bubbles optional a boolean indicating whether the event bubbles or not. cancelable optional a boolean indicating whether or not the event can be canceled. composed optional a...
TransformStream - Web APIs
the streams api represents a set of transformable data. constructor transformstream() creates and returns a transform stream object from the given handlers. properties transformstream.readable read only the readable end of a transformstream. transformstream.writable read only the writable end of a transformstream. methods none examples anything-to-uint8array stream in the following example, a transform stream passes through all chunks it receives as uint8array values. const transformcontent = { start() {}, // required. async transform(chunk, controller) { chunk = await chunk switch (typeof chunk) { case 'object': // just say the stream is done i guess if (chunk === null) controller.terminate() else if (arraybuffer.isview(chunk))...
TransitionEvent.initTransitionEvent() - Web APIs
in the progress of been removed from most implementation. do not use it anymore, use the standard constructor, transitionevent(), to create a synthetic transitionevent syntax transitionevent.inittransitionevent(typearg, canbubblearg, cancelablearg, transitionnamearg, elapsedtimearg); parameters typearg is a domstring identifying the specific type of transition event that occurred. the following value is allowed: value meaning transitionend the transition completed. canbubblearg is a boolean flag indicating if the event can bubble (true) or not (false). cancelablearg is a boolean flag indicating if the event associated action can be avoided (true) or not (false). transitionnamearg is a domstring containing the name of the css pro...
UIEvent() - Web APIs
Web › API › UIEvent › UIEvent
uievent.detail lists the semantic for standard events. view: optional and defaulting to null, of type windowproxy, that is the window associated with the event . ...
sourceCapabilities - Web APIs
example, when a user lifts their finger off of a touchscreen, several uievents may be generated including touchend, mousedown, click, and focus. all of these events must have the same sourcecapabilities representing the touchscreen. a device is considered "responsible" for an event only when that interaction is part of the abstraction provided by the web platform. for example, many user agents allow a window to be resized with a mouse or a keyboard, but this detail is not exposed to the web platform in any way, and so the sourcecapabilities of a resize event will typically be null. syntax var idc = event.sourcecapabilities value an instance of inputdevicecapabilities. specifications specification status comment inputdevicecapabilitiesthe definition of 'sourcecap...
UIEvent - Web APIs
Web › API › UIEvent
lity, you should create a uievent object using the uievent() constructor. several interfaces are direct or indirect descendants of this one: mouseevent, touchevent, focusevent, keyboardevent, wheelevent, inputevent, and compositionevent. ...
URL.hash - Web APIs
Web › API › URL › hash
the fragment is not percent-decoded. if the url does not have a fragment identifier, this property contains an empty string — "". note: this feature is available in web workers. syntax const string = url.hash url.hash = newhash value a usvstring. ...
URL.host - Web APIs
Web › API › URL › host
note: this feature is available in web workers. syntax const host = url.host url.host = newhost value a usvstring. ...
URL.origin - Web APIs
Web › API › URL › origin
the origin read-only property of the url interface returns a usvstring containing the unicode serialization of the origin of the represented url. the exact structure varies depending on the type of url: for http or https urls, the scheme followed by '://', followed by the domain, followed by ':', followed by the port (the default port, 80 and 443 respectively, if explicitely specified). for file: urls, the value is browser dependant. for blob: urls, the origin of the url following blob: will be used, e.g "blob:https://mozilla.org" will be returned as "https://mozilla.org". note: this feature is available in web workers. syntax const originstring = url.origin value a usvstring. examples const url = new url("blob:https://mozilla.org:443/") console.log(url.origin); // logs 'https:...
URL.pathname - Web APIs
Web › API › URL › pathname
note: this feature is available in web workers. syntax const path = url.pathname url.pathname = newpath value a usvstring. ...
URL.pathname - Web APIs
note: this feature is available in web workers. syntax const path = url.pathname url.pathname = newpath value a usvstring. ...
URL.search - Web APIs
Web › API › URL › search
modern browsers provide the url.searchparams property to make it easy to parse out the parameters from the query string. note: this feature is available in web workers. syntax const searchparams = object.search url.search = newsearchparams value a usvstring. ...
URL.search - Web APIs
Web › API › URL › search?q=123
modern browsers provide the url.searchparams property to make it easy to parse out the parameters from the query string. note: this feature is available in web workers. syntax const searchparams = object.search url.search = newsearchparams value a usvstring. ...
URL.searchParams - Web APIs
Web › API › URL › searchParams
note: this feature is available in web workers. syntax const urlsearchparams = url.searchparams value a urlsearchparams object. examples if the url of your page is https://example.com/?name=jonathan%20smith&age=18 you could parse out the name and age parameters using: let params = (new url(document.location)).searchparams; let name = params.get('name'); // is the string "jonathan smith". ...
URLSearchParams() - Web APIs
orkers. syntax var urlsearchparams = new urlsearchparams(init); parameters init optional one of: a usvstring, which will be parsed from application/x-www-form-urlencoded format. a leading '?' character is ignored. a sequence of usvstring pairs, representing names/values. a record of usvstring keys and usvstring values. return value a urlsearchparams object instance. examples the following example shows how to create a urlsearchparams object from a url string. // retrieve params via url.search, passed into ctor var url = new url('https://example.com?foo=1&bar=2'); var params = new urlsearchparams(url.search); // pass in a string literal var params2 = new urlsearchparams("foo=1&bar=2"); var params2a = new urlsearchparams("?foo=1&bar=2"); // pass in a sequence of pairs var para...
URLSearchParams.append() - Web APIs
note: this feature is available in web workers. syntax urlsearchparams.append(name, value) parameters name the name of the parameter to append. value the value of the parameter to append. return value void. examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter. ...
URLSearchParams.entries() - Web APIs
the key and value of each pair are usvstring objects. note: this feature is available in web workers. syntax searchparams.entries(); parameters none. return value returns an iterator. ...
URLSearchParams.forEach() - Web APIs
note: this feature is available in web workers. syntax searchparams.foreach(callback); parameters callback a callback function that is executed against each parameter, with the param value provided as its parameter. return value void. ...
URLSearchParams.keys() - Web APIs
the keys are usvstring objects. note: this method is available in web workers. syntax searchparams.keys(); parameters none. return value returns an iterator. ...
URLSearchParams.set() - Web APIs
chparams.set(name, value) parameters name the name of the parameter to set. value the value of the parameter to set. return value void. examples let's start with a simple example: let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a third parameter. params.set('baz', 3); params.tostring(); // "foo=1&bar=2&baz=3" below is a real-life example demonstrating how to create a url and set some search parameters. you can copy and paste the example in a code environment like codepen, jsfiddle, or the multi-line javascript interpreter in firefox. line #41: comment out this line to stop dumping the search parameters to the console (debug). line #43: dumps the generated object and it's string representation to the co...
URLSearchParams.values() - Web APIs
the values are usvstring objects. note: this feature is available in web workers. syntax searchparams.values(); parameters none. return value returns an iterator. ...
URLUtilsReadOnly.hash - Web APIs
the hash is not percent encoded. syntax string = object.hash; examples // in a web worker, on the page https://developer.mozilla.org/docs/urlutilsreadonly.hash#example var result = window.self.hash; // returns:'#hash' specifications specification status comment urlthe definition of 'urlutilsreadonly.hash' in that specification. living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. ...
URLUtilsReadOnly.pathname - Web APIs
syntax string = object.pathname; examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.pathname var result = window.self.pathname; // returns:'/urlutilsreadonly.pathname' specifications specification status comment urlthe definition of 'urlutilsreadonly.pathname' in that specification. living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. ...
URLUtilsReadOnly.search - Web APIs
syntax string = object.search; examples // in a web worker, on the page https://developer.mozilla.org/docs/urlutilsreadonly.href?t=67 var result = window.self.search; // returns:'?t=67' specifications specification status comment urlthe definition of 'urlutilsreadonly.search' in that specification. living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. ...
URLUtilsReadOnly - Web APIs
of the url. urlutilsreadonly.hostname read only is a domstring containing the domain of the url. urlutilsreadonly.origin read only returns a domstring containing the canonical form of the origin of the specific location. urlutilsreadonly.port read only is a domstring containing the port number of the url. urlutilsreadonly.pathname read only is a domstring containing an initial '/' followed by the path of the url. urlutilsreadonly.search read only is a domstring containing a '?' followed by the parameters of the url. urlutilsreadonly.hash read only is a domstring containing a '#' followed by the fragment identifier of the url. methods this interface doesn't inherit any methods. urlutilsreadonly.tostring() returns a domstring containing the whole url. it is a synonym f...
URL API - Web APIs
Web › API › URL API
e of interfaces to its name: url urlsearchparams older versions of the specification included an interface called urlutilsreadonly, which has since been merged into the workerlocation interface. examples if you want to process the parameters included in a url, you could do it manually, but it's much easier to create a url object to do it for you. the filltablewithparameters() function below takes as input a htmltableelement object representing a <table>. rows are added to the table, one for each key found in the parameters, with the first column containing the key's name, and the second column having the value. note the call to urlsearchparams.sort() to sort the parameter list before generating the table. function filltablewithparameters(tbl) { let url = new url(document.locatio...
USB.getDevices() - Web APIs
Web › API › USB › getDevices
the getdevices method of the usb interface returns a promise that resolves with an array of usbdevice objects for paired attached devices. for information on pairing devices, see usb.requestdevice(). syntax usb.getdevices() parameters none. return value a promise that resolves with an array of usbdevice objects. example the following example logs the product name and serial number of paired devices to the console. for information on pairing devices, see usb.requestdevice(). navigator.usb.getdevices() .then(devices => { console.log("total devices: " + devices.length); devices.foreach(device => { console.log("product name: " + device.productname + ", serial number " + device.serialnumber); }); }); specifications specification status comment webus...
USB.requestDevice() - Web APIs
Web › API › USB › requestDevice
the requestdevice() method of the usb interface returns a promise that resolves with an instance of usbdevice if the specified device is found. calling this function triggers the user agent's pairing flow. syntax usb.requestdevice([filters]) parameters filters an array of filter objects for possible devices you would like to pair. each filter object can have the following properties: vendorid productid classcode subclasscode protocolcode serialnumber return value a promise that resolves with an instance of usbdevice. example the following example looks for one of two usb devices. notice that two product ids are specified. both are passed to requestdevice(). this triggers a user-agent flow that prompts the user to select a device for pairing. only the selected...
USB - Web APIs
Web › API › USB
s connected. usb.ondisconnect an event handler called whenever a paired device is disconnected. methods usb.getdevices() returns a promise that resolves with an array of usbdevice objects for paired attached devices. usb.requestdevice() returns a promise that resolves with an instance of usbdevice if the specified device is found. calling this function triggers the user agent's pairing flow. specifications specification status comment webusbthe definition of 'usb' in that specification. draft initial definition. ...
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.clearHalt() - Web APIs
r that condition. 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'. endpointnumber indicates the number of the endpoint to clear. the promise will reject if an invalid endpoint is supplied. return value a promise. example the following example shows how to test for and clear a 'stall' condition in the result of a data transfer. what data can be passed to a usb device and how it is passed is particular and unique to each device. while (true) { let result = await data.transferin(1, 6); if (result.data && result.data.bytelength === 6) { console.log('channel 1: ' + result.data.getuint16(0)); console.log('chan...
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. ...
USVString - Web APIs
Web › API › USVString
usvstring corresponds to the set of all possible sequences of unicode scalar values. usvstring maps to a string when returned in javascript; it's generally only used for apis that perform text processing and need a string of unicode scalar values to operate on. usvstring is equivalent to domstring except for not allowing unpaired surrogate codepoints. unpaired surrogate codepoints present in usvstring are converted by the browser to unicode 'replacement character' u+fffd, (�). specifications specification status comment web idlthe definition of 'usvstring' in that specification. candidate recommendation initial definition. ...
UserDataHandler - Web APIs
n both document.importnode() and node.clonenode(), although user data is not copied over, the handler will be called. properties none. methods handle (operation, key, data, src, dst) (no return value) this method is a callback which will be called if a node is being cloned, imported, renamed and as well, if deleted or adopted. operation (unsigned short) is an operation type integer (see below). key (domstring) is the user key. data (domuserdata) is the user data. src (node) is the source node (null if being deleted). dst (node) is the destination node (if any, or null). constants constant value operation node_cloned 1 node.clonenode() node_imported 2 document.importnode() node_deleted unimplemented (see bug 550400) 3 ...
ValidityState.patternMismatch - Web APIs
orm to the constraints set by the element's pattern attribute. if the field supports the pattern attribute -- which means the <input> is of type text, tel, email, url, password, or search -- and the pattern value is set to a valid regular expression, if the value don't doesn't conform to the constraints set by the pattern value, the patternmismatch property will be true. ...
ValidityState.stepMismatch - Web APIs
ncluding 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-classes. specifications specification status comment html living standardthe definition of 'validitystate.stepmismatch' in that specification. living standard html 5.1the defi...
ValidityState.typeMismatch - Web APIs
rl input is not an empty string, a single valid url, or one or more comma separated urls if the multiple attribute is present, there is a typemismatch. ...
Vibration API - Web APIs
oting that you don't have to provide a pause as your last entry since the vibration automatically stops at the end of each vibration period. canceling existing vibrations calling navigator.vibrate() with a value of 0, an empty array, or an array containing all zeros will cancel any currently ongoing vibration pattern. ...
VideoPlaybackQuality.totalVideoFrames - Web APIs
esholdexceeded() 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.droppedvideoframes)/quality.totalvideoframes > 0.1) { lostframesthresholdexceeded(); } a similar algorithm might be used to attempt to switch to a lower-resolution video that requires less bandwidth, in order to avoid dropping frames. specifications specification status comment media playback qualitythe definition of 'videoplaybackquality.totalvideoframes' in that specification. editor's draft initial definition. ...
VideoTrack.kind - Web APIs
Web › API › VideoTrack › kind
f video contained in the videotrack. the kind can be used to determine the scenarios in which specific tracks should be enabled or disabled. 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. video track kind strings the kinds available for video tracks are: "alternative" a potential alternative to the main track, such as a different video take or a version of the soundtrack with only the music and no dialogue. "captions" a version of the main video track with captions burnt in. "main" the primary video track. "sign" a sign-language interpretation of an audio track. "sub...
VideoTrack.label - Web APIs
Web › API › VideoTrack › label
n-readable label, if one is available in the track metadata. otherwise, an empty string ("") is returned. for example, a track whose kind is "sign" might have a label such as "a sign-language interpretation.". example this example returns an array of track kinds and labels for potential use in a user interface to select video tracks for a specified media element. the list is filtered to only allow certain track kinds through. function gettracklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "commentary" ]; el.videotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, label: track.label }); } }); return tracklist; } the resulting track...
WEBGL_compressed_texture_astc.getSupportedProfiles() - Web APIs
the webgl_compressed_texture_astc.getsupportedprofiles() method returns an array of strings containing the names of the astc profiles supported by the implementation. syntax sequence<domstring> ext.getsupportedprofiles(); return value an array of domstring elements indicating which astc profiles are supported by the implementation. currently, this can be: "ldr": low dynamic range. "hdr": high dynamic range. dynamic range refers to ratio between the brightest and darkest parts of the scene. low dynamic ranges are for example jpeg format images which won't exceed 255:1, or crt monitors which won't exceed 100:1. an hdr image stores pixel values that span the whole tonal range of real-world scenes (100,000:1). examples var ext = gl.getextension('webgl_compressed_texture_astc'); ext.
WEBGL_compressed_texture_atc - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method. ...
WEBGL_compressed_texture_etc - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is available to both, webgl1 and webgl2 contexts. ...
WEBGL_compressed_texture_etc1 - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is available to both, webgl1 and webgl2 contexts. ...
WEBGL_compressed_texture_pvrtc - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: pvrtc is typically only available on mobile devices with powervr chipsets. ...
WEBGL_compressed_texture_s3tc - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is available to both, webgl1 and webgl2 contexts. ...
WEBGL_compressed_texture_s3tc_srgb - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is available to both webgl1 and webgl2 contexts. ...
WEBGL_debug_renderer_info - Web APIs
d contexts. generally, the graphics driver information should only be used in edge cases to optimize your webgl content or to debug gpu problems. the webglrenderingcontext.getparameter() method can help you to detect which features are supported and the failifmajorperformancecaveat context attribute lets you control if a context should be returned at all, if the performance would be dramatically slow. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: depending on the privacy settings of the browser, this extension might only be available to privileged contexts or not work at all. in firefox, if privacy.resistfingerprinting is set to true, this extensions is disabled. th...
WEBGL_debug_shaders.getTranslatedShaderSource() - Web APIs
syntax gl.getextension('webgl_debug_shaders').gettranslatedshadersource(shader); parameters shader a webglshader to get the translated source from. return value a string containing the translated shader source. an empty string is returned, if: no source has been defined or, webglrenderingcontext.compileshader() has not yet been called or, the translation for the shader failed. ...
WEBGL_draw_buffers.drawBuffersWEBGL() - Web APIs
this method is part of the webgl_draw_buffers extension. note: when using webgl2, this method is available as gl.drawbuffers() by default and the constants are named gl.color_attachment1 etc. without the "webgl" suffix. syntax void gl.getextension('webgl_draw_buffers').drawbufferswebgl(buffers); parameters buffers an array of glenum constants defining drawing buffers. possible values: gl.none: the fragment shader is not written to any color buffer. gl.back: the fragment shader is written to the back color buffer. ...
WEBGL_lose_context.loseContext() - Web APIs
it triggers the steps described in the webgl specification for handling context lost. the context will remain lost until webgl_lose_context.restorecontext() is called. ...
WEBGL_lose_context.restoreContext() - Web APIs
syntax gl.getextension('webgl_lose_context').restorecontext(); errors thrown invalid_operation if the context was not lost. ...
WakeLockSentinel - Web APIs
a handle to the underlying platform wake lock and can be manually released and reacquired. an object representing the wake lock is returned via the navigator.wakelock.request() method. an acquired wakelocksentinel can be released manually via the release() method, or automatically via the platform wake lock. this can happen if the document becomes inactive or looses visibility, if the device is low on power or the user 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. prev...
WaveShaperNode.WaveShaperNode() - Web APIs
the waveshapernode() constructor of the web audio api creates 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 ...
WebGL2RenderingContext.copyTexSubImage3D() - Web APIs
al array texture. level a glint specifying the level of detail. level 0 is the base image level and level n is the nth mipmap reduction level. xoffset a glint specifying the x offset within the texture image. yoffset a glint specifying the y offset within the texture image. zoffset a glint specifying the z offset within the texture image. 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 specifying the height of the texture. return value none. examples gl.copytexsubimage3d(gl.texture_3d, 0, 0, 0, 0, 0, 0, 16, 16); specifications specification status comment ...
WebGL2RenderingContext.getUniformBlockIndex() - Web APIs
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. opengl es 3.0th...
WebGL2RenderingContext.renderbufferStorageMultisample() - Web APIs
syntax void gl.renderbufferstoragemultisample(target, samples, internalformat, width, height); parameters target a glenum specifying the target renderbuffer object. possible values: gl.renderbuffer: buffer data storage for single images in a renderable internal format. samples a glsizei specifying the number of samples to be used for the renderbuffer storage. ...
WebGL2RenderingContext.texImage3D() - Web APIs
its, 4 alpha bits. gl.unsigned_short_5_5_5_1: 5 red bits, 5 green bits, 5 blue bits, 1 alpha bit. gl.byte gl.unsigned_short gl.short gl.unsigned_int gl.int gl.half_float gl.float gl.unsigned_int_2_10_10_10_rev gl.unsigned_int_10f_11f_11f_rev gl.unsigned_int_5_9_9_9_rev gl.unsigned_int_24_8 gl.float_32_unsigned_int_24_8_rev (pixels must be null) source one of the following objects can be used as a pixel source for the texture: arraybufferview, imagebitmap, imagedata, htmlimageelement, htmlcanvaselement, htmlvideoelement. offset a glintptr byte offset into the webglbuffer's data store. used to upload data to the currently bound webgltexture from the webglbuffer bound to the pixel_unpack_buffer target. return value none. examples g...
WebGL2RenderingContext.texStorage2D() - Web APIs
ormat a glenum specifying the texture store format. possible values: gl.r8 gl.r16f gl.r32f gl.r8ui gl.rg8 gl.rg16f gl.rg32f gl.rg8ui gl.rgb8 gl.srgb8 gl.rgb565 gl.r11f_g11f_b10f gl.rgb9_e5 gl.rgb16f gl.rgb32f gl.rgb8ui gl.rgba8 gl.srgb8_aplha8 gl.rgb5_a1 gl.rgba4 gl.rgba16f gl.rgba32f gl.rgba8ui unlike opengl 3.0, webgl 2 doesn't support the following etc2 and eac compressed texture formats (see section 5.37 in the webgl 2 spec). you might be able to enable them via the webgl_compressed_texture_etc extension, though. gl.compressed_r11_eac gl.compressed_signed_r11_eac gl.compressed_rg11_eac gl.compressed_signed_rg11_eac gl.compressed_rgb8_etc2 gl.compressed_rgba8_etc2_eac gl.compressed_srgb8_etc2 gl.compressed_srgb8_alpha8...
WebGL2RenderingContext.texSubImage3D() - Web APIs
its, 4 alpha bits. gl.unsigned_short_5_5_5_1: 5 red bits, 5 green bits, 5 blue bits, 1 alpha bit. gl.byte gl.unsigned_short gl.short gl.unsigned_int gl.int gl.half_float gl.float gl.unsigned_int_2_10_10_10_rev gl.unsigned_int_10f_11f_11f_rev gl.unsigned_int_5_9_9_9_rev gl.unsigned_int_24_8 gl.float_32_unsigned_int_24_8_rev (pixels must be null) pixels one of the following objects can be used as a pixel source for the texture: arraybufferview, a uint8array must be used if type is gl.unsigned_byte. a uint16array must be used if type is either gl.unsigned_short_5_6_5, gl.unsigned_short_4_4_4_4, gl.unsigned_short_5_5_5_1, or ext.half_float_oes. a float32array must be used if type is gl.float. imagebitmap, imagedata, htmlimageelement...
WebGL2RenderingContext.uniform[1234][uif][v]() - Web APIs
the webgl2renderingcontext.uniform[1234][uif][v]() methods of the webgl api specify values of uniform variables. ui stands for unsigned integer, i for integer, f for float, and v for vector. not all combinations are valid: u cannot be combined with f. see the syntax table below. equivalent regex: uniform[1234](u?i|f)v? syntax void gl.uniform1ui(location, v0); void gl.uniform2ui(location, v0, v1); void gl.uniform3ui(location, v0, v1, v2); void gl.uniform4ui(location, v0, v1, v2, v3); void gl.uniform1fv(location, data, optional srcoffset, optional srclength); void gl.uniform2fv(location, data, optional srcoffset, optional srclength); void gl.uniform3fv(location, data, optional srcoffset, optional srclength); void gl.uniform4fv(location, data, optional srcoffset, optional srclen...
WebGL2RenderingContext.uniformMatrix[234]x[234]fv() - Web APIs
the webgl2renderingcontext.uniformmatrix[234]x[234]fv() methods of the webgl 2 api specify matrix values for uniform variables. there are no 2x2, 3x3, and 4x4 versions of this method. they are abbreviated in 2, 3, and 4, respectively. see the syntax below. syntax void gl.uniformmatrix2fv(location, transpose, data, optional srcoffset, optional srclength); void gl.uniformmatrix3x2fv(location, transpose, data, optional srcoffset, optional srclength); void gl.uniformmatrix4x2fv(location, transpose, data, optional srcoffset, optional srclength); void gl.uniformmatrix2x3fv(location, transpose, data, optional srcoffset, optional srclength); void gl.uniformmatrix3fv(location, transpose, data, optional srcoffset, optional srclength); void gl.uniformmatrix4x3fv(location, transpose, data...
WebGL2RenderingContext.vertexAttribIPointer() - Web APIs
s of the first component in the vertex attribute array. must be a multiple of type. return value none. description very similar to webglrenderingcontext.vertexattribpointer(). the main difference is that while values specified by vertexattribpointer are always interpreted as floating-point values in the shader (even if they were originally specified as integers in the buffer), this method allows specifying values which are interpreted as integers in the shader. examples linear blend skinning //describe the layout of the buffer: //1. position gl.vertexattribpointer(0, 3, gl.float, false, 20, 0); gl.enablevertexattribarray(0); //2. bone weights, normalized to [0, 1] gl.vertexattribpointer(1, 4, gl.unsigned_byte, true, 20, 12); gl.enablevertexattribarray(1); //3. bone indices, interpret...
WebGL2RenderingContext - Web APIs
ents of attachments in a framebuffer webgl2renderingcontext.readbuffer() selects a color buffer as the source for pixels. renderbuffers webgl2renderingcontext.getinternalformatparameter() returns information about implementation-dependent support for internal formats. webgl2renderingcontext.renderbufferstoragemultisample() creates and initializes a renderbuffer object's data store and allows specifying the number of samples to be used. textures webgl2renderingcontext.texstorage2d() specifies all levels of two-dimensional texture storage. webgl2renderingcontext.texstorage3d() specifies all levels of a three-dimensional texture or two-dimensional array texture. webgl2renderingcontext.teximage3d() specifies a three-dimensional texture image. webgl2renderingcontext.texsubimag...
WebGLBuffer - Web APIs
the webglbuffer interface is part of the webgl api and represents an opaque buffer object storing data such as vertices or colors. description the webglbuffer object does not define any methods or properties of its own and its content is not directly accessible. when working with webglbuffer objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.bindbuffer() webglrenderingcontext.createbuffer() webglrenderingcontext.deletebuffer() webglrenderingcontext.isbuffer() examples creating a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); specifications specification status comment webgl 1.0the definition of 'webglbuffer' in that specification. r...
WebGLContextEvent - Web APIs
ace is part of the webgl api and is an interface for an event that is generated in response to a status change to the webgl rendering context. inheritance this interface inherits properties and methods from its parent interface, event. ...
WebGLFramebuffer - Web APIs
the webglframebuffer interface is part of the webgl api and represents a collection of buffers that serve as a rendering destination. description the webglframebuffer object does not define any methods or properties of its own and its content is not directly accessible. ...
WebGLProgram - Web APIs
the webglprogram is part of the webgl api and is a combination of two compiled webglshaders consisting of a vertex shader and a fragment shader (both written in glsl). to create a webglprogram, call the gl context's createprogram() 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 ...
WebGLRenderbuffer - Web APIs
the webglrenderbuffer interface is part of the webgl api and represents a buffer that can contain an image, or can be source or target of an rendering operation. description the webglrenderbuffer object does not define any methods or properties of its own and its content is not directly accessible. ...
WebGLRenderingContext.activeTexture() - Web APIs
oid gl.activetexture(texture); parameters texture the texture unit to make active. the value is a gl.texturei where i is within the range from 0 to gl.max_combined_texture_image_units - 1. return value none. exceptions if texture is not one of gl.texturei, where i is within the range from 0 to gl.max_combined_texture_image_units - 1, a gl.invalid_enum error is thrown. examples the following call selects gl.texture1 as the current texture. subsequent calls that modify the texture state will affect this texture. gl.activetexture(gl.texture1); the number of texture units is implementation dependent, you can get this number with the help of the max_combined_texture_image_units constant. it is, per specification, at least 8. gl.getparameter(gl.max_combined_texture_image_units); ...
WebGLRenderingContext.attachShader() - Web APIs
the webglrenderingcontext.attachshader() method of the webgl api attaches either a fragment or vertex webglshader to a webglprogram. syntax void gl.attachshader(program, shader); parameters program 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...
WebGLRenderingContext.bindBuffer() - Web APIs
a given webglbuffer to a target. syntax void gl.bindbuffer(target, buffer); parameters target a glenum specifying the binding point (target). possible values: gl.array_buffer: buffer containing vertex attributes, such as vertex coordinates, texture coordinate data, or vertex color data. gl.element_array_buffer: buffer used for element indices. when using a webgl 2 context, the following values are available additionally: gl.copy_read_buffer: buffer for copying from one buffer object to another. gl.copy_write_buffer: buffer for copying from one buffer object to another. gl.transform_feedback_buffer: buffer for transform feedback operations. gl.uniform_buffer: buffer used for storing uniform blocks. gl.pixel_pack_buffer: buffer used for pixel transfer op...
WebGLRenderingContext.bindFramebuffer() - Web APIs
ringcontext.bindframebuffer() method of the webgl api binds a given webglframebuffer to a target. syntax void gl.bindframebuffer(target, framebuffer); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. framebuffer a webglframebuffer object to bind. return value none. exceptions a gl.invalid_enum error is thrown if target is not gl.framebu...
WebGLRenderingContext.bindTexture() - Web APIs
the webglrenderingcontext.bindtexture() method of the webgl api binds a given webgltexture to a target (binding point). syntax void gl.bindtexture(target, texture); parameters target a glenum specifying the binding point (target). possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map: a cube-mapped texture. when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture. gl.texture_2d_array: a two-dimensional array texture. texture a webgltexture object to bind. return value none. exceptions a gl.invalid_enum error is thrown if target is not gl.texture_2d, gl.texture_cube_map, gl.texture_3d, or gl.texture_2d_array. examples binding a texture var canvas = documen...
WebGLRenderingContext.blendEquation() - Web APIs
ifying 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 possible values, a gl.invalid_enum error is thrown. return value none. examples to set the blend equation, use: gl.blendequation(gl.func_add); gl.blendequation(gl.func_subtr...
WebGLRenderingContext.copyTexImage2D() - Web APIs
ents 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 specifying the height of the texture. border a glint specifying the width of the border. must be 0. return value none. examples gl.copyteximage2d(gl.texture_2d, 0, gl.rgba, 0, 0, 512, 512, 0)...
WebGLRenderingContext.copyTexSubImage2D() - Web APIs
xture_cube_map_negative_z: negative z face for a cube-mapped texture. level a glint specifying the level of detail. level 0 is the base image level and level n is the nth mipmap reduction level. xoffset a glint specifying the horizontal offset within the texture image. yoffset a glint specifying the vertical offset within the texture image. 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 specifying the height of the texture. return value none. examples gl.copytexsubimage2d(gl.texture_2d, 0, 0,0, 0, 0, 16, 16); specifications specification status comment ...
WebGLRenderingContext.disable() - Web APIs
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 testing and updates to the stencil buffer. see webglrenderingcontext.stencilfunc(). when using a webgl 2 context, the following values are available additionally: constant description gl.rasterizer_discard deactivates that primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored. return value none. examples gl.disable(gl.dither); to check if a capability is disabled, use...
WebGLRenderingContext.drawingBufferHeight - Web APIs
y represents the actual height of the current drawing buffer. it should match the height attribute of the <canvas> element associated with this context, but might differ if the implementation is not able to provide the requested height. syntax gl.drawingbufferheight; examples given this <canvas> element: <canvas id="canvas"></canvas> you can get the height of the drawing buffer with the following lines: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.drawingbufferheight; // 150 specifications specification status comment webgl 1.0the definition of 'webglrenderingcontext.drawingbufferheight' in that specification. recommendation initial definition. ...
WebGLRenderingContext.drawingBufferWidth - Web APIs
operty represents the actual width of the current drawing buffer. it should match the width attribute of the <canvas> element associated with this context, but might differ if the implementation is not able to provide the requested width. syntax gl.drawingbufferwidth; examples given this <canvas> element: <canvas id="canvas"></canvas> you can get the width of the drawing buffer with the following lines: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.drawingbufferwidth; // 300 specifications specification status comment webgl 1.0the definition of 'webglrenderingcontext.drawingbufferwidth' in that specification. recommendation initial definition. ...
WebGLRenderingContext.enable() - Web APIs
rage 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 and updates to the stencil buffer. see webglrenderingcontext.stencilfunc(). when using a webgl 2 context, the following values are available additionally: constant description gl.rasterizer_discard primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored. return value none. examples gl.enable(gl.dither); to check if a capability is enabled, use the webglrendering...
WebGLRenderingContext.getError() - Web APIs
.no_error no error has been recorded. the value of this constant is 0. gl.invalid_enum an unacceptable value has been specified for an enumerated argument. the command is ignored and the error flag is set. gl.invalid_value a numeric argument is out of range. the command is ignored and the error flag is set. gl.invalid_operation the specified command is not allowed for the current state. the command is ignored and the error flag is set. gl.invalid_framebuffer_operation the currently bound framebuffer is not framebuffer complete when trying to render to or to read from it. gl.out_of_memory not enough memory is left to execute the command. gl.context_lost_webgl if the webgl context is lost, this error is returned on the f...
WebGLRenderingContext.getProgramParameter() - Web APIs
ther or not the last validation operation was successful. gl.attached_shaders: returns a glint indicating the number of attached shaders to a program. gl.active_attributes: returns a glint indicating the number of active attribute variables to a program. gl.active_uniforms: returns a glint indicating the number of active uniform variables to a program. when using a webgl 2 context, the following values are available additionally: gl.transform_feedback_buffer_mode: returns a glenum indicating the buffer mode when transform feedback is active. may be gl.separate_attribs or gl.interleaved_attribs. gl.transform_feedback_varyings: returns a glint indicating the number of varying variables to capture in transform feedback mode. gl.active_uniform_blocks: returns a glint indic...
WebGLRenderingContext.getRenderbufferParameter() - Web APIs
(in bits) for the red color. gl.renderbuffer_alpha_size: returns a glint that is the resolution size (in bits) for the alpha component. gl.renderbuffer_depth_size: returns a glint that is the resolution size (in bits) for the depth component. gl.renderbuffer_stencil_size: returns a glint that is the resolution size (in bits) for the stencil component. when using a webgl 2 context, the following value is available additionally: gl.renderbuffer_samples: returns a glint indicating the number of samples of the image of the currently bound renderbuffer. return value depends on the requested information (as specified with pname). either a glint or a glenum. examples gl.getrenderbufferparameter(gl.renderbuffer, gl.renderbuffer_width); specifications speci...
WebGLRenderingContext.getTexParameter() - Web APIs
the webglrenderingcontext.gettexparameter() method of the webgl api returns information about the given texture. syntax any gl.gettexparameter(target, pname); parameters target a glenum specifying the binding point (target). possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map: a cube-mapped texture. when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture. gl.texture_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 mag...
WebGLRenderingContext.getVertexAttrib() - Web APIs
gl.short, gl.unsigned_short, gl.float. gl.vertex_attrib_array_normalized: returns a glboolean that is true if fixed-point data types are normalized for the vertex attribute array at the given index. gl.current_vertex_attrib: returns a float32array (with 4 elements) representing the current value of the vertex attribute at the given index. when using a webgl 2 context, the following values are available additionally: gl.vertex_attrib_array_integer: returns a glboolean indicating whether or not an integer data type is in the vertex attribute array at the given index. gl.vertex_attrib_array_divisor: returns a glint describing the frequency divisor used for instanced rendering. when using the angle_instanced_arrays extension: ext.vertex_attrib_ar...
WebGLRenderingContext.isContextLost() - Web APIs
in this case, all contexts are lost, then restored after switching gpus. another page running in the user's browser performs an operation using the gpu that takes too long, causing hte browser to decide to reset the gpu in order to break the stall. this would cause every webgl context to be lost throughout the entire 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 ...
WebGLRenderingContext.isEnabled() - Web APIs
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. see webglrenderingcontext.stencilfunc(). when using a webgl 2 context, the following values are available additionally: constant description gl.rasterizer_discard primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored. return value a glboolean indicating if the capability cap is enabled (true), or not (false). examples gl.isenab...
WebGLRenderingContext.makeXRCompatible() - Web APIs
ard 2d display but can then be transitioned to a 3d immersion system. syntax let makecompatpromise = webglrenderingcontext.makexrcompatible(); parameters none. return value a promise which successfully resolves once the webgl context is ready to be used for rendering webxr content. exceptions this method doesn't throw traditional exceptions; instead, the promise rejects with one of the following errors as the value passed into the rejection handler: aborterror switching the context over to the webxr-compatible context failed. invalidstateerror the webgl context has been lost or there is no available webxr device. usage notes because makexrcompatible() may involve replacing the underlying webgl context with a new one that uses the new rendering hardware, the existing contents ...
WebGLRenderingContext.readPixels() - Web APIs
olor framebuffer into an arraybufferview object. syntax // webgl1: void gl.readpixels(x, y, width, height, format, type, pixels); // webgl2: void gl.readpixels(x, y, width, height, format, type, glintptr offset); void gl.readpixels(x, y, width, height, format, type, arraybufferview pixels, gluint dstoffset); parameters x a glint specifying the first horizontal pixel that is read from the lower left corner of a rectangular block of pixels. y a glint specifying the first vertical pixel that is read from the lower left corner of a rectangular block of pixels. width a glsizei specifying the width of the rectangle. height a glsizei specifying the height of the rectangle. format a glenum specifying the format of the pixel data. possible values: gl.alpha: discards the red, green...
WebGLRenderingContext.stencilFunc() - Web APIs
e test is done. the default value is all 1. return value none. examples the stencil testing is disabled by default. to enable or disable stencil testing, use the enable() and disable() methods with the argument gl.stencil_test. gl.enable(gl.stencil_test); gl.stencilfunc(gl.less, 0, 0b1110011); to get the current stencil function, reference value, or other stencil information, query the following constants with getparameter(). gl.getparameter(gl.stencil_func); gl.getparameter(gl.stencil_value_mask); gl.getparameter(gl.stencil_ref); gl.getparameter(gl.stencil_back_func); gl.getparameter(gl.stencil_back_value_mask); gl.getparameter(gl.stencil_back_ref); gl.getparameter(gl.stencil_bits); specifications specification status comment webgl 1.0the definition of 'st...
WebGLRenderingContext.stencilFuncSeparate() - Web APIs
e default value is all 1. return value none. examples the stencil testing is disabled by default. to enable or disable stencil testing, use the enable() and disable() methods with the argument gl.stencil_test. gl.enable(gl.stencil_test); gl.stencilfuncseparate(gl.front, gl.less, 0.2, 1110011); to get the current stencil function, reference value, or other stencil information, query the following constants with getparameter(). gl.getparameter(gl.stencil_func); gl.getparameter(gl.stencil_value_mask); gl.getparameter(gl.stencil_ref); gl.getparameter(gl.stencil_back_func); gl.getparameter(gl.stencil_back_value_mask); gl.getparameter(gl.stencil_back_ref); gl.getparameter(gl.stencil_bits); specifications specification status comment webgl 1.0the definition of 'st...
WebGLRenderingContext.texParameter[fi]() - Web APIs
the webgl api set texture parameters. syntax void gl.texparameterf(glenum target, glenum pname, glfloat param); void gl.texparameteri(glenum target, glenum pname, glint param); parameters target a glenum specifying the binding point (target). possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map: a cube-mapped texture. when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture. gl.texture_2d_array: a two-dimensional 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 w...
WebGLRenderingContext.vertexAttrib[1234]f[v]() - Web APIs
bute arrays). the only way to change the values is by calling this function again. ...
WebGLRenderingContext - Web APIs
xt('webgl'); once you have the webgl rendering context for a canvas, you can render within it. the webgl tutorial has more information, examples, and resources on how to get started with webgl. if you require a webgl 2.0 context, see webgl2renderingcontext; this supplies access to an implementation of opengl es 3.0 graphics. constants see the webgl constants page. the webgl context the following properties and methods provide general information and functionality to deal with the webgl context: webglrenderingcontext.canvas a read-only back-reference to the htmlcanvaselement. might be null if it is not associated with a <canvas> element. webglrenderingcontext.commit() pushes frames back to the original htmlcanvaselement, if the context is not directly fixed to a specific canv...
WebGLSampler - Web APIs
webglsampler objects are not available in webgl 1. ...
WebGLShaderPrecisionFormat.precision - Web APIs
the read-only webglshaderprecisionformat.precision property returns the number of bits of precision that can be represented. for integer formats this value is always 0. examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float).precision; // 23 gl.getshaderprecisionformat(gl.fragment_shader, gl.low_int).precision; // 0 specifications specification status comment webgl 1.0the definition of 'webglshaderprecisionformat.precision' in that specification. recommendation initial definition. ...
WebGLShaderPrecisionFormat.rangeMax - Web APIs
the read-only webglshaderprecisionformat.rangemax property returns the base 2 log of the absolute value of the maximum value that can be represented. examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float).rangemax; // 127 gl.getshaderprecisionformat(gl.fragment_shader, gl.low_int).rangemax; // 24 specifications specification status comment webgl 1.0the definition of 'webglshaderprecisionformat.rangemax' in that specification. recommendation 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. ...
WebGLSync - Web APIs
Web › API › WebGLSync
webglsync objects are not available in webgl 1. ...
WebGLTexture - Web APIs
the webgltexture interface is part of the webgl api and represents an opaque texture object providing storage and state for texturing operations. description the webgltexture object does not define any methods or properties of its own and its content is not directly accessible. ...
WebGLUniformLocation - Web APIs
the webgluniformlocation interface is part of the webgl api and represents the location of a uniform variable in a shader program. description the webgluniformlocation object does not define any methods or properties of its own and its content is not directly accessible. when working with webgluniformlocation objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.getuniformlocation() webglrenderingcontext.uniform() examples getting an uniform location var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var location = gl.getuniformlocation(webglprogram, 'uniformname'); specifications specification status comment webgl 1.0the definition of 'webgluniformlocation' in that specification. ...
WebGLVertexArrayObject - Web APIs
the webglvertexarrayobject interface is part of the webgl 2 api, represents vertex array objects (vaos) pointing to vertex array data, and provides names for different sets of vertex data. when working with webglvertexarrayobject objects, the following methods are useful: webgl2renderingcontext.createvertexarray() webgl2renderingcontext.deletevertexarray() webgl2renderingcontext.isvertexarray() webgl2renderingcontext.bindvertexarray() webgl 1: the oes_vertex_array_object extension allows you to use vertex array objects in a webgl 1 context. examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ... // calls to bindbuffer or vertexattribpointer // which will be "recorded" in the vao // ... specifications specification status comment webg...
A basic 2D WebGL animation example - Web APIs
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 compileshader(id, type) { let code = document.getelementbyid(id).firstchild.nodevalue; let shader = gl.createshader(type); gl.shadersource(shader, code); gl.compileshader(shader); if (!gl.getshaderparameter(shader, gl.compile_status)) { console.log(`error compiling ${type === gl.vertex_shader ? "vertex" : "fr...
Clearing by clicking - Web APIs
illustration of how to combine webgl and user interaction. every time the user clicks the canvas or the button, the canvas is cleared with a new randomly chosen color. note how we embed the webgl function calls inside the event handler function. ...
Simple color animation - Web APIs
ndler. a click event handler additionally enables the basic user interaction of starting and stopping the animation. the timer and the timer handler function establish the animation loop, a set of drawing commands that are executed at a regular period (typically, every frame; in this case, once per second). ...
Animating objects with WebGL - Web APIs
amount to rotate in radians [0, 0, 1]); // axis to rotate around this rotates the modelviewmatrix by the current value of squarerotation, around the z axis. to actually animate, we need to add code that changes the value of squarerotation over time. ...
Animating textures in WebGL - Web APIs
video); } you've seen this code before. it's nearly identical to the image onload function in the previous example — except when we call teximage2d(), instead of passing an image object, we pass in the <video> element. webgl knows how to pull the current frame out and use it as a texture. then in main() in place of the call to loadtexture() in the previous example, we call inittexture() followed by setupvideo() . in the definition of render() if copyvideo is true, then we call updatetexture() each time just before we call the drawscene() function. const texture = inittexture(gl); const video = setupvideo('firefox.mp4'); var then = 0; // draw the scene repeatedly function render(now) { now *= 0.001; // convert to seconds const deltatime = now - then; then = n...
Creating 3D objects using WebGL - Web APIs
s by defining a color for each face, then uses a loop to assemble an array of all the colors for each of the vertices. const facecolors = [ [1.0, 1.0, 1.0, 1.0], // front face: white [1.0, 0.0, 0.0, 1.0], // back face: red [0.0, 1.0, 0.0, 1.0], // top face: green [0.0, 0.0, 1.0, 1.0], // bottom face: blue [1.0, 1.0, 0.0, 1.0], // right face: yellow [1.0, 0.0, 1.0, 1.0], // left face: purple ]; // convert the array of colors into a table for all the vertices. var colors = []; for (var j = 0; j < facecolors.length; ++j) { const c = facecolors[j]; // repeat each color four times for the four vertices of the face colors = colors.concat(c, c, c, c); } const colorbuffer = gl.createbuffer(); gl.bindbuffer(g...
Getting started with WebGL - Web APIs
les github repository. it's worth noting here that this series of articles introduces webgl itself; however, there are a number of frameworks available that encapsulate webgl's capabilities, making it easier to build 3d applications and games, such as three.js and babylon.js. preparing to render in 3d the first thing you need in order to use webgl for rendering is a canvas. the html fragment below declares a canvas that our sample will draw into. <body> <canvas id="glcanvas" width="640" height="480"></canvas> </body> preparing the webgl context the main() function in our javascript code, is called when our script is loaded. its purpose is to set up the webgl context and start rendering content. // // start here // function main() { const canvas = document.queryselector("#glcanvas"...
WebGL types - Web APIs
Web › API › WebGL API › Types
webgl 1 these types are used within a webglrenderingcontext. type web idl type description glenum unsigned long used for enums. see also the list of constants. glboolean boolean a boolean. glbitfield unsigned long a bit field that stores multiple, logical bits. used for example in webglrenderingcontext.clear(). glbyte byte 8-bit twos complement signed integer. glshort short 16-bit twos complement signed integer. glint long 32-bit twos complement signed integer. glsizei long used for sizes (e.g. width and height of the drawing buffer). glintptr long long special type for pointer arithmetic. ...
Lifetime of a WebRTC session - Web APIs
brtc 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 negotiation is performed, with one exception: media continues to flow across the original network connection until the new one is up and running. then media shifts to the new network connection and the old one is closed. note: different browsers support ice restart under different sets of conditions. not all browsers will perform ice restart due to network congestion, for example. if you need to change the configuration of the connection in some way (such as ch...
WebRTC Statistics API - Web APIs
d is video. this way, we look only at the video-related statistics for the local rtcrtpreceiver responsible for receiving the streamed media. commonly used statistics reference the rtcstatsreport object contains a map of named objects based one of the rtcstats dictionary's subclasses. upon looking up a statistic category by name, you get an object containing the corresponding data. the table below shows the statistic categories and the corresponding dictionaries; for each statistic category, the full hierarchy of rtcstats-based dictionaries are listed, so you can easily find all the available values. mapping of statistic category names to the dictionaries they implement statistic category name (rtcstatstype) description dictionaries implemented candidate-pair ...
WebSocket.readyState - Web APIs
the connection is not yet open. 1 open the connection is open and ready to communicate. 2 closing the connection is in the process of closing. 3 closed the connection is closed or couldn't be opened. ...
WebSocket.send() - Web APIs
Web › API › WebSocket › send
transmitted to the server over the websocket connection, increasing the value of bufferedamount by the number of bytes needed to contain the data. if the data can't be sent (for example, because it needs to be buffered but the buffer is full), the socket is closed automatically. syntax websocket.send("hello server!"); parameters data the data to send to the server. it may be one of the following types: usvstring a text string. the string is added to the buffer in utf-8 format, and the value of bufferedamount is increased by the number of bytes required to represent the utf-8 string. arraybuffer you can send the underlying binary data used by a typed array object; its binary data contents are queued in the buffer, increasing the value of bufferedamount by the requisite number...
Writing a WebSocket server in Java - Web APIs
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 bytes are the message. decoding algorithm decoded byte = encoded byte xor (position of en...
WebXR performance guide - Web APIs
ited set of memory storage slots for specific 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 var...
Web Animations API - Web APIs
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. ...
Web Bluetooth API - Web APIs
interfaces bluetooth returns a promise to a bluetoothdevice object with the specified options. bluetoothadvertisingdata provides advertising data about a particular bluetooth device. bluetoothcharacteristicproperties provides properties of a particular bluetoothremotegattcharacteristic. bluetoothdevice represents a bluetooth device inside a particular script execution environment. bluetoothremotegattcharacteristic represents a gatt characteristic, which is a basic data element that provides further information about a peripheral’s service. ...
Web Crypto API - Web APIs
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. ...
Web NFC API - Web APIs
interfaces ndefmessage interface that represents ndef messages that can be received from or sent to a compatible device or tag via ndefreader and ndefwriter objects respectively. a message is composed of metadata and ndef records. ndefreader interface that enables reading messages from compatible nfc devices or tags. the messages are represented as ndefmessage objects. ...
Web Speech API - Web APIs
nition object, which has a number of event handlers available for detecting when speech is input through the device's microphone. the speechgrammar interface represents a container for a particular set of grammar that your app should recognise. grammar is defined using jspeech grammar format (jsgf.) speech synthesis is accessed via the speechsynthesis interface, a text-to-speech component that allows programs to read out their text content (normally via the device's default speech synthesiser.) different voice types are represented by speechsynthesisvoice objects, and different parts of text that you want to be spoken are represented by speechsynthesisutterance objects. you can get these spoken by passing them to the speechsynthesis.speak() method. for more details on using these features,...
WheelEvent() - Web APIs
the wheelevent() constructor returns a newly created wheelevent object. syntax var wheelevent = new wheelevent(typearg, wheeleventinit); properties typearg is a domstring representing the name of the event. wheeleventinit optional is a wheeleventinit dictionary, having the following fields: "deltax", optional and defaulting to 0.0, is a double representing the horizontal scroll amount in the deltamode unit. "deltay", optional and defaulting to 0.0, is a double representing the vertical scroll amount in the deltamode unit. "deltaz", optional and defaulting to 0.0, is a double representing the scroll amount for the z-axis in the deltamode unit. "deltamode", optional and defaulting to 0, is a unsigned long representing the unit of the delta values scroll amount. permitted va...
WheelEvent - Web APIs
ent necessarily reflect the content's scrolling direction. therefore, do not rely on delta* properties to get the content's scrolling direction. instead, detect value changes to scrollleft and scrolltop of the target in the scroll event. ...
Window.alert() - Web APIs
Web › API › Window › alert
ters message optional a string you want to display in the alert dialog, or, alternatively, an object that is converted into a string and displayed. example window.alert("hello world!"); alert("hello world!"); both produce: notes the alert dialog should be used for messages which do not require any response on the part of the user, other than the acknowledgement of the message. the following text is shared between this article, dom:window.prompt and dom:window.confirm dialog boxes are modal windows - they prevent the user from accessing the rest of the program's interface until the dialog box is closed. for this reason, you should not overuse any function that creates a dialog box (or modal window). specification specification status comment html living s...
Window.close() - Web APIs
Web › API › Window › close
.open('moreinfo.htm'); } function closeopenedwindow() { openedwindow.close(); } closing the current window in the past, when you called the window object's close() method directly, rather than calling close() on a window instance, the browser closed the frontmost window, whether your script created that window or not. this is no longer the case; for security reasons, scripts are no longer allowed to close windows they didn't open. (firefox 46.0.1: scripts can not close windows, they had not opened) function closecurrentwindow() { window.close(); } specification specification status comment html living standardthe definition of 'window.close()' in that specification. living standard html5the definition of 'window.close()' in that specificatio...
Window.closed - Web APIs
Web › API › Window › closed
the window.closed read-only property indicates whether the referenced window is closed or not. syntax const isclosed = windowref.closed; value a boolean. possible values: true: the window has been closed. false: the window is open. examples change the url of a window from a popup the following example demonstrates how a popup window can change the url of the window that opened it. before attempting to change the url, it checks that the current window has an opener using the window.opener property and that the opener isn't closed: // check that an opener exists and is not closed if (window.opener && !window.opener.closed) { window.opener.location.href = 'http://www.mozilla.org'; } note that popups can only access the window that opened them. refreshing a previously opened po...
Window.confirm() - Web APIs
Web › API › Window › confirm
age); parameters message a string you want to display in the alert dialog. return value a boolean indicating whether ok (true) or cancel (false) was selected. if a browser is ignoring in-page dialogs, then the returned value is always false. example if (window.confirm("do you really want to leave?")) { window.open("exit.html", "thanks for visiting!"); } produces: notes the following text is shared between this article, dom:window.prompt and dom:window.alert dialog boxes are modal windows — they prevent the user from accessing the rest of the program's interface until the dialog box is closed. for this reason, you should not overuse any function that creates a dialog box (or modal window). regardless, there are good reasons to avoid using dialog boxes for confirmation. ...
Window.content - Web APIs
Web › API › Window › content
content (webpages), content is normally equivalent to top (except in the case of a webpage loaded in a sidebar, content still refers to the window of the currently selected tab). note: some examples use _content instead of content. the former has been deprecated for a long time, and you should use content in any new code. syntax var windowobject = window.content; example executing the following code in a chrome xul window with a <browser type="content-primary"/> element in it draws a red border around the first div on the page currently displayed in the browser: content.document.getelementsbytagname("div")[0].style.border = "solid red 1px"; specification none. see also working with windows in chrome code when accessing content documents from privileged code, be aware of xpcn...
Window.crypto - Web APIs
Web › API › Window › crypto
although the property itself is read-only, all of its methods (and the methods of its child object, subtlecrypto) are not read-only, and therefore vulnerable to attack by polyfill. although window.crypto is available on all windows, the returned crypto object only has one usable feature in insecure contexts: the getrandomvalues() method. in general, you should use this api only in secure contexts. ...
Window.customElements - Web APIs
ously registered custom elements. examples the most common example you'll see of this property being used is to get access to the customelementregistry.define() method to define and register a new custom element, e.g.: let customelementregistry = window.customelements; customelementregistry.define('my-custom-element', mycustomelement); however, it is usually shortened to something like the following: customelements.define('element-details', class extends htmlelement { constructor() { super(); const template = document .getelementbyid('element-details-template') .content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(template.clonenode(true)); } } ); see our web-components-examples repo for more usage examples. sp...
window.dump() - Web APIs
Web › API › Window › dump
ole.log(). privileged code can also use components.utils.reporterror and nsiconsoleservice to log messages to the error console/browser console. dump() is also available to xpcom components implemented in javascript, even though window is not the global object in components. it is also explicitly made available in sandboxes. however, this use of dump is not affected by the preference mentioned below -- it will always be shown. it is therefore advisable to either check this preference yourself or use a debugging preference of your own to make sure you don't send lots of debugging content to a user's console when they might not be interested in it at all. note that dump output from xpcom components goes to stderr, while dump called elsewhere will output to stdout. in gecko dump() is disabled ...
Window.external - Web APIs
Web › API › Window › external
the external property of the window api returns an instance of the external interface, which was intended to contain functions related to adding external search providers to the browser. however, this is now deprecated, and the contained methods are now dummy functions that do nothing as per spec. methods the external object has the following methods: method description addsearchprovider(descriptionurl) dummy function; does nothing. see autodiscovery of search plugins. issearchproviderinstalled() dummy function; does nothing. specifications specification status html living standardthe definition of 'external' in that specification. living standard ...
Window: hashchange event - Web APIs
the hashchange event is fired when the fragment identifier of the url has changed (the part of the url beginning with and following the # symbol). bubbles yes cancelable no interface hashchangeevent event handler onhashchange examples you can use the hashchange event in an addeventlistener method: window.addeventlistener('hashchange', function() { console.log('the hash has changed!') }, false); or use the onhashchange event handler property: function locationhashchanged() { if (location.hash === '#cool-feature') { console.log("you're visiting a cool feature!"); } } window.onhashchange = locationhashchanged; specifications specification status comment html living standardthe definition of 'has...
Window.history - Web APIs
Web › API › Window › history
at you should be aware of before using them. example history.back(); // equivalent to clicking back button history.go(-1); // equivalent to history.back(); notes for top-level pages you can see the list of pages in the session history, accessible via the history object, in the browser's dropdowns next to the back and forward buttons. for security reasons the history object doesn't allow the non-privileged code to access the urls of other pages in the session history, but it does allow it to navigate the session history. there is no way to clear the session history or to disable the back/forward navigation from unprivileged code. the closest available solution is the location.replace() method, which replaces the current item of the session history with the provided url. specifi...
Window.innerHeight - Web APIs
ewport of the closest frameset var intouterframesetheight = top.innerheight; // will return the height of the viewport of the outermost frameset fixme: link to an interactive demo here to change the size of a window, see window.resizeby() and window.resizeto(). to get the outer height of a window, i.e. the height of the whole browser window, see window.outerheight. graphical example the following figure shows the difference between outerheight and innerheight. specification specification status comment css object model (cssom) view modulethe definition of 'window.innerheight' in that specification. working draft initial definition ...
window.location - Web APIs
Web › API › Window › location
ation object, a document will be loaded using the url as if location.assign() had been called with the modified url. note that security settings, like cors, may prevent this to effectively happen. ...
Window.locationbar - Web APIs
<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>various dom tests</title> <script> var visible = window.locationbar.visible; </script> </head> <body> <p>various dom tests</p> </body> </html> specifications specification status comment html living standardthe definition of 'window.locationbar' in that specification. ...
Window.menubar - Web APIs
Web › API › Window › menubar
the window.menubar property returns the menubar object, whose visibility can be checked. syntax objref = window.menubar example the following complete html example demonstrates how the visible property of the menubar object is used. <html> <head> <title>various dom tests</title> <script> var visible = window.menubar.visible; </script> </head> <body> <p>various dom tests</p> </body> </html> specifications specification status comment html living standardthe definition of 'window.menubar' in that specification. living standard html5the definition of 'window.menubar' in that specification. recommendation ...
Window.mozAnimationStartTime - Web APIs
k in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. returns the time, in milliseconds since the epoch, at which animations started now should be considered to have started. this value should be used instead of, for example, date.now(), because this value will be the same for all animations started in this window during this refresh interval, allowing them to remain in sync with one another. this also allows javascript-based animations to remain synchronized with css transitions and smil animations triggered during the same refresh interval. syntax time = window.mozanimationstarttime; parameters time is the time in milliseconds since the epoch at which animations for the current window should be considered to have started. ...
Window.onbeforeinstallprompt - Web APIs
nt handler for processing a beforeinstallprompt, which is dispatched on devices when a user is about to be prompted to "install" a web application. its associated event may be saved for later and used to prompt the user at a more suitable time. syntax window.addeventlistener("beforeinstallprompt", function(event) { ... }); window.onbeforeinstallprompt = function(event) { ...}; example the following example uses the beforeinstallprompt event to make an install button operable, by using the event inside a click handler. window.addeventlistener("beforeinstallprompt", function(beforeinstallpromptevent) { beforeinstallpromptevent.preventdefault(); // prevents immediate prompt display // shows prompt after a user clicks an "install" button installbutton.addeventlistener("click", functi...
Window.outerHeight - Web APIs
the window.outerheight read-only property returns the height in pixels of the whole browser window, including any sidebar, window chrome, and window-resizing borders/handles. notes to change the size of a window, see window.resizeby() and window.resizeto(). to get the inner height of a window, i.e. the height of the page being displayed, see window.innerheight. graphical example the following figure shows the difference between outerheight and innerheight. specification specification status comment css object model (cssom) view modulethe definition of 'window.outerheight' in that specification. working draft ...
Window.pageYOffset - Web APIs
olling position to the maximum possible value if the attempted scroll would exceed the maximum. this prevents us from falling off the edge of the document. nobody wants to know what's out there. there might be dragons. css iframe { width: 620px; height: 450px; border: 1px solid black; } #info { margin-top: 20px; font: 16px "open sans", "helvetica", "arial"; } result the result follows. note that the frame's contents have been scrolled to show the section named "overview", and that the value of the pageyoffset property is shown with the corresponding value. specification specification status comment css object model (cssom) view modulethe definition of 'window.pageyoffset' in that specification. working draft ...
Window.releaseEvents() - Web APIs
summary releases the window from trapping events of a specific type. syntax window.releaseevents(eventtype) eventtype is a combination of the following values: event.abort, event.blur, event.click, event.change, event.dblclick, event.dragddrop, event.error, event.focus, event.keydown, event.keypress, event.keyup, event.load, event.mousedown, event.mousemove, event.mouseout, event.mouseover, event.mouseup, event.move, event.reset, event.resize, event.select, event.submit, event.unload. example window.releaseevents(event.keypress) notes note that you can pass a list of events to this method using the following syntax: window.releaseevents(event.keypress | event.keydown | event.keyup). see also window.captureevents ( ). specification this is not part of any specification. bro...
Window.requestFileSystem() - Web APIs
ication. do not use this method! syntax this method is prefixed with webkit in all browsers that implement it (that is, google chrome). window.requestfilesystem(type, size, successcallback[, errorcallback]); parameters type the type of storage to request. specify window.temporary if it's acceptable for the browser to delete the files at its own discretion, such as if storage space runs low, or window.persistent if you need the files to remain in place unless the user or the web site or app explicitly permit it. persistent storage requires that the user grant the site quota. size the amount of storage space you wish to have allocated for your app's use. successcallback a function which is invoked when the file system has been successfully obtained. the callback receives a single...
window.requestIdleCallback() - Web APIs
functions are generally called in first-in-first-out order; however, callbacks which have a timeout specified may be called out-of-order if necessary in order to run them before the timeout elapses. ...
Window: resize event - Web APIs
some earlier browsers it was possible to register resize event handlers on any html element. it is still possible to set onresize attributes or use addeventlistener() to set a handler on any element. however, resize events are only fired on the window object (i.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...
Window.screen - Web APIs
Web › API › Window › screen
the window property screen returns a reference to the screen object associated with the window. the screen object, implementing the screen interface, is a special object for inspecting properties of the screen on which the current window is being rendered. syntax let screenobj = window.screen; example if (screen.pixeldepth < 8) { // use low-color version of page } else { // use regular, colorful page } specifications specification status comment css object model (cssom) view modulethe definition of 'window.screen' in that specification. working draft initial definition. ...
Window.scrollbars - Web APIs
Web › API › Window › scrollbars
the window.scrollbars property returns the scrollbars object, whose visibility can be checked. syntax objref = window.scrollbars example the following complete html example shows how the visible property of the scrollbars object is used. <!doctype html> <html> <head> <title>various dom tests</title> <script> let visiblescrollbars = window.scrollbars.visible; </script> </head> <body> <p>various dom tests</p> </body> </html> specifications specification status comment html living standardthe definition of 'window.scrollbars' in that specification. living standard html5the definition of 'window.scrollbars' in that specification. recommendation ...
Window.sessionStorage - Web APIs
can be used to access the current origin's session storage space. exceptions securityerror the request violates a policy decision, or the origin is not a valid scheme/host/port tuple (this can happen if the origin uses the file: or data: scheme, for example). for example, the user may have their browser configured to deny permission to persist data for the specified origin. example the following snippet accesses the current origin's session storage object and adds data to it with storage.setitem(). sessionstorage.setitem('mycat', 'tom'); the following example autosaves the contents of a text field, and if the browser is refreshed, restores the text field content so that no writing is lost. // get the text field that we're going to track let field = document.getelementbyid("field");...
Window.sidebar - Web APIs
Web › API › Window › sidebar
obsolete since firefox 23 (only present in seamonkey). end users can use the "load this bookmark in the sidebar" option instead. also see creating a firefox sidebar. addpersistentpanel(title, contenturl, "") adds a sidebar panel, which is able to work in the background. ...
Window: unhandledrejection event - Web APIs
pt when a javascript promise that has no rejection handler is rejected; typically, this is the window, but may also be a worker. this is useful for debugging and for providing fallback error handling for unexpected situations. bubbles no cancelable yes interface promiserejectionevent event handler property onunhandledrejection usage notes allowing the unhandledrejection event to bubble will eventually result in an error message being output to the console. you can prevent this by calling preventdefault() on the promiserejectionevent; see preventing default handling below for an example. examples here we have a few examples showing ways you can make use of the unhandledrejection event. the event includes two useful pieces of informatio...
Window.window - Web APIs
Web › API › Window › window
in web pages, the window object is also a global object. this means: global variables of your script are in fact properties of window: var global = {data: 0}; alert(global === window.global); // displays "true" you can access built-in properties of the window object without having to type window. prefix: settimeout("alert('hi!')", 50); // equivalent to using window.settimeout. ...
WindowEventHandlers.onafterprint - Web APIs
the onafterprint property of the windoweventhandlers mixin is the eventhandler for processing afterprint events for the current window. these events are raised after the user prints, or if they abort the print dialog. the beforeprint and afterprint events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has completed. in general, you should prefer the use of an @media print css at-rule, but it may be necessary to use these events in some cases. syntax window.addeventlistener("afterprint", function(event) { ... }); window.onafterprint = function(event) { ... }; specification specification status comment html living standardthe definition of 'onafterprint' in that speci...
WindowEventHandlers.onbeforeprint - Web APIs
in general, you should prefer the use of an @media print css at-rule, but it may be necessary to use these events in some cases. ...
WindowEventHandlers.onhashchange - Web APIs
function hashhandler() { console.log('the hash has changed!'); } window.addeventlistener('hashchange', hashhandler, false); overriding the hash this function sets a new hash dynamically, setting it randomly to one of two values. function changehash() { location.hash = (math.random() > 0.5) ? 'location1' : 'location2'; } the hashchange event the dispatched hashchange event has the following properties: field type description newurl domstring the new url to which the window is navigating. oldurl domstring the previous url from which the window was navigated. polyfill for event.newurl and event.oldurl // let this snippet run before your hashchange event binding code if (!window.hashchangeevent)(function(){ var lasturl = docume...
WindowEventHandlers.onpopstate - Web APIs
'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. ...
WindowOrWorkerGlobalScope.btoa() - Web APIs
u can encode control characters such as ascii values 0 through 31. syntax var encodeddata = scope.btoa(stringtoencode); parameters stringtoencode the binary string to encode. return value an ascii string containing the base64 representation of stringtoencode. exceptions invalidcharactererror the string contained a character that did not fit in a single byte. see "unicode strings" below for more detail. example const encodeddata = window.btoa('hello, world'); // encode a string const decodeddata = window.atob(encodeddata); // decode the string unicode strings the btoa() function takes a javascript string as a parameter. in javascript strings are represented using the utf-16 character encoding: in this encoding, strings are represented as a sequence of 16-bit (2 byte) units...
WindowOrWorkerGlobalScope.caches - Web APIs
the caches read-only property of the windoworworkerglobalscope interface returns the cachestorage object associated with the current context. this object enables functionality such as storing assets for offline use, and generating custom responses to requests. syntax var mycachestorage = self.caches; // or just caches value a cachestorage object. example the following example shows how you'd use a cache in a service worker context to store assets offline. this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.addall([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg',...
WindowOrWorkerGlobalScope.clearTimeout() - Web APIs
d) parameters timeoutid the identifier of the timeout you want to cancel. this id was returned by the corresponding call to settimeout(). it's worth noting that the pool of ids used by settimeout() 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. var alarm = { remind: function(amessage) { alert(amessage); this.timeoutid = undefined; }, setup: function() { if (typeof this.timeoutid === 'number') { this.cancel(); } this.timeou...
self.createImageBitmap() - Web APIs
decoded using color space conversion. either none or default (default). the value default indicates that implementation-specific behavior is used. resizewidth: a long integer that indicates the output width. resizeheight: a long integer that indicates the output height. resizequality: specifies the algorithm to be used for resizing the input to match the output dimensions. one of pixelated, low (default), medium, or high. return value a promise which resolves to an imagebitmap object containing bitmap data from the given rectangle. example creating sprites from a sprite sheet this example loads a sprite sheet, extracts individual sprites, and then renders each sprite to the canvas. a sprite sheet is an image containing multiple smaller images, each of which you want to be able...
WindowOrWorkerGlobalScope.indexedDB - Web APIs
the indexeddb read-only property of the windoworworkerglobalscope mixin provides a mechanism for applications to asynchronously access the capabilities of indexed databases. syntax var idbfactory = self.indexeddb; value an idbfactory object. example the following code creates a request for a database to be opened asychronously, after which the database is opened when the request's onsuccess handler is fired: var db; function opendb() { var dbopenrequest = window.indexeddb.open('todolist'); dbopenrequest.onsuccess = function(e) { db = dbopenrequest.result; } } specifications specification status comment indexed database api draftthe definition of 'indexeddb' in that specification. recommendation defined in a windoworworkerglobalscope partial in the...
WindowOrWorkerGlobalScope.origin - Web APIs
the origin read-only property of the windoworworkerglobalscope interface returns the origin of the global scope, serialized as a string. syntax var myorigin = self.origin; // or just origin value a usvstring. examples executed from inside a worker script, the following snippet will log the worker's global scope's origin to the console each time it receives a message onmessage = function() { console.log(self.origin); }; if the origin is not a scheme/host/port tuple (say you are trying to run it locally, i.e. via file:// url), origin will return the string "null". specifications specification status comment html living standardthe definition of 'windoworworkerglobalscope.origin' in that specification. living standard initial definition. ...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
it creates a microtask by using a promise that resolves immediately. if (typeof window.queuemicrotask !== "function") { window.queuemicrotask = function (callback) { promise.resolve() .then(callback) .catch(e => settimeout(() => { throw e; })); // report exceptions }; } specifications specificati...
WindowOrWorkerGlobalScope - Web APIs
note: windoworworkerglobalscope is a mixin and not an interface; you can't actually create an object of type windoworworkerglobalscope. properties these properties are defined on the windoworworkerglobalscope mixin, and implemented by window and workerglobalscope. ...
Worker.onmessage - Web APIs
Web › API › Worker › onmessage
presents an eventhandler, that is a function to be called when the message event occurs. these events are of type messageevent and will be called when the worker's parent receives a message (i.e. from the dedicatedworkerglobalscope.postmessage method). note: the message payload is available in the message event's data property. syntax myworker.onmessage = function(e) { ... } example the following code snippet shows creation of a worker object using the worker() constructor. messages are passed to the worker when the value inside the form input first changes. an onmessage handler is also present, to deal with messages that are passed back from the worker. var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value,second.value]); console...
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 ...
Worker - Web APIs
Web › API › Worker
geerror property. rejectionhandled fires every time a promise rejects, regardless of whether or not there is a handler to catch the rejection. also available through the onrejectionhandled event handler property. unhandledrejection fires when a promise rejects with no handler to catch the rejection. also available using the onunhandledrejection event handler property. ...
WorkerGlobalScope.close() - Web APIs
the close() method of the workerglobalscope interface discards any tasks queued in the workerglobalscope's event loop, effectively closing this particular scope. syntax self.close(); example if you wanted to close your worker instance from inside the worker itself, you could call the following: close(); close() and self.close() are effectively equivalent — both represent close() being called from inside the worker's inner scope. note: there is also a way to stop the worker from the main thread: the worker.terminate method. ...
WorkerGlobalScope.console - Web APIs
the console read-only property of the workerglobalscope interface returns a console object providing access to the browser console for the worker. syntax var consoleobj = self.console; value a console object. example this property allows you to have access to a browser console for debugging purposes, inside a worker. so for example you could call console.log('test'); inside a worker (which would basically be the equivalent of self.console.log('test');, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), to return a test message out to the browser console. if you are calling console.log() from a dedicatedworkerglobalscope or other worker scope that acts on a single loaded window, that tab's web console will receive the logs. however,...
WorkerGlobalScope.importScripts() - Web APIs
objects representing the scripts to be imported. these paths are relative to html document base url. return value none. exceptions networkerror imported scripts were not served with a valid javascript mime type (i.e. text/javascript). example if you had some functionality written in a separate script called foo.js that you wanted to use inside worker.js, you could import it using the following line: importscripts('foo.js'); importscripts() and self.importscripts() are effectively equivalent — both represent importscripts() being called from inside the worker's inner scope. specifications specification status comment html living standardthe definition of 'importscripts()' in that specification. living standard ...
WorkerGlobalScope.onclose - Web APIs
summary the onclose property of the workerglobalscope interface represents an eventhandler to be called when the close event occurs and bubbles through the worker. this non-standard event handler was only implemented by a few browsers and has been removed from all or nearly all of them. syntax self.onclose = function() { ... }; example the following code snippet shows an onclose handler set inside a worker: self.onclose = function() { console.log('your worker instance has been closed'); } specifications this feature is no longer defined in any specifications. ...
WorkerGlobalScope.onerror - Web APIs
the onerror property of the workerglobalscope interface represents an eventhandler to be called when the error event occurs and bubbles through the worker. syntax self.onerror = function() { ... }; example the following code snippet shows an onerror handler set inside a worker: self.onerror = function() { console.log('there is an error inside your worker!'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onerror' in that specification. living standard ...
WorkerGlobalScope.onlanguagechange - Web APIs
the onlanguagechange property of the workerglobalscope interface represents an eventhandler to be called when the languagechange event occurs and bubbles through the worker. syntax self.onlanguagechange = function() { ... }; example the following code snippet shows an onlanguagechange handler set inside a worker: self.onlanguagechange = function() { console.log('your preferred language settings have been changed'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onlanguagechange' in that specification. living standard ...
WorkerGlobalScope.onoffline - Web APIs
the onoffline property of the workerglobalscope interface represents an eventhandler to be called when the offline event occurs and bubbles through the worker. syntax self.onoffline = function() { ... }; example the following code snippet shows an onoffline handler set inside a worker: self.onoffline = function() { console.log('your worker is now offline'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onoffline' in that specification. living standard ...
WorkerGlobalScope.ononline - Web APIs
the ononline property of the workerglobalscope interface represents an eventhandler to be called when the online event occurs and bubbles through the worker. syntax self.ononline = function() { ... }; example the following code snippet shows an ononline handler set inside a worker: self.ononline = function() { console.log('your worker is now online'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.ononline' in that specification. living standard ...
WorkerGlobalScope.performance - Web APIs
bj = self.performance; return value a performance object. example if you called console.log(performance); inside a worker (which would basically be the equivalent of self.console.log(self.performance);, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), you will get a workerperformance object written to the console — something like the following: workerperformance {now: function} __proto__: workerperformance constructor: function workerperformance() { [native code] } now: function now() { [native code] } __proto__: object you could use this performance object to return performance data, as you might do with a normal performance object. note: firefox has a bug with using console.log inside shared/service workers (see ...
WorkerGlobalScope.self - Web APIs
rkerglobalscope, sharedworkerglobalscope, or serviceworkerglobalscope. syntax var selfref = self; value a global scope object (differs depending on the type of worker you are dealing with, as indicated above). ...
WorkerLocation - Web APIs
ing the domain of the url of the script executed in the worker. urlutilsreadonly.origin read only returns a domstring containing the canonical form of the origin of the specific location. urlutilsreadonly.port read only is a domstring containing the port number of the url of the script executed in the worker. urlutilsreadonly.pathname read only is a domstring containing an initial '/' followed by the path of the url of the script executed in the worker. urlutilsreadonly.search read only is a domstring containing a '?' followed by the parameters of the url of the script executed in the worker. urlutilsreadonly.hash read only is a domstring containing a '#' followed by the fragment identifier of the url of the script executed in the worker. methods the workerlocation interface...
WorkerNavigator.connection - Web APIs
the workernavigator.connection read-only property returns a networkinformation object containing information about the system's connection, such as the current bandwidth of the user's device or whether the connection is metered. this could be used to select high definition content or low definition content based on the user's connection. syntax connectioninfo = self.navigator.connection specifications specification status comment network information apithe definition of 'navigator.connection' in that specification. draft initial specification ...
WorkerNavigator - Web APIs
such an object is initialized for each worker and is available via the workerglobalscope.navigator property obtained by calling window.self.navigator. properties the workernavigator interface implements properties from the navigatorid, navigatorlanguage, navigatoronline, navigatordatastore, and navigatorconcurrenthardware interfaces. workernavigator.connectionread only provides a networkinformation object containing information about the network connection of a device. ...
Worklet - Web APIs
Web › API › Worklet
the worklet interface is a lightweight version of web workers and gives developers access to low-level parts of the rendering pipeline. with worklets, you can run javascript and webassembly code to do graphics rendering or audio processing where high performance is required. worklet types worklets are restricted to specific use cases; they cannot be used for arbitrary computations like web workers. the worklet interface abstracts properties and methods common to all kind of worklets, and cannot be created directly. instead, you can use one of the following classes: name description location specification paintworklet for programmatically generating an image where a css property expects a file. access this interface through css.paintworklet.
WritableStream.getWriter() - Web APIs
lestreamdefaultwriter and locks the stream to that instance. while the stream is locked, no other writer can be acquired until this one is released. syntax var writer = writablestream.getwriter(); parameters none. return value a writablestreamdefaultwriter object instance. exceptions typeerror the stream you are trying to create a writer for is not a writablestream. examples the following example illustrates several features of this interface. it shows the creation of the writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is use...
WritableStream - Web APIs
onger 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. writablestream.getwriter() returns a new instance of writablestreamdefaultwriter and locks the stream to that instance. while the stream is locked, no other writer can be acquired until this one is released. examples the following example illustrates several features of this interface. it shows the creation of the writablestream with a custom sink and an api-supplied queueing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is us...
WritableStreamDefaultController - Web APIs
when constructing a writablestream, the underlying sink is given a corresponding writablestreamdefaultcontroller instance to manipulate. constructor none. writablestreamdefaultcontroller instances are created automatically during writablestream construction. properties none. methods writablestreamdefaultcontroller.error() causes any future interactions with the associated stream to error. ...
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
d use the writablestream.getwriter() method. syntax var writablestreamdefaultwriter = new writablestreamdefaultwriter(stream); parameters stream the writablestream to be written to. return value an instance of the writablestreamdefaultwriter object. exceptions typeerror the provided stream value is not a writablestream, or it is locked to another writer already. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. fin...
WritableStreamDefaultWriter.close() - Web APIs
the stream). syntax var promise = writablestreamdefaultwriter.close(); parameters none. return value a promise, which fulfills with the undefined if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. exceptions typeerror the stream you are trying to close is not a writablestream. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. fin...
WritableStreamDefaultWriter.ready - Web APIs
the ready read-only property of the writablestreamdefaultwriter interface returns a promise that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. syntax var promise = writablestreamdefaultwriter.ready; value a promise. example the following example shows two uses of the ready property. the first uses ready to ensure that the writablestream is done writing and thus able to receive data before sending a binary chunk. the second also checks whether the the writablestream is done writing, but this time because the writing must be finished before the writer can be closed. function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter v...
WritableStreamDefaultWriter.write() - Web APIs
twriter.write(chunk); parameters chunk a block of binary data to pass to the writablestream. return value a promise, which fulfills with the undefined upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. exceptions typeerror the target stream is not a writable stream, or it does not have an owner. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. fin...
XDomainRequest - Web APIs
e defined, even as an empty function, or xdomainrequest may not fire onload for duplicate requests. security the xdomainrequest is built to be secure in multiple ways. the origin's security protocol must match that of the requested url. (http to http, https to https). if these do not match, the request will error "access is denied". the requested url's server must have the access-control-allow-origin header set to either all ("*") or to include the origin of the request. specifications this interface and its methods are non-standard. ...
XMLDocument - Web APIs
the xmldocument interface represents an xml document. it inherits from the generic document and does not add any specific methods or properties to it: nevertheless, several algorithms behave differently with the two types of documents. ...
Using XMLHttpRequest in IE6 - Web APIs
xmlhttprequest was first introduced by microsoft in internet explorer 5.0 as an activex control. however, in ie7 and other browsers xmlhttprequest is a native javascript object. ...
XMLHttpRequest() - Web APIs
st(paramsdictionary); parameters (non-standard) objparameters there are two flags you can set: mozanon boolean: setting this flag to true will cause the browser not to expose the origin and user credentials when fetching resources. most important, this means that cookies will not be sent unless explicitly added using setrequestheader. mozsystem boolean: setting this flag to true allows making cross-site connections without requiring the server to opt-in using cors. requires setting mozanon: true, i.e. this can't be combined with sending cookies or other user credentials. this only works in privileged (reviewed) apps (bug 692677); it does not work on arbitrary webpages loaded in firefox ...
XMLHttpRequest.getAllResponseHeaders() - Web APIs
charset=utf-8\r\n connection: keep-alive\r\n strict-transport-security: 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()...
XMLHttpRequest.readyState - Web APIs
open() not called yet. 1 opened open() has been called. 2 headers_received send() has been called, and headers and status are available. 3 loading downloading; responsetext holds partial data. 4 done the operation is complete. unsent the xmlhttprequest client has been created, but the open() method hasn't been called yet. opened open() method has been invoked. ...
XMLHttpRequest.responseText - Web APIs
syntax var resulttext = xmlhttprequest.responsetext; value a domstring which contains either the textual data received using the xmlhttprequest or null if the request failed or "" if the request has not yet been sent by calling send(). while handling an asynchronous request, the value of responsetext always has the current content received from the server, even if it's incomplete because the data has not been completely received yet. ...
XMLHttpRequest.sendAsBinary() - Web APIs
use arraybufferview instead. another possible approach to send binary data is the stringview non native typed arrays superclass in conjunction with the send() method. ...
XMLHttpRequest.setRequestHeader() - Web APIs
to the end of the existing header's content. if no accept header has been set using this, an accept header with the type "*/*" is sent with the request when send() is called. for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. note: for your custom fields, you may encounter a "not allowed by access-control-allow-headers in preflight response" exception when you send requests across domains. in this situation, you need to set up the access-control-allow-headers in your response header at server side. syntax xmlhttprequest.setrequestheader(header, value) parameters header the name of the header whose value is to be set. value the value to set as the body of the header. ...
XMLHttpRequest.status - Web APIs
is 0. browsers also report a status of 0 in case of xmlhttprequest errors. ...
XMLHttpRequest.statusText - Web APIs
t, statustext will assume the default value "ok". ...
XMLHttpRequest.upload - Web APIs
the xmlhttprequest upload property returns an xmlhttprequestupload object that can be observed to monitor an upload's progress. it is an opaque object, but because it's also an xmlhttprequesteventtarget, event listeners can be attached to track its process. the following events can be triggered on an upload object and used to monitor the upload: event event listener description loadstart onloadstart the upload has begun. progress onprogress periodically delivered to indicate the amount of progress made so far. abort onabort the upload operation was aborted. error onerror the upload failed due to an error. load onload the upload completed successfully. timeout ontimeout the upload timed ...
XMLHttpRequest - Web APIs
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. ...
XMLHttpRequestEventTarget - Web APIs
xmlhttprequesteventtarget is the interface that describes the event handlers you can implement in an object that will handle events for an xmlhttprequest. ...
XMLHttpRequestResponseType - Web APIs
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, the value of response is always null. you ...
XMLSerializer.serializeToString() - Web APIs
to issues with the content's compatibility with xml serialization. syntaxerror a serialization of html was requested but could not succeed due to the content not being well-formed. usage notes compatible node types the specified root node—and all of its descendants—must be compatible with the xml serialization algorithm. the root node itself must be either a node or attr object. the following types are also permitted as descendants of the root node, in addition to node and attr: documenttype document documentfragment element comment text processinginstruction attr if any other type is encountered, a typeerror exception is thrown. notes on the resulting xml there are some things worth noting about the xml output by serializetostring(): for xml serializations, elemen...
XMLSerializer - Web APIs
hich returns the xml equivalent of the document. inserting nodes into a dom based on xml this example uses the element.insertadjacenthtml() method to insert a new dom node into the body of the document, based on xml created by serializing an element object. note: in the real world, you should usually instead call importnode() method to import the new node into the dom, then call one of the following methods to add the node to the dom tree: the document and element methods append() and prepend() the node.replacewith() method (to replace an existing node with the new one) the document.insertadjacentelement() and element.insertadjacentelement() methods. because insertadjacenthtml() accepts a string and not a node as its second parameter, xmlserializer is used to first convert the nod...
XPathEvaluator.createExpression() - Web APIs
ompiled form of the xpath expression. exceptions invalid_expression_err if the expression is not legal according to the rules of the xpathevaluator, an xpathexception of type invalid_expression_err is raised. namespace_err if the expression contains namespace prefixes which cannot be resolved by the specified xpathnsresolver, a domexception of type namespace_error is raised. example the following example shows the use of the evaluate() method. html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = resul...
XPathEvaluator - Web APIs
the xpathevaluator interface allows to compile and evaluate xpath expressions. it is implemented by the document interface. methods xpathevaluator.createexpression() creates a parsed xpath expression with resolved namespaces. xpathevaluator.creatensresolver() adapts any dom node to resolve namespaces allowing the xpath expression to be evaluated relative to the context of the node where it appeared within the document. xpathevaluator.evaluate() evaluates an xpath expression string and returns a result of the specified type if possible. example the following example shows the use of the xpathevaluator interface. html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expressi...
XPathExpression - Web APIs
n from its dom tree. this is useful when an expression will be reused in an application, because it is just compiled once and all namespace prefixes which occur within the expression are preresolved. objects of this type are created by calling xpathevaluator.createexpression(). methods xpathexpression.evaluate() evaluates the xpath expression on the given node or document. example the following example shows the use of the xpathexpression interface. html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression(xpath); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent =...
XPathResult.booleanValue - Web APIs
alue of a result with xpathresult.resulttype being boolean_type. note: this feature is available in web workers. syntax var value = result.booleanvalue; return value the return value is the boolean value of the xpathresult returned by document.evaluate(). exceptions type_err in case xpathresult.resulttype is not boolean_type, an xpathexception of type type_err is thrown. example the following example shows the use of the booleanvalue property. html <div>xpath example</div> <p>text is 'xpath example': <output></output></p> javascript var xpath = "//div/text() = 'xpath example'"; var result = document.evaluate(xpath, document, null, xpathresult.boolean_type, null); document.queryselector("output").textcontent = result.booleanvalue; result specifications specificat...
XPathResult.invalidIteratorState - Web APIs
rator has become invalid. it is true if xpathresult.resulttype is unordered_node_iterator_type or ordered_node_iterator_type and the document has been modified since this result was returned. note: this feature is available in web workers. syntax var iteratorstate = result.invaliditeratorstate; return value a boolean value indicating whether the iterator has become invalid. example the following example shows the use of the invaliditeratorstate property. html <div>xpath example</div> <p>iterator state: <output></output></p> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.any_type, null); // invalidates the iterator state document.queryselector("div").remove(); document.queryselector("output").textcontent = result.invaliditeratorst...
XPathResult.iterateNext() - Web APIs
eratenext(); return value the next node within the node set of the xpathresult. exceptions type_err in case xpathresult.resulttype is not unordered_node_iterator_type or ordered_node_iterator_type, an xpathexception of type type_err is thrown. invalid_state_err if the document is mutated since the result was returned, an xpathexception of type invalid_state_err is thrown. example the following example shows the use of the iteratenext() method. html <div>xpath example</div> <div>tag names of the matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.any_type, null); var node = null; var tagnames = []; while(node = result.iteratenext()) { tagnames.push(node.localname); } document.queryselector("ou...
XPathResult.numberValue - Web APIs
c value of a result with xpathresult.resulttype being number_type. note: this feature is available in web workers. syntax var value = result.numbervalue; return value the return value is the numeric value of the xpathresult returned by document.evaluate(). exceptions type_err in case xpathresult.resulttype is not number_type, an xpathexception of type type_err is thrown. example the following example shows the use of the numbervalue property. html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "count(//div)"; var result = document.evaluate(xpath, document, null, xpathresult.number_type, null); document.queryselector("output").textcontent = result.numbervalue; result specifications specification status c...
XPathResult.resultType - Web APIs
ame order that they appear in the document. any_unordered_node_type 8 a result node-set containing any single node that matches the expression. the node is not necessarily the first node in the document that matches the expression. first_ordered_node_type 9 a result node-set containing the first node in the document that matches the expression. example the following example shows the use of the resulttype property. html <div>xpath example</div> <div>is xpath result a node set: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.any_type, null); document.queryselector("output").textcontent = result.resulttype >= xpathresult.unordered_node_iterator_type && result.resulttype <= xp...
XPathResult.singleNodeValue - Web APIs
r first_ordered_node_type. note: this feature is available in web workers. syntax var value = result.singlenodevalue; return value the return value is the node value of the xpathresult returned by document.evaluate(). exceptions type_err in case xpathresult.resulttype is not any_unordered_node_type or first_ordered_node_type, an xpathexception of type type_err is thrown. example the following example shows the use of the singlenodevalue property. html <div>xpath example</div> <div>tag name of the element having the text content 'xpath example': <output></output></div> javascript var xpath = "//*[text()='xpath example']"; var result = document.evaluate(xpath, document, null, xpathresult.first_ordered_node_type, null); document.queryselector("output").textcontent = result.single...
XPathResult.snapshotItem() - Web APIs
es not become invalid, but may not correspond to the current document if it is mutated. syntax var node = result.snapshotitem(i); return value the node at the given index within the node set of the xpathresult. exceptions type_err in case xpathresult.resulttype is not unordered_node_snapshot_type or ordered_node_snapshot_type, an xpathexception of type type_err is thrown. example the following example shows the use of the snapshotitem() method. html <div>xpath example</div> <div>tag names of the matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.ordered_node_snapshot_type, null); var node = null; var tagnames = []; for(var i = 0; i < result.snapshotlength; i++) { var node = result.snapshotit...
XPathResult.snapshotLength - Web APIs
in the result snapshot. note: this feature is available in web workers. syntax var snapshotlength = result.snapshotlength; return value an integer value representing the number of nodes in the result snapshot. exceptions type_err in case xpathresult.resulttype is not unordered_node_snapshot_type or ordered_node_snapshot_type, an xpathexception of type type_err is thrown. example the following example shows the use of the snapshotlength property. html <div>xpath example</div> <div>number of matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.ordered_node_snapshot_type, null); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification...
XPathResult.stringValue - Web APIs
ng value of a result with xpathresult.resulttype being string_type. note: this feature is available in web workers. syntax var value = result.stringvalue; return value the return value is the string value of the xpathresult returned by document.evaluate(). exceptions type_err in case xpathresult.resulttype is not string_type, an xpathexception of type type_err is thrown. example the following example shows the use of the stringvalue property. html <div>xpath example</div> <div>text content of the &lt;div&gt; above: <output></output></div> javascript var xpath = "//div/text()"; var result = document.evaluate(xpath, document, null, xpathresult.string_type, null); document.queryselector("output").textcontent = result.stringvalue; result specifications specification...
XRBoundedReferenceSpace.boundsGeometry - Web APIs
each point is treated as a two-dimensional point, and must be located at ground level (that is, its y coordinate must be 0). this boundary is typically configured by the user, using the software that controls their xr hardware. this may be done by walking the border of the space they wish to use, or by drawing the shape of their room using their xr input device. ...
XRInputSource.gripSpace - Web APIs
s shaped like a straight rod, held in the user's fist. the native origin of the grip space is located at the centroid—the center of mass—of the user's fist, tracking the position of the user's hand. the coordinate system for the left hand's grip space. the coordinate system for the right hand's grip space. as shown in the diagram above, the coordinate system is oriented as follows: the x-axis is perpendicular to the palm of the user's hand, with the direction extending outward from the back of the hand being +x if the controller is in the user's right hand or -x if the controller is in the left hand. the z-axis along the length of the rod, parallel to the user's palm and along the length of their grip. +z is in the direction of the user's thumb, and -z is in the oppos...
XRInputSource.handedness - Web APIs
tsource property handedness indicates which of the user's hands the webxr input source is associated with, or if it's not associated with a hand at all. syntax let hand = xrinputsource.handedness; value a domstring indicating whether the input controller is held in one of the user's hands, and if it is, which hand. the value, which comes from the xrhandedness enumerated type, is one of the following: none the input controller is not associated with one of the user's hands. 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. usage notes if the input source is not a device associated with a user's hand (whether by being held, attached, or worn), ...
XRInputSource.targetRayMode - Web APIs
rce.targetraymode; value a domstring taken from the xrtargetraymode enumerated type, indicating which method to use when generating and presenting the target ray to the user. the possible values are: gaze the user is using a gaze-tracking system (or gaze input) which detects the direction in which the user is looking. the target ray will be drawn originating at the viewer's eyes and will follow the direction in which they'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 direct...
XRInputSource.targetRaySpace - Web APIs
ace. the exact meaning of this space varies, however, depending on the mode: every gaze input (targetraymode value of gaze), shares the same xrspace object as their target ray space, since the gaze input comes from the viewer'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 ...
XRInputSource - Web APIs
squeeze action should correspond to a gripping act in reality, such as taking hold of an object or pressing a trigger on a tool or weapon. when a squeeze action begins, such as by the user pressing the trigger or tightening their grip, a squeezestart event is sent to the xrsession. once the action is completed and the user has released the trigger or the grip, a squeeze event is sent. this is followed by a squeezeend, which is also sent if the action is aborted rather than completed. if the device has a button or other pressable input control, it is a primary input source, and this button is a primary action. a primary action may occur when the user presses a button, clicks on a touchpad or the top button of a thumb stick, or uses a hand gesture or spoken command that invokes the button-lik...
XRInputSourceArray.length - Web APIs
ber of items in the input source list represented by the xrinputsourcearray object. syntax let inputsourcecount = xrinputsourcearray.length; value an integer value indicating the number of xrinputsource objects representing webxr input sources are includled in the array. examples in this example, a game that requires at least one input source uses length to check this before proceeding to allow the user to play the game. let sources = xrsession.inputsources; if (sources.length === 0) { showalertdialog("you need to have at least one controller to play super duper shark jump fest 9000.", [ { label: "shop now", url: "https://www.amazon.com/s?k=vr+controllers" }, { label: "quit" handler: quitgame } ]); } here, ...
XRInputSourceEvent.inputSource - Web APIs
ppropriately given the particulars of the user input device being manipulated. syntax let inputsource = xrinputsourceevent.inputsource; value an xrinputsource object identifying the source of the user input event. this event indicates an action the user has taken using a webxr input controller, such as a hand controller, motion sensing device, or other input apparatus. example the snippet below shows a handler for the select event which looks specifically for events which happen on gaze input devices. the device type is identified by looking at the xrinputsource in inputsource and its targetraymode property. xrsession.onselect = event => { let source = event.inputsource; if (source.targetraymode == "gaze") { /* handle selection using a gaze input */ } }; specifications ...
XRInputSourceEvent - Web APIs
rce has fully completed a primary squeeze action. squeezeend sent 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 */ ...
XRInputSourceEventInit - Web APIs
the xrinputsourceeventinit dictionary is used when calling the xrinputsourceevent() constructor to provide configuration options for the newly-created xrinputsourceevent object to take on. properties the xrinputsourceeventinit dictionary inherits properties from the eventinit dictionary. it also offers the following: frame an xrframe object representing the event frame during which the event took place. this event is not associated with the animation process, and has no viewer information contained within it. inputsource an xrinputsource object representing the input device from which the event is being sent. specifications specification status comment webxr device apithe definition of 'xrinputsourceeventinit' in that specification. working draft ...
XRInputSourcesChangeEvent() - Web APIs
ourceschange. 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 xrinputsourceschangeevent object indicating that a single new input source, described by an xrinputsource object named newinputsource, has been added to the system. let iscevent = new xrinputsourceschangeevent("inputsourceschange", { session: xrsession, added: [newinputsource], removed: [] }); specifications specification ...
XRInputSourcesChangeEvent.added - Web APIs
the read-only xrinputsourceschangeevent property added is a list of zero or more input sources, each identified using an xrinputsource object, which have been newly made available for use. syntax let addedinputs = xrinputsourceschangeevent.added; value an array of zero or more xrinputsource objects, each representing one input device added to the xr system. examples the example below creates a handler for the inputsourceschange event that processes the lists of added and removed from the webxr system. it looks for new and removed devices whose targetraymode is tracked-pointer. xrsession.oninputsourcescchange = event => { for (let input of event.added) { if (input.targetraymode == "tracked-pointer") { addedpointerdevice(input); } } for (let input of event.removed)...
XRInputSourcesChangeEvent.removed - Web APIs
the read-only xrinputsourceschangeevent property removed is an array of zero or more xrinputsource objects representing the input sources which have been removed from the xrsession. syntax removedinputs = xrinputsourceschangeevent.removed; value an array of zero or more xrinputsource objects, each representing one input device removed from the xr system. examples the example below creates a handler for the inputsourceschange event that processes the lists of added and removed from the webxr system. it looks for new and removed devices whose targetraymode is tracked-pointer. xrsession.oninputsourcescchange = event => { for (let input of event.added) { if (input.targetraymode == "tracked-pointer") { addedpointerdevice(input); } } for (let input of event.removed) { ...
XRInputSourcesChangeEvent - Web APIs
ices newly connected or enabled for use. session read only the xrsession to which this input source change event is being directed. methods while xrinputsourceschangeevent defines no methods of its own, it inherits methods from its parent interface, event. event types inputsourceschange delivered to the xrsession when the set of input devices available to it changes. examples the following example shows how to set up an event handler which uses inputsourceschange events to detect newly-available pointing devices and to load their models in preparation to display them in the next animation frame. xrsession.addeventlistener("inputsourceschange", oninputsourceschange); function oninputsourceschange(event) { for (let input of event.added) { if (input.targetraymode == "tracke...
XRPermissionDescriptor.mode - Web APIs
ut is presented inline within the context of an element in a standard html document, rather 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 examples the example below checks to ensure that permission has been granted to allow the user to use webxr for an immersive virtual reality experience. no specific features are specified during this query; see requiredfeatures and optionalfeatures for more information on specifying features during a webxr permission check. let xrpermissiondesc = { name: "xr", mode: "immersive-vr" }; if (navigator.permissions) { na...
XRPermissionStatus - Web APIs
the xrpermissionstatus interface defines the object returned by calling navigator.permissions.query() for the xr permission name; it indicates whether or not the app or site has permission to use webxr, an may be monitored over time for changes to that permissions tate. properties in addition to the properties listed below, xrpermissionstatus includes the properties defined by its parent interface, permissionstatus. granted an array of strings listing the names of the features for which permission has been granted as of the time at which navigator.permissions.query() was called. any feature which was specified in either the optionalfeatures or requiredfeatures when calling navigator.permissions.query() are listed in granted if and only if permission to use them is granted. methods...
XRReferenceSpaceEvent.transform - Web APIs
the read-only xrreferencespaceevent property transform indicates the position and orientation of the affected referencespace's native origin after the changes the event represents are applied. the transform is defined using the old coordinate system, which allows it to be used to convert coordinates from the pre-event coordinate system to the post-event coordiante system. syntax let refspace = xrreferencespaceevent.transform; value an xrrigidtransform object providing a transform that can be used to convert coordinates from the pre-event coordinate system to the post-event coordinate system. usage notes upon receiving a reset event, you can apply the transform to cached position or orientation information to shift them into the updated coordinate system. alternatively, you can just d...
XRReferenceSpaceEvent - Web APIs
space. currently, the only event that uses this type is the reset event. constructor xrreferencespaceevent() returns a new xrreferencespaceevent with the specified type and configured using the values in the given xrreferencespaceeventinit dictionary. properties in addition to inheriting the properties available on the parent interface, event, xrreferencespaceevent objects include the following properties: referencespace read only an xrreferencespace indicating the reference space that generated the event. transform read only an xrrigidtransform object indicating the position and orientation of the specified referencespace's native origin after the event, defined relative to the coordinate system before the event. methods while xrreferencespaceevent does not define any met...
XRReferenceSpaceEventInit.transform - Web APIs
the xrreferencespaceeventinit property transform indicates the position and orientation of the affected reference space's native origin after the changes the event represents are applied. the transform is defined using the old coordinate system, which allows it to be used to convert coordinates from the pre-event coordinate system to the post-event coordiante system. syntax let eventinitdict = { referencespace: xrreferencespace, transform: xrrigidtransform }); value an xrrigidtransform object providing a transform that can be used to convert coordinates from the pre-event coordinate system to the post-event coordinate system. examples this simple snippet calls the constructor to create a new reference space event of type reset. let refspaceevent = new xrreferencespaceevent("rese...
XRRenderState.baseLayer - Web APIs
he source of bitmap images and a description of how the image is to be rendered in the device. this property is read-only; however, you can indirectly change its value using xrsession.updaterenderstate. syntax var xrwebgllayer = xrrenderstate.baselayer; value a xrwebgllayer object which is used as the source of the world's contents when rendering each frame of the scene. see the examples below to see how to use updaterenderstate() to set the current xrwebgllayer used for rendering the scene. examples you can set the xrwebgllayer used for rendering by calling updaterenderstate(), like this: let canvas = document.queryselector("canvas"); gl = canvas.getcontext("webgl", { xrcompatible: true }); setnewwebgllayer(); function setnewwebgllayer(gl) { if (!gl) { /* webgl not available...
XRRenderState - Web APIs
eld of view (for inline presentations), and a reference to the xrwebgllayer being used as the target for rendering the scene prior to it being presented on the xr device's display or displays. when you apply changes using the xrsession method updaterenderstate(), the specified changes take effect after the current animation frame has completed, but before the next one begins. properties the followiing properties are available on xrrenderstate objects. baselayer read only the xrwebgllayer from which the browser's compositing system obtains the image for the xr session. depthfar read only the distance, in meters, of the far clip plane from the viewer. the far clip plane is the plane which is parallel to the display beyond which rendering of the scene no longer takes place. this, ...
XRRigidTransform.matrix - Web APIs
creating the matrix in this section, intended for more advanced readers, we cover how the api calculates the matrix for the specified transform. it begins by allocating a new matrix and writing a 4x4 identity matrix into it: [1000010000100001]\begin{bmatrix} 1 & 0 & 0 & 0\\ 0 & 1 & 0 & 0\\ 0 & 0 & 1 & 0\\ 0 & 0 & 0 & 1 \end{bmatrix} this is a tran...
XRSession.cancelAnimationFrame() - Web APIs
nimation frame which was previously requested by calling requestanimationframe. syntax xrsession.cancelanimationframe(handle); parameters handle the unique value returned by the call to requestanimationframe() that previously scheduled the animation callback. return value none. usage notes this function has no effect if the specified handle cannot be found. example in the example below we see code 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 cal...
XRSession: select event - Web APIs
ure 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 target ray for tracked-pointer inputs and sends the pose's transform to a function called myhandleselectwithray(). xrsession.addeventlistener("select", event => { if (event.inputsource.targetraymode == "tracked-pointer") { let targetraypose = event.frame.getpose(event.
XRSession: squeeze event - Web APIs
ng 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 pose representing the target ray for tracked-pointer inputs and sends the pose's transform to a function called myhandlesqueezewithray(). this code treats the squeeze as an instantaneous action that doesn't involve tracking an ongoing activity. if you need to track a squeeze action that isn't in...
XRSessionEvent() - Web APIs
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 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 ...
XRSessionEvent - Web APIs
e state of an xrsession. these events occur, for example, when the session ends or the visibility of its context changes. constructor xrsessionevent() creates and returns a new xrsessionevent object configured using the specified xrsessioneventinit object's values as available. properties in addition to properties inherited from its parent interface, event, xrsessionevent provides 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 appl...
XRSessionInit - Web APIs
if none are included, the device will use a default feature configuration for all options. optionalfeatures optional an array of values identifying features which the returned xrsession may optionally support. ...
XRSpace - Web APIs
Web › API › XRSpace
ime at which a given xrframe takes place. numeric values such as pose positions are thus coordinates in the corresponding xrspace, relative to that space's origin. note: the xrspace interface is never used directly; instead, all spaces are created using one of the interfaces based on xrspace. at this time, those are xrreferencespace and xrboundedreferencespace. interfaces based on xrspace below is a list of interfaces based on the xrspace interface. xrboundedreferencespace represents a reference space which may move within a region of space whose borders are defined by an array of points laid out in clockwise order along the floor to define the passable region of the space. the origin of an xrboundedreferencespace is always at floor level, with its x and z coordinates typically defa...
XRSystem: devicechange event - Web APIs
usage notes devicechange events are not delivered if the document which owns the xrsystem object has been granted permission to do so through the xr-spatial-tracking feature policy. you can use this event to, for example, monitor for the availability of a webxr-compatible device so that you can enable a ui element which the user can use to activate immersive mode. this is shown in the example below. example the example shown here handles the devicechange event by toggling the availability of the "enter xr" button based on whether or not any immersive devices are currently available. if (navigator.xr) { navigator.xr.addeventlistener("devicechange", event => { navigator.xr.issessionsupported("immersive-vr") .then(immersiveok) => { if (immersiveok) { enablexrbutton.d...
XRSystem: isSessionSupported() - Web APIs
e context of an html document) or immersive-vr for a fully-immersive virtual experience. return value a promise that resolves to true if the specified session mode is supported; otherwise the promise resolves to false. exceptions rather than throwing true exceptions, issessionsupported() rejects the returned promise, passing to the rejection handler a domexception whose name is one of the following strings. securityerror the document's origin does not have permission to use the xr-spatial-tracking feature policy. examples in this example, we see issessionsupported() used to detect whether or not the device supports vr mode by checking to see if an immersive-vr session is supported. if it is, we set up a button to read "enter xr", to call a method onbuttonclicked(), and enable the ...
XRTargetRayMode - Web APIs
controller. the target ray can be anything from a simple line (ideally fading over distance) to an animated effect, such as the science-fiction "phaser" style shown in the screenshot above. values gaze the user is using a gaze-tracking system (or gaze input) which detects the direction in which the user is looking. the target ray will be drawn originating at the viewer's eyes and will follow the direction in which they'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 direct...
XRView - Web APIs
Web › API › XRView
rovides information describing a single view into the xr scene for a specific frame, providing orientation and position information for the viewpoint. you can think of it as a description of a specific eye or camera and how it views the world. a 3d frame will involve two views, one for each eye, separated by an appropriate distance which approximates the distance between the viewer's eyes. this allows the two views, when projected in isolation into the appropriate eyes, to simulate a 3d world. properties eye read only which of the two eyes (left) or (right) for which this xrview represents the perspective. this value is used to ensure that any content which is pre-rendered for presenting to a specific eye is distributed or positioned correctly. the value can also be none if the xrview i...
XRViewerPose - Web APIs
he slight separation between the left and right eye. this view can represent anything from the point-of-view of a user's xr headset to the viewpoint represented by a player's movement of an avatar using mouse and keyboard, presented on the screen, to a virtual camera capturing the scene for a spectator. properties in addition to the properties inherited from xrpose, xrviewerpose includes the following: views read only an array of xrview objects, one for each viewpoint on the scene which is needed to represent the scene to the user. a typical headset provides a viewer pose with two views whose eye property is either left or right, indicating which eye that view represents. taken together, these views can reproduce the 3d effect when displayed on the xr device. usage notes the xrviewe...
XRWebGLLayer.framebuffer - Web APIs
the read-only xrwebgllayer property framebuffer is an opaque webglframebuffer which is used to buffer the rendered image if the xr compositor is being used. otherwise, this property's value is null. the opaque framebuffer is functionally nearly the same as a standard webgl framebuffer, except for the differences covered in the section how opaque framebuffers are special below. syntax let framebuffer = xrwebgllayer.framebuffer; value a webglframebuffer object representing the framebuffer into which the 3d scene is being rendered, or null if the xr compositor is disabled for the session. usage notes how opaque framebuffers are special the framebuffer represented by the framebuffer property is opaque. as such, its behavior is different in several ways from a standard webgl context. the...
XRWebGLLayer.ignoreDepthValues - Web APIs
ble to more accurately represent the scene in the 3d space. examples if the web application which is using wexr is rendering its content without using a depth buffer—or if the depth buffer's contents are invalid—you should disable the use of the depth buffer for webxr rendering by setting ignoredepthvalues to true when creating the xrwebgllayer. this is demonstrated in the snippet of code below: const gllayeroptions = { ignoredepthvalues: true }; let gllayer = new xrwebgllayer(xrsession, gl, gllayeroptions); specifications specification status comment webxr device apithe definition of 'xrwebgllayer.ignoredepthvalues' in that specification. working draft initial definition. ...
XRWebGLLayer - Web APIs
or simulated xr device, in the case of an inline session) and a webgl context used to render the scene for display on the device. in particular, it provides access to the webgl framebuffer and viewport to ease access to the context. although xrwebgllayer is currently the only type of framebuffer layer supported by webgl, it's entirely possible that future updates to the webxr specification may allow for other layer types and corresponding image sources. 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-alias...
XRWebGLLayerInit.ignoreDepthValues - Web APIs
er created by the xrwebgllayer() constructor. the default value, false, means the depth buffer will be used, if available. usage notes if ignoredepthvalues is true, the webxr compositor will ignore the contents of the depth buffer, if it exists, while compositing and rendering the scene. if false, the depth buffer's contents are used, if one is present. using a depth buffer while compositing allows the xr compositor to help ensure the compositing is done as accurately as possible. each entry in the depth buffer corresponds to the depth of the fragment whose color is at the same location in the color buffer, and must have a value between 0.0 and 1.0, where 0.0 corresponds to the distance specified in the xrsession object's renderstate record's depthnear and 1.0 represents the distance given...
Generating HTML - Web APIs
> <xsl:value-of select="@company" /> </b> </xsl:if> <br /> </xsl:template> <xsl:template match="myns:body"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> ... ...
XSL Transformations in Mozilla FAQ - Web APIs
escaping requires us to add a parsing step to our output generation, which we don't. in most cases, there are pretty easy workarounds. the only use cases we have seen are bad xml or bad xslt. and rss feeds. the latter is pretty much the only issue to us, and we're sorry that we can't support it. but mixing parsing with xslt is brittle and we rather not support d-o-e than either crash or be even slower. what about document.write? just like for xhtml, document.write is not supported during xslt transformations. sadly, current builds don't error, but just give unexpected results, like crashes (bug 202765). in most cases, there is no need to actually use it, though. if you need platform dependent code or stylesheets, just do <xsl:if test="system-property('xsl:vendor')='transformiix'"> ...
XSLTProcessor - Web APIs
in the stylesheet. a null value for namespaceuri is treated the same as an empty string. void xsltprocessor.clearparameters() removes all set parameters from the xsltprocessor. the xsltprocessor will then use the defaults specified in the xslt stylesheet. void xsltprocessor.reset() removes all parameters and stylesheets from the xsltprocessor. properties non-web-exposed properties the following properties are [chromeonly] and not exposed to web content: [chromeonly] attribute unsigned long xsltprocessor.flags flags that tweak the behavior of the processor. not reset by calling xsltprocessor.reset(). default value: 0 possible values are: name value effect (none) 0 none disable_all_loads 1 disable loading exter...
msGetRegionContent - 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. the msgetregioncontent returns an array of range instances corresponding to the content from the region flow that is positioned in the region. this proprietary method is specific to internet explorer browser. syntax var retval = element.msgetregioncontent(); parameters retval [out, reval] type: msrangecollection the name of the property to enable. return value type: boolean returned ranges are sorted by document position and do not overlap. if an element is not a region, this method throws ...
Web APIs
Web › API
web apis are typically used with javascript, although this doesn't always have to be the case. specifications this is a list of all the apis that are available. ...
ARIA guides - Accessibility
error handling in forms labeling widgets labeling composite widgets and regions managing focus in composite widgets (aria-activedescendant vs roving tabindex) using landmark roles handling dynamic updates & live regions virtual vs. ...
Using the aria-activedescendant attribute - Accessibility
content, uses the aria-activedescendant property to inform the assistive technology about the active child which has focus. this active child using the aria-activedescendant property must always be visible on screen and must be a descendant of the container in the document object model. note: opinions may differ on how assistive technology should handle this technique. the information provided below is one of those opinions and therefore not normative. examples example 1: code working examples: notes aria attributes used related aria techniques compatibility tbd: add support information for common ua and at product combinations additional resources ...
Using the aria-hidden attribute - Accessibility
" 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</span>! </p> accessibility concerns best practices aria-hidden="true" should not be added when: ...
Using the aria-label attribute - Accessibility
used with any typical html element; it is not limited to elements that have an aria role assigned. value string possible effects on user agents and 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: multiple labels in the example below, a button is styled to look like a typical "close" button, with an x in the middle. since there is nothing indicating that the purpose of the button is to close the dialog, the aria-label attribute is used to provide the label to any assistive technologies. <button aria-label="close" onclick="mydialog.close()">x</button> notes the most common accessibility api mapping for a label is the a...
Using the aria-orientation attribute - Accessibility
vertical the element is oriented vertically. horizontal (default) the element is oriented horizontally. possible effects on user agents and 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. <a href="#" id="handle_zoomslider" role="slider" aria-orientation="vertical" aria-valuemin="0" aria-valuemax="17" aria-valuenow="14" > <span>11</span> </a> working examples: slider example notes used with aria roles scrollbar listbox combobox menu tree separator slider tablist toolb...
Using the aria-relevant attribute - Accessibility
used to describe what types of changes have occurred to an aria-live region, and which are relevant and should be announced. any change that is not relevant acts in the same manner it would if the aria-live attribute were set to off. aria-relevant is commonly used when a web page contains content that may be updated while viewing the page. values a space-delimited list of one or more of the following values: additions element nodes added to the accessibility tree within the live region; should be considered relevant. removals are deletion of nodes in the accessiblity tree; should be considered relevant. text are changes to the textual content of existing nodes; should be considered relevant. all is equivalent to additions removals text. aria-relevant="additions text" is the default...
Using the aria-valuenow attribute - Accessibility
luemax 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 snippet below shows a simple slider with a current value of 4. <div role="slider" aria-valuenow="4" aria-valuemin="1" aria-valuemax="10"> working examples: progressbar example slider example spinbutton example notes used with aria roles progressbar scrollbar slider spinbutton related aria techniques aria-valuemax aria-valuemin aria-valuetext compatibility tbd: add support informati...
Using the aria-valuetext attribute - Accessibility
s will rely solely on the aria-valuenow attribute for the current value. if aria-valuetext is specified, assistive technologies should render that value instead of the value of aria-valuenow. 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 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. <div role="slider" aria-valuenow="1" aria-valuemin="1" aria-valuemax="7" aria-valuetext="sunday"> working examples: notes used with aria r...
Using the article role - Accessibility
assistive technologies support html5 yet. possible effects on user agents and assistive technology when the user navigates an element assigned the role of article, assistive technologies that typically intercept standard keyboard events should switch to document browsing mode, as opposed to passing keyboard events through to the web application. assistive technologies may provide a feature allowing the user to navigate the hierarchy of any nested article elements. 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 <article role="article"> <header> <h2>blog post</h2> </header> <section class="content"> <p>a very interesting post</p> </section> ...
ARIA: tabpanel role - Accessibility
required javascript features include note about semantic alternatives to using this role or attribute. the first rule of aria use is you can use a native feature with the semantics and behavior you require already built in, instead of re-purposing an element and adding an aria role, state or property to make it accessible, then do so. then post full details in best practices section below. examples fill in a simple example that nicely shows a typical usage of the property, then perhaps some more complex examples. <div role="tablist"> <div role="tab" aria-selected="true" aria-controls="tabpanel-id" id="tab-id" tabindex="0">tab label</div> accessibility concerns optionally, warn of any potential accessibility concerns that exist with using this property, and how to work aroun...
ARIA: article role - Accessibility
nition of 'article' in that specification. recommendation wai-aria authoring practicesthe definition of 'feed' in that specification. working draft precedence order this role corresponds to the <article> element in html, and that element should be used instead, if possible. this role does not require any specific roles to be present among its children. it is the only role allowed as a direct child of an element with the feed role. see also feed role section role <article> element rss article ...
ARIA: grid role - Accessibility
first row of the grid, focus does not move. home moves focus to the first cell in the row that contains focus. end moves focus to the last cell in the row that contains focus. ctrl + home moves focus to the first cell in the first row. ctrl + end moves focus to the last cell in the last row. if cells, rows, or columns can be selected, the following key combination are commonly used: key combination action ctrl + space select the column that contains the focus. shift + space selects the row that contains the focus. if the grid includes a column with checkboxes to select rows, this key combination can be used to check that box even if the focus is not on the checkbox. ctrl + a selects al...
ARIA: List role - Accessibility
trol over your html but are able to improve accessibility dynamically after the fact with javascript. unlike the html <ol> and <ul>, the aria list roles doesn't distinguish between ordered and unordered lists. if at all possible, you should use the appropriate semantic html elements to mark up a list (<ol> and <ul>) and list items (<li>). for example, our above example should be rewritten as follows: <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> </ul> or use an ordered list if the order of the list items matters: <ol> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> </ol> note: the aria list/listitem roles don't distinguish between ordered and unordered lists. as an aside, note that if you are using the semantic html elements of ol or u...
ARIA: Listitem role - Accessibility
best practices only use role="list" and role="listitem" if you have to — for example if you don't have control over your html but are able to improve accessibility dynamically after the fact with javascript. if at all possible, you should use the appropriate semantic html elements to mark up a list and listitems — <ol>/<ul> and <li>. for example, our above example should be rewritten as follows: <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> </ul> or use an ordered list if the order of the list items matters: <ol> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> </ol> note: the aria list/listitem roles don't distinguish between ordered and unordered lists. note: if you are marking up a list of items that will function as a tabbed i...
ARIA: img role - Accessibility
es of content it is not so obvious, and role="img" can come into play. for example, if you use emojis in your text, the meaning might be obvious to a sighted user, but someone using a screenreader might get confused because the emojis might have either no text representation at all, or the alternative text might be confusing and not match the context it is being used in. for example, take the following code: <div role="img" aria-label="that cat is so funny"> <p> &#x1f408; &#x1f602; </p> </div> &#x1f408; &#x1f602; are entity references for emojis read out as "cat" and "face with tears of joy", but this doesn't necessarily make sense — the implied meaning is possibly more like "that cat is so funny", so we include that in an aria-label along with role="img". this seems to work ok ...
ARIA: row role - Accessibility
attribute to indicate the present status. this is not the case for an ordinary table or grid, in which the aria-expanded attribute is not present. to create an interactive widget that has a tabular structure, use the grid pattern instead. if the interaction provides for the selection state of individual cells, if left to right and top to botton navigation is provided, or if the user interface allows the rearranging of cell order or otherwise changing individual cell order such as through drag and drop, use grid or treegrid instead. note: using the native html table element (<table>) along with the table row element (<tr>) whenever possible is strongly encouraged. associated wai-aria roles, states, and properties context roles role="rowgroup" an optional contextual row parent, it es...
ARIA: tab role - Accessibility
order, ideally the active tab's associated tabpanel. → focuses and optionally activates the next tab in the tab list. if the current tab is the last tab in the tab list it activates the first tab. ← focuses and optionally activates the previous tab in the tab list. if the current tab is the first tab in the tab list it activates the last tab. delete when allowed removes the currently selected tab from the tab list. required javascript features while there are ways to build tab-like functionality without javascript, there are no substitute combination of html and css only that will provide the same set of functionality that's required above for accessible tabs with content. example this example combines the role tab with tablist and element...
ARIA: heading role - Accessibility
mically inserting content. in that case, the newly-added headings need aria-level attributes whose values are consistent with the rest of the document structure. instead of using a <div> or <span> with a heading role and aria-level, consider using a native <h1> through <h6> element instead to indicate that this text is a heading, and what part of the structure it represents. examples the following shows a typical page structure. <div id="container"> <div role="heading" aria-level="1">the main page heading</div> <p>this article is about showing a page structure.</p> <div role="heading" aria-level="2">introduction</div> <p>an introductory text.</p> <div role="heading" aria-level="2">chapter 1</div> <p>text</p> <div role="heading" aria-level="3">chapter 1.1</div> <p>more text in a sub sec...
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...
Forms - Accessibility
the following pages provide various techniques for improving the accessibility of web forms: basic form hints: adding hints and descriptions for invalid or required fields alerts: using alerts to provide client-side validation error messages multi-part labels: enabling complex form labels with a control inside each label see also the yahoo! article on form validation and aria (retrieved on archive.org), covering much of the same content. ...
ARIA - Accessibility
upported by nvda with firefox, and voiceover with safari. references aria roles reference pages covering all the wai-aria roles discussed on mdn. standardization efforts wai-aria specification the w3c specification itself. wai-aria authoring practices the official best practices documents how best to aria-ify common widgets and interactions. an excellent resource. videos following talks are a great way to understand aria: aria, accessibility apis and coding like you give a damn! – léonie watson filing bugs file aria bugs on browsers, screen readers, and javascript libraries. related topics accessibility, ajax, javascript ...
Accessibility FAQ - Accessibility
i'm interested in helping promote the fine accessibility features that firefox provides, what can i do? join the firefox accessibility advocates ...
HTML To MSAA - Accessibility
this table reflects mapping rules for specific elements only, it doesn't reflect any general rules applicable to all elements. for example, if name column has n/a value then it means specific elements doesn't provide own rules to calculate name but name can be computed from aria markup or @title attribute. ...
Robust - Accessibility
s article provides practical advice on how to write your web content so that it conforms to the success criteria outlined in the robust principle of the web content accessibility guidelines (wcag) 2.0 and 2.1. robust states that content must be robust enough that it can be interpreted reliably by a wide variety of user agents, including assistive technologies. this can generally be achieved by following web standards and testing rigorously. note: to read the w3c definitions for robust and its guidelines and success criteria, see principle 4: robust — content must be robust enough that it can be interpreted reliably by a wide variety of user agents, including assistive technologies. guideline 4.1 — compatible: maximize compatibility with current and future user agents, including assist...
-moz-image-region - CSS: Cascading Style Sheets
/* keyword value */ -moz-image-region: auto; /* <shape> value */ -moz-image-region: rect(0, 8px, 4px, 4px); /* global values */ -moz-image-region: inherit; -moz-image-region: initial; -moz-image-region: unset; the syntax is similar to the clip property. ...
-moz-outline-radius-topleft - CSS: Cascading Style Sheets
f the element, specified as the percentages of the top and left sides of the border box. formal definition initial value0applies toall elementsinheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valueas specifiedanimation typea length, percentage or calc(); formal syntax <outline-radius>where <outline-radius> = <length> | <percentage> examples the example below will not display the desired effect if you are viewing this in a browser other than firefox. html <p>look at this paragraph's top-left corner.</p> css p { margin: 5px; border: solid cyan; outline: dotted red; -moz-outline-radius-topleft: 2em; } result specifications not part of any standard. ...
-moz-outline-radius - CSS: Cascading Style Sheets
e rounded corners. /* one value */ -moz-outline-radius: 25px; /* two values */ -moz-outline-radius: 25px 1em; /* three values */ -moz-outline-radius: 25px 1em 12%; /* four values */ -moz-outline-radius: 25px 1em 12% 4mm; /* global values */ -moz-outline-radius: inherit; -moz-outline-radius: initial; -moz-outline-radius: unset; constituent properties this property is a shorthand for the following css properties: -moz-outline-radius-bottomleft -moz-outline-radius-bottomright -moz-outline-radius-topleft -moz-outline-radius-topright syntax values elliptical outlines and <percentage> values follow the syntax described in border-radius. one, two, three or four <outline-radius> values, represents one of: <length> see <length> for possible values. <percentage> a <percentage>;...
-webkit-mask-repeat-x - CSS: Cascading Style Sheets
the image is repeated as much as possible without clipping. the first and last images are pinned to either side of the element, and whitespace is distributed evenly between the images. the mask-position property is ignored unless only one image can be displayed without clipping. the only case where clipping happens using space is when there isn't enough room to display one image. round as the allowed space increases in size, the repeated images will stretch (leaving no gaps) until there is room for another one to be added. when the next image is added, all of the current ones compress to allow room. example: an image with an original width of 260px, repeated three times, might stretch until each repetition is 300px wide, and then another image will be added. they will then compress to 225px...
-webkit-mask-repeat-y - CSS: Cascading Style Sheets
repeated as much as possible without clipping. the first and last images are pinned to the top and bottom edge of the element, and whitespace is distributed evenly between the images. the mask-position property is ignored unless only one image can be displayed without clipping. the only case where clipping happens using space is when there isn't enough room to display one image. round as the allowed vertical space increases in size, the repeated images will stretch (leaving no gaps) until there is room for another one to be added. when the next image is added, all of the current ones compress to allow room. example: an image with an original height of 260px, repeated three times, might stretch until each repetition is 300px high, and then another image will be added. they will then compres...
-webkit-print-color-adjust - CSS: Cascading Style Sheets
ng of background colors and images in browsers based on the webkit engine. /* keyword values */ -webkit-print-color-adjust: economy; -webkit-print-color-adjust: exact; /* global values */ -webkit-print-color-adjust: inherit; -webkit-print-color-adjust: initial; -webkit-print-color-adjust: unset; syntax the -webkit-print-color-adjust property is specified as one of the keyword values listed below. values economy normal behavior. background colors and images are only printed if the user explicitly allows it in their browser's print settings dialog. exact background colors and images of the element to which this rule is applied are always printed, user's print settings are overridden. formal definition value not found in db! formal syntax syntax not found in db! examples forc...
-webkit-text-security - CSS: Cascading Style Sheets
> field (such as <input> or <textarea>) by replacing them with a shape. it only affects fields that are not of type=password. syntax -webkit-text-security: circle; -webkit-text-security: disc; -webkit-text-security: square; -webkit-text-security: none; formal definition value not found in db! formal syntax syntax not found in db! examples obscuring a text input try typing in the field below. if your browser supports this property, the characters should be visually replaced with squares. html <label for="name">name:</label> <input type="text" name="name" id="name" /> css input { -webkit-text-security: square; } result specifications not part of any standard. ...
-webkit-text-stroke - CSS: Cascading Style Sheets
longhand properties -webkit-text-stroke-width and -webkit-text-stroke-color. /* width and color values */ -webkit-text-stroke: 4px navy; text-stroke: 4px navy; /* global values */ -webkit-text-stroke: inherit; -webkit-text-stroke: initial; -webkit-text-stroke: unset; text-stroke: inherit; text-stroke: initial; text-stroke: unset; constituent properties this property is a shorthand for the following css properties: -webkit-stroke-color -webkit-stroke-width syntax values <length> the width of the stroke. <color> the color of the stroke. formal definition initial valueas each of the properties of the shorthand:-webkit-text-stroke-width: 0-webkit-text-stroke-color: currentcolorapplies toall elementsinheritedyescomputed valueas each of the properties of the shorthand:-webkit-t...
-webkit-touch-callout - CSS: Cascading Style Sheets
/* keyword values */ -webkit-touch-callout: default; -webkit-touch-callout: none; /* global values */ -webkit-touch-callout: initial; -webkit-touch-callout: inherit; -webkit-touch-callout: unset; syntax values default the default callout is displayed. ...
:-moz-last-node - CSS: Cascading Style Sheets
e 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
xtension that matches an element if the user interface is being displayed left-to-right. this is determined by the preference intl.uidirection.locale (where locale is the current locale) being set to "ltr". note: this selector is mainly used by extensions and themes to adapt the user interface based on the user's locale. (this can vary from window to window, and even from tab to tab.) it also allows extensions to work even when they don't support the user's default locale, since they can support both left-to-right and right-to-left layouts regardless of locale specifics. this selector does not work properly from html; it always matches, regardless of whether the ui locale is left-to-right or right-to-left. syntax :-moz-locale-dir(ltr) examples this example doesn't work if you're not...
:-moz-locale-dir(rtl) - CSS: Cascading Style Sheets
xtension that matches an element if the user interface is being displayed right-to-left. this is determined by the preference intl.uidirection.locale (where locale is the current locale) being set to "rtl". note: this selector is mainly used by extensions and themes to adapt the user interface based on the user's locale. (this can vary from window to window, and even from tab to tab.) it also allows extensions to work even when they don't support the user's default locale, since they can support both left-to-right and right-to-left layouts regardless of locale specifics. this selector does not work properly from html; it never matches, no matter whether the ui locale is left-to-right or right-to-left. syntax :-moz-locale-dir(rtl) examples this example will not work if you're not usi...
:-moz-only-whitespace - CSS: Cascading Style Sheets
the :empty selector was changed to act like :-moz-only-whitespace, but no browser currently supports this yet. the :-moz-only-whitespace css pseudo-class matches elements that only contains text nodes that only contain whitespace. ...
:-moz-suppressed - CSS: Cascading Style Sheets
...
:-moz-ui-valid - CSS: Cascading Style Sheets
if the control has focus, and the value was valid (including empty) when it gained focus, apply this pseudo-class. if the control has focus, and the value was invalid when it gained focus, re-validate on every keystroke. ...
:-moz-window-inactive - CSS: Cascading Style Sheets
round windows was achieved by setting an attribute (active="true") on the top-level xul chrome window. this attribute is no longer used. syntax :-moz-window-inactive examples this example alters the appearance of a box's background depending on whether its window is active or not. html <div id="mybox"> <p>this is a box!</p> </div> css #mybox { background: linear-gradient(to bottom, yellow, cyan); width: 200px; height: 200px; } #mybox:-moz-window-inactive { background: cyan; } result the result of this code is shown below. you can view this as a separate page as well. specifications not part of any standard. ...
::-webkit-file-upload-button - CSS: Cascading Style Sheets
link compatible browsers like chrome, opera and safari (indicated by the -webkit prefix). syntax selector::-webkit-file-upload-button examples html <form> <label for="fileupload">upload file</label><br> <input type="file" id="fileupload"> </form> css input, label { display: block; } input[type=file]::-webkit-file-upload-button { border: 1px solid grey; background: #fffaaa; } below is the example for you to try. the screenshot to the left shows what the button will look like if you are without access to chrome, opera or safari. screenshotlive sample specifications not part of any standard. ...
::-webkit-meter-optimum-value - CSS: Cascading Style Sheets
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-progress-bar - CSS: Cascading Style Sheets
it is a child of the ::-webkit-progress-inner-element pseudo-element and the parent of the ::-webkit-progress-value pseudo-element. note: for ::-webkit-progress-value to take effect, appearance needs to be set to none on the <progress> element. ...
::-webkit-search-results-button - CSS: Cascading Style Sheets
the ::-webkit-search-results-button css pseudo-element represents a button (the "search results button") at the left edge of an <input> of type="search" which when clicked displays a menu which allows the user to choose from previous recent search queries. this button and pseudo-element are non-standard, supported only in webkit and blink, hence the vendor prefix. the search results button is only shown on search <input> elements that have a results attribute. syntax selector::-webkit-search-results-button specifications not part of any standard. ...
::after (:after) - CSS: Cascading Style Sheets
Web › CSS › ::after
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. css animationsthe definition of 'animations on pseudo-element properties' in that specification. working draft allows animations on properties defined on pseudo-elements. selectors level 3the definition of '::after' in that specification. recommendation introduces the two-colon syntax. css level 2 (revision 1)the definition of '::after' in that specification. recommendation initial definition, using the one-colon syntax. ...
::grammar-error - CSS: Cascading Style Sheets
the ::grammar-error css pseudo-element represents a text segment which the user agent has flagged as grammatically incorrect. allowable properties only a small subset of css properties can be used in a rule with ::grammar-error in its selector: color background-color cursor caret-color outline and its longhands text-decoration and its associated properties text-emphasis-color text-shadow syntax ::grammar-error examples simple document grammar check in this example, eventual supporting browsers should highlight any flagged grammatical errors with the styles shown. html <p>my friends is coming to the party tonight.</p> css ::grammar-error { text-decoration: underline red; color: red; } result specifications specification status comment ...
::marker - CSS: Cascading Style Sheets
Web › CSS › ::marker
the ::marker css pseudo-element selects the marker box of a list item, which typically contains a bullet or number. it works on any element or pseudo-element set to display: list-item, such as the <li> and <summary> elements. ::marker { color: blue; font-size: 1.2em; } allowable properties only certain css properties can be used in a rule with ::marker as a selector: all font properties the white-space property color text-combine-upright, unicode-bidi and direction properties the content property all animation and transition properties the specification states that additional css properties may be supported in future. syntax ::marker examples html <ul> <li>peaches</li> <li>apples</li> <li>plums</li> </ul> css ul li::marker { color: red; font-size: 1.5em; }...
::placeholder - CSS: Cascading Style Sheets
ceholder accessibility concerns color contrast contrast ratio placeholder text typically has a lighter color treatment to indicate that it is a suggestion for what kind of input will be valid, and is not actual input of any kind. it is 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 (wc...
::spelling-error - CSS: Cascading Style Sheets
the ::spelling-error css pseudo-element represents a text segment which the user agent has flagged as incorrectly spelled. allowable properties only a small subset of css properties can be used in a rule with ::spelling-error in its selector: color background-color cursor caret-color outline and its longhands text-decoration and its associated properties text-emphasis-color text-shadow syntax ::spelling-error examples simple document spell check in this example, eventual supporting browsers should highlight any flagged spelling errors with the styles shown. html <p contenteditable spellcheck="true">my friends are coegdfgfddffbgning to the party tonight.</p> css ::spelling-error { text-decoration: wavy red; } result specifications specification...
:active - CSS: Cascading Style Sheets
Web › CSS › :active
ypically the leftmost button. syntax :active examples active links html <p>this paragraph contains a link: <a href="#">this link will turn red while you click on it.</a> the paragraph will get a gray background while you click on it or the link. ...
:dir() - CSS: Cascading Style Sheets
Web › CSS › :dir
ir() 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 dir="auto">עִבְרִית</div> </div> </div> css :dir(ltr) { background-color: yellow; } :dir(rtl) { background-color: powderblue; } result specifications specification status comment html living standardthe definition of ':dir(ltr)' in that specification. living standard no changes. selectors level 4the definition of ':dir()' in that specification. working draft initial definition. ...
:enabled - CSS: Cascading Style Sheets
Web › CSS › :enabled
the :enabled css pseudo-class represents any enabled element. an element is enabled if it can be activated (selected, clicked on, typed into, etc.) or accept focus. the element also has a disabled state, in which it can't be activated or accept focus. /* selects any enabled <input> */ input:enabled { color: blue; } syntax :enabled examples the following example makes the color of text and button <input>s green when enabled, and gray when disabled. this helps the user understand which elements can be interacted with. html <form action="url_of_form"> <label for="firstfield">first field (enabled):</label> <input type="text" id="firstfield" value="lorem"><br> <label for="secondfield">second field (disabled):</label> <input type="text" id="secondfield" value="ipsum" disabled="di...
:focus-visible - CSS: Cascading Style Sheets
on mouse-focus for browsers that do support :focus-visible */ background: transparent; } custom-button:focus-visible { /* draw a very noticeable focus style for keyboard-focus on browsers that do support :focus-visible */ outline: 4px dashed darkorange; background: transparent; } polyfill you can polyfill :focus-visible using focus-visible.js. accessibility concerns low vision make sure the visual focus indicator can be seen by people with low vision. this will also benefit anyone use a screen in a brightly lit space (like outside in the sun). wcag 2.1 sc 1.4.11 non-text contrast requires that the visual focus indicator be at least 3 to 1. accessible visual focus indicators: give your site some focus! tips for designing useful and usable focus indicators c...
:focus - CSS: Cascading Style Sheets
Web › CSS › :focus
en focused */ input:focus { color: red; } note: this pseudo-class applies only to the focused element itself. use :focus-within if you want to select an element that contains a focused element. syntax :focus examples html <input class="red-input" value="i'll be red when focused."><br> <input class="blue-input" value="i'll be blue when focused."> css .red-input:focus { background: yellow; color: red; } .blue-input:focus { background: yellow; color: blue; } result accessibility concerns make sure the visual focus indicator can be seen by people with low vision. this will also benefit anyone use a screen in a brightly lit space (like outside in the sun). wcag 2.1 sc 1.4.11 non-text contrast requires that the visual focus indicator be at least 3 to 1. accessible visu...
:fullscreen - CSS: Cascading Style Sheets
ss. there are two rules here. the first establishes the background color of the "toggle full-screen mode" button when the element is not in a full-screen state. the key is the use of the :not(:fullscreen), which looks for the element to not have the :fullscreen pseudo-class applied to it. #fs-toggle:not(:fullscreen) { background-color: #afa; } when the document is in full-screen mode, the following css applies instead, setting the background color to a pale shade of red. #fs-toggle:fullscreen { background-color: #faa; } specifications specification status comment fullscreen apithe definition of ':fullscreen' in that specification. living standard initial definition. ...
:has() - CSS: Cascading Style Sheets
Web › CSS › :has
limitation that it couldn't be used within stylesheets. instead, it could only be used with functions like document.queryselector(); this was due to performance concerns. this limitation has been removed because no browser implemented it that way. instead, browsers currently only support the use of :has() within stylesheets. examples matching <a> elements that directly contain an <img> the following selector matches only <a> elements that directly contain an <img> child: a:has(> img) matching <h1> elements that are followed by a <p> the following selector matches <h1> elements only if they have a <p> element directly following them: h1:has(+ p) specifications specification status comment selectors level 4the definition of ':has()' in that specification. ...
:host() - CSS: Cascading Style Sheets
Web › CSS › :host()
in this example we have a simple custom element — <context-span> — that you can wrap around text: <h1>host selectors <a href="#"><context-span>example</context-span></a></h1> inside the element's constructor, we create style and span elements, fill the span with the content of the custom element, and fill the style e...
:host - CSS: Cascading Style Sheets
Web › CSS › :host
the :host css pseudo-class selects the shadow host of the shadow dom containing the css it is used inside — in other words, this allows you to select a custom element from inside its shadow dom. note: this has no effect when used outside a shadow dom. /* selects a shadow root host */ :host { font-weight: bold; } syntax :host examples styling the shadow host the following snippets are taken from our host-selectors example (see it live also). in this example we have a simple custom element — <context-span> — that you can wrap around text: <h1>host selectors <a href="#"><context-span>example</context-span></a></h1> inside the element's constructor, we create style and span elements, fill the span with the content of the custom element, and fill the style element with some ...
:hover - CSS: Cascading Style Sheets
Web › CSS › :hover
ogous effect, but based on the :checked pseudo-class (applied to hidden radioboxes), see this demo, taken from the :checked reference page. specifications specification comment feedback html living standardthe definition of ':hover' in that specification. whatwg html github issues selectors level 4the definition of ':hover' in that specification. allows :hover to be applied to any pseudo-element. css working group drafts github issues selectors level 3the definition of ':hover' in that specification. css level 2 (revision 1)the definition of ':hover' in that specification. initial definition. ...
:invalid - CSS: Cascading Style Sheets
Web › CSS › :invalid
erstanding wcag 2.0 notes radio buttons if any one of the radio buttons in a group is required, the :invalid pseudo-class is applied to all of them if none of the buttons in the group is selected. (grouped radio buttons share the same value for their name attribute.) gecko defaults by default, gecko does not apply a style to the :invalid pseudo-class. however, it does apply a style (a red "glow" using the box-shadow property) to the :-moz-ui-invalid pseudo-class, which applies in a subset of cases for :invalid. specifications specification status comment html living standardthe definition of ':invalid' in that specification. living standard no change. html5the definition of ':invalid' in that specification. recommendation defines the se...
:not() - CSS: Cascading Style Sheets
Web › CSS › :not
(div):not(span) { font-weight: bold; } /* elements that are not `.crazy` or `.fancy` */ /* note that this syntax is not well supported yet. */ body :not(.crazy, .fancy) { font-family: sans-serif; } result specifications specification status comment selectors level 4the definition of ':not()' in that specification. working draft extends its argument to allow some non-simple selectors. selectors level 3the definition of ':not()' in that specification. recommendation initial definition. ...
:nth-child() - CSS: Cascading Style Sheets
-child(5n) represents elements 5 [=5×1], 10 [=5×2], 15 [=5×3], etc. the first one to be returned as a result of the formula is 0 [=5x0], resulting in a no-match, since the elements are indexed from 1, whereas n starts from 0. this may seem weird at first, but it makes more sense when the b part of the formula is >0, like in the next example. :nth-child(n+7) represents the seventh and all following elements: 7 [=0+7], 8 [=1+7], 9 [=2+7], etc. :nth-child(3n+4) represents elements 4 [=(3×0)+4], 7 [=(3×1)+4], 10 [=(3×2)+4], 13 [=(3×3)+4], etc. :nth-child(-n+3) represents the first three elements. [=-0+3, -1+3, -2+3] p:nth-child(n) represents every <p> element in a group of siblings. this selects the same elements as a simple p selector (although with a higher specificity). p:nth-...
:only-child - CSS: Cascading Style Sheets
/* selects each <p>, but only if it is the */ /* only child of its parent */ p:only-child { background-color: lime; } note: as originally defined, the selected element had to have a parent. beginning with selectors level 4, this is no longer required. ...
: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...
:root - CSS: Cascading Style Sheets
Web › CSS › :root
the :root css pseudo-class matches the root element of a tree representing the document. in html, :root represents the <html> element and is identical to the selector html, except that its specificity is higher. /* selects the root element of the document: <html> in the case of html */ :root { background: yellow; } syntax :root examples declaring global css variables :root can be useful for declaring global css variables: :root { --main-color: hotpink; --pane-padding: 5px 42px; } specifications specification status comment selectors level 4the definition of ':root' in that specification. working draft no change. selectors level 3the definition of ':root' in that specification. recommendation initial definition. ...
:target - CSS: Cascading Style Sheets
Web › CSS › :target
the :target css pseudo-class represents a unique element (the target element) with an id matching the url's fragment. /* selects an element with an id matching the current url's fragment */ :target { border: 2px solid black; } for example, the following url has a fragment (denoted by the # sign) that points to an element called section2: http://www.example.com/index.html#section2 the following element would be selected by a :target selector when the current url is equal to the above: <section id="section2">example</section> syntax :target examples a table of contents the :target pseudo-class can be used to highlight the portion of a page that has been linked to from a table of contents. html <h3>table of contents</h3> <ol> <li><a href="#p1">jump to the first paragraph!</a></li...
fallback - CSS: Cascading Style Sheets
if a valid fallback style is not specified, it defaults to decimal. ...
suffix - CSS: Cascading Style Sheets
of the@counter-style rule specifies content that will be appended to the marker representation. syntax /* <symbol> values */ suffix: ""; suffix: ") "; suffix: url(bullet.png); values <symbol> specifies a <symbol> that is appended to the marker representation. it may be a <string>, <image>, or <custom-ident>. formal definition related at-rule@counter-styleinitial value". ...
symbols - CSS: Cascading Style Sheets
the symbols css descriptor is used to specify the symbols that the specified counter system will use to construct counter representations. syntax the symbols descriptor is specified as one or more <symbol>s. values <symbol> represents a symbol used within the counter system. this must be one of the following data types: <string> <image> (note: this value is "at risk" and may be removed from the specification. it is not yet implemented.) <custom-ident> description a symbol can be a string, image, or identifier. it is used within the @counter-style at-rule. symbols: a b c d e; symbols: "\24b6" "\24b7" "\24b8" d e; symbols: "0" "1" "2" "4" "5" "6" "7" "8" "9"; symbols: url('first.svg') url('second.svg') url('third.svg'); symbols: indic-numbers; the symbols descriptor mu...
@document - CSS: Cascading Style Sheets
Web › CSS › @document
...
font-display - CSS: Cascading Style Sheets
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. description the font display timeline the font display timeline is based on a timer that begins the moment the user agent attempts to use a given downloaded font face. the timeline is divided into the three periods below which dictate the rendering behavior of any elements using the font face. font block period if the font face is not loaded, any element attempting to use it must render an invisible fallback font face. if the font face successfully loads during this period, it is used normally. font swap period if the font face is not loaded, any element attempting to use it must render a fallback font face...
font-family - CSS: Cascading Style Sheets
syntax /* <string> values */ font-family: "font family"; font-family: 'another font family'; /* <custom-ident> value */ font-family: examplefont; values <family-name> specifies the name of the font family. ...
src - CSS: Cascading Style Sheets
Web › CSS › @font-face › src
the format hint contains a comma-separated list of format strings that denote well-known font formats. if a user agent doesn't support the specified formats, it skips downloading the font resource. if no format hints are supplied, the font resource is always downloaded. <font-fac...
unicode-range - CSS: Cascading Style Sheets
r example u+26. codepoint range a range of unicode code points. so for example, u+0025-00ff means include all characters in the range u+0025 to u+00ff. wildcard range a range of unicode code points containing wildcard characters, that is using the '?' character, so for example u+4?? means include all characters in the range u+400 to u+4ff. description the purpose of this descriptor is to allow the font resources to be segmented so that a browser only needs to download the font resource needed for the text content of a particular page. for example, a site with many localizations could provide separate font resources for english, greek and japanese. for users viewing the english version of a page, the font resources for greek and japanese fonts wouldn't need to be downloaded, saving band...
any-hover - CSS: Cascading Style Sheets
Web › CSS › @media › any-hover
the any-hover css media feature can be used to test whether any available input mechanism can hover over elements. syntax the any-hover feature is specified as a keyword value chosen from the list below. none none of the available input mechanism(s) can hover conveniently, or there is no pointing input mechanism. hover one or more available input mechanisms can conveniently hover over elements. examples testing whether input methods can hover html <a href="#">try hovering over me!</a> css @media (any-hover: hover) { a:hover { background: yellow; } } result specifications specification status comment media queries level 4the definition of 'any-hover' in that specification. candidate recommendation initial definition. ...
any-pointer - CSS: Cascading Style Sheets
none no pointing device is available. coarse at least one input mechanism includes a pointing device of limited accuracy. ...
aspect-ratio - CSS: Cascading Style Sheets
e 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. html <div id='inner'> watch this element as you resize your viewport's width and height. </div> css /* minimum aspect ratio */ @media (min-aspect-ratio: 8/5) { div { background: #9af; /* blue */ } } /* maximum aspect ratio */ @media (max-aspect-ratio: 3/2) { div { ...
color-gamut - CSS: Cascading Style Sheets
srgb the output device can support approximately the srgb gamut or more. this includes the vast majority of color displays. p3 the output device can support approximately the gamut specified by the dci p3 color space or more. the p3 gamut is larger than and includes the srgb gamut. ...
color - CSS: Cascading Style Sheets
Web › CSS › @media › color
ue and red and 6 bits for green, then the device is considered to use 5 bits per color component. if the device uses indexed colors, the minimum number of bits per color component in the color table is used. see applying color to html elements using css to learn more about using css to apply color to html. ...
display-mode - CSS: Cascading Style Sheets
experience between launching a site from a url and launching it from a desktop icon. this feature corresponds to the web app manifest's display member. both apply to the top-level browsing context and any child browsing contexts. the feature query applies regardless of whether a web app manifest is present. syntax the display-mode feature is specified as a keyword value chosen from the list below. display mode description fallback display mode fullscreen all of the available display 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 use...
height - CSS: Cascading Style Sheets
Web › CSS › @media › height
ght. 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 which case it computes to false. media queriesthe definition of 'heig...
hover - CSS: Cascading Style Sheets
Web › CSS › @media › hover
the hover css media feature can be used to test whether the user's primary input mechanism can hover over elements. syntax the hover feature is specified as a keyword value chosen from the list below. none the primary input mechanism cannot hover at all or cannot conveniently hover (e.g., many mobile devices emulate hovering when the user performs an inconvenient long tap), or there is no primary pointing input mechanism. hover the primary input mechanism can conveniently hover over elements. examples html <a href="#">try hovering over me!</a> css @media (hover: hover) { a:hover { background: yellow; } } result specifications specification status comment media queries level 4the definition of 'hover' in that specification. candidate r...
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. washed the device is used in an exceptionally bright environment, causing the screen to be washed out and difficult to read. for example: bright daylight. examples this code will likely not work on any devices (device compatibility is low). @media (light-level: normal) { p { background: url("texture.jpg"); color: #333; } } @media (light-level: dim) { p { background: #222; color: #ccc; } } @media (light-level: washed) { p { background: white; color: black; font-size: 2em; } } specifications specification status comment media queries level 5the definition of '...
pointer - CSS: Cascading Style Sheets
Web › CSS › @media › pointer
none the primary input mechanism does not include a pointing device. ...
prefers-color-scheme - CSS: Cascading Style Sheets
eme css media feature is used to detect if the user has requested the system use a light or dark color theme. syntax light indicates that user has notified the system that they prefer an interface that has a light theme, or has not expressed an active preference. dark indicates that user has notified the system that they prefer an interface that has a dark theme. examples the elements below have an initial color theme. they can be further themed according to the user's color scheme preference. html <div class="day">day (initial)</div> <div class="day light-scheme">day (changes in light scheme)</div> <div class="day dark-scheme">day (changes in dark scheme)</div> <br> <div class="night">night (initial)</div> <div class="night light-scheme">night (changes in light scheme)</div> <di...
prefers-reduced-data - CSS: Cascading Style Sheets
at user has expressed the preference for lightweight alternate content. 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 system. examples note: no browser currently implements this feature so the following example will not work. in this example the montserrat-regular.woff2 font file will neither be preloaded nor downloaded if the user prefers reduced data, in this case the "system font stack" will serve as the fallback font: html <head> <link rel="preload" href="fonts/montserrat-regular.woff2" as="font" media="(prefers-reduced-data: no-preference)" crossorigin> <link rel="stylesheet" hre...
prefers-reduced-transparency - CSS: Cascading Style Sheets
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 so the following example will not work. this example has an annoying transparency effect by default. html <div class="transparency">transparent box</div> css .transparency { opacity: 0.5; } @media (prefers-reduced-transparency: reduce) { .transparency { opacity: 1; } } result specifications specification status comment media queries level 5the definition of '...
resolution - CSS: Cascading Style Sheets
Web › CSS › @media › resolution
s 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. ...
scan - CSS: Cascading Style Sheets
Web › CSS › @media › scan
ia feature can be used to test the scanning process (if any) utilized by the output device. the word scanning used in this context does not refer to an image scanner, such as one used to digitize a photograph. rather, it means the process by which an image is painted onto a television screen (or other device). syntax the scan feature is specified as a single keyword value chosen from the list below. interlace the device draws odd lines and even lines alternately. some televisions use interlaced scanning. progressive the device draws all lines in sequence. all computer screens use progressive scanning. examples html <p>if your screen uses interlaced rendering, this text should be in a sans-serif font. if your screen uses progressive scanning, you should see a serif font.</p> ...
scripting - CSS: Cascading Style Sheets
Web › CSS › @media › scripting
none scripting is completely unavailable on the current document. initial-only scripting is enabled during the initial page load, but not afterwards. enabled scripting is supported and active on the current document. examples html <p class="script-none">you do not have scripting available. :-(</p> <p class="script-initial-only">your scripting is only enabled during the initial page load. ...
update - CSS: Cascading Style Sheets
the update css media feature can be used to test how frequently (if at all) the output device is able to modify the appearance of content. syntax the update feature is specified as a single keyword value chosen from the list below. none once it has been rendered, the layout can no longer be updated. example: documents printed on paper. slow the layout may change dynamically according to the usual rules of css, but the output device is not able to render or display changes quickly enough for them to be perceived as a smooth animation. examples: e-book readers or severely underpowered devices. fast the layout may change dynamically according to the usual rules of css, and the output device is not unusually constrained in speed, so regularly-updating things like css animations can be ...
width - CSS: Cascading Style Sheets
Web › CSS › @media › width
port 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 case it computes to false. media queriesthe definition of 'width' ...
@namespace - CSS: Cascading Style Sheets
prefix "xml-namespace-url"; description the defined namespaces can be used to restrict the universal, type, and attribute selectors to only select elements within that namespace. the @namespace rule is generally only useful when dealing with documents containing multiple namespaces—such as html5 with inline svg or mathml, or xml that mixes multiple vocabularies. any @namespace rules must follow all @charset and @import rules, and precede all other at-rules and style declarations in a style sheet. @namespace can be used to define the default namespace for the style sheet. when a default namespace is defined, all universal and type selectors (but not attribute selectors, see note below) apply only to elements in that namespace. the @namespace rule can also be used to define a namespace ...
min-zoom - CSS: Cascading Style Sheets
l 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 itselfcomputed valueauto, or a non-negative number or percentage as specified formal syntax auto | <number> | <percenta...
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 ...
Adjacent sibling combinator - CSS: Cascading Style Sheets
/* paragraphs that come immediately after any image */ img + p { font-weight: bold; } syntax former_element + target_element { style properties } examples css li:first-of-type + li { color: red; } html <ul> <li>one</li> <li>two!</li> <li>three</li> </ul> result specifications specification status comment selectors level 4the definition of 'next-sibling combinator' in that specification. ...
Alternative style sheets - CSS: Cascading Style Sheets
isted in the page style submenu, with "default style" pre-selected. when the user selects a different style, the page will immediately be re-rendered using that style sheet. no matter what style is selected, the rules from the reset.css stylesheet will always be applied. try it out click here for a working example you can try out. details any stylesheet in a document falls into one of the following categories: persistent (no rel="alternate", no title=""): always applies to the document. preferred (no rel="alternate", with title="..." specified): applied by default, but disabled if an alternate stylesheet is selected. there can only be one preferred stylesheet, so providing stylesheets with different title attributes will cause some of them to be ignored. see correctly using titles wi...
At-rules - CSS: Cascading Style Sheets
Web › CSS › At-rule
/* general structure */ @identifier (rule); /* example: tells browser to use utf-8 character set */ @charset "utf-8"; there are several at-rules, designated by their identifiers, each with a different syntax: @charset — defines the character set used by the style sheet. @import — tells the css engine to include an external style sheet. ...
Detecting CSS animation support - CSS: Cascading Style Sheets
we assume that animation is not supported by setting animation to false. we set the animationstring to animation which is the property we want to set later on. we create an array of browser prefixes to loop over and we set pfx to an empty string. then we check if the css animation-name prope...
CSS Backgrounds and Borders - CSS: Cascading Style Sheets
these styles can also decorate borders with lines or images, and make them square or rounded. ...
CSS Basic User Interface - CSS: Cascading Style Sheets
css basic user interface is a css module that lets you define the rendering and functionality of features related to the user interface. reference properties appearance box-sizing cursor ime-mode nav-down nav-left nav-right nav-up outline outline-width outline-style outline-color outline-offset resize text-overflow user-select guides using url values for the cursor property explains how a url can be used with the cursor property to produce custom cursors. specifications specification status comment css basic user interface module level 4 working draft css basic user interface module level 3 recommendation css level 2 (revision 1) recommendation initial definition. ...
Box alignment for block, absolutely positioned and table layout - CSS: Cascading Style Sheets
d right margin of auto, you can push a block into the center: .container { width: 20em; margin-left: auto; margin-right: auto; } in table layout, you have access to the vertical-align property to align the contents of a cell inside that cell. for many use cases, turning the block container into a flex item will give you the alignment capability that you are looking for. in the example below, a container with a single item inside has been turned into a flex container for the purpose of being able to use the alignment properties. reference css properties justify-content align-content justify-self align-self glossary entries alignment subject alignment container fallback alignment ...
Box alignment in Multi-column Layout - CSS: Cascading Style Sheets
ich are specific to multi-column layout and box alignment, it should be read in conjunction with the main box alignment page which details the common features of box alignment across layout methods. in multi-column layout the alignment container is the content box of the multicol container. the alignment subject is the column box. the properties which apply to multi-column layouts are detailed below. note: multi-column layout predates the box alignment specification. and the properties listed here, while specified for multicol, may not be supported in browsers. align-content and justify-content the align-content property applies to the block axis and justify-content to the inline axis. any spacing added to the columns due to use of space distribution will be added to the gap between the...
Styling Columns - CSS: Cascading Style Sheets
ps between boxes in other specifications such as css grid layout. the initial value of column-gap in multicol is 1em. this means your columns will not run into each other. in other layout methods the initial value for column-gap is 0. if you use the keyword value “normal” the gap will be set to 1em. you can change the gap by using any length unit as the value of column-gap. in the example below, the column-gap is set to 40px. the allowed value for column-gap is a <length-percentage>, this means percentages are allowed. percentage values for column-gap are calculated as a percentage of the width of the multicol container. column rules the specification defines column-rule-width, column-rule-style and column-rule-color, providing a shorthand column-rule. these properties work in exac...
CSS Conditional Rules - CSS: Cascading Style Sheets
css conditional rules is a css module that allows to define a set of rules that will only apply based on the capabilities of the processor or the document the style sheet is being applied to. reference at-rules @document @media @supports @import specifications specification status comment css conditional rules module level 3 candidate recommendation initial definition ...
Consistent list indentation - CSS: Cascading Style Sheets
down, and what we're left with is this: if you want consistent rendering of lists between gecko, internet explorer, and opera, you need to set both the left margin and left padding of the <ul> element. we can ignore <li> altogether for these purposes. if you want to reproduce the default display in netscape 6.x, you write: ul {margin-left: 0; padding-left: 40px;} if you're more interested in following the internet explorer/opera model, then: ul {margin-left: 40px; padding-left: 0;} of course, you can fill in your own preferred values. set both to 1.25em, if you like -- there's no reason why you have to stick with pixel-based indentation. if you want to reset lists to have no indentation, then you still have to zero out both padding and margin: ul {margin-left: 0; padding-left: 0;} remem...
CSS Namespaces - CSS: Cascading Style Sheets
css namespaces is a css module that allows authors to specify xml namespaces in css. reference at-rules @namespace specifications specification status comment css namespaces module recommendation initial definition ...
Using z-index - CSS: Cascading Style Sheets
default rendering layer) layer 1 layer 2 layer 3 ... top layer (closest to the observer) notes: when no z-index property is specified, elements are rendered on the default rendering layer 0 (zero). if several elements share the same z-index value (i.e., they are placed on the same layer), stacking rules explained in the section stacking without the z-index property apply. in the following example, the layers' stacking order is rearranged using z-index. the z-index of element #5 has no effect since it is not a positioned element. source code for the example html <div id="abs1"> <b>div #1</b> <br />position: absolute; <br />z-index: 5; </div> <div id="rel1"> <b>div #2</b> <br />position: relative; <br />z-index: 3; </div> <div id="rel2"> <b>div #3</b> <br /...
Stacking with floated blocks - CSS: Cascading Style Sheets
for floated blocks, the stacking order is a bit different. floating blocks are placed between non-positioned blocks and positioned blocks: the background and borders of the root element descendant non-positioned blocks, in order of appearance in the html floating blocks descendant positioned elements, in order of appearance in the html actually, as you can see in the example below, the background and border of the non-positioned block (div #4) is completely unaffected by floating blocks, but the content is affected. this happens according to standard float behaviour. this behavior can be shown with an added rule to the above list: the background and borders of the root element descendant non-positioned blocks, in order of appearance in the html floating blocks descendant non-po...
Stacking context example 1 - CSS: Cascading Style Sheets
div #2 can be controlled through z-index. it happens that, since div #1 and div #3 are not assigned any z-index value, they do not create a stacking context. this means that all their content, including div #2 and div #4, belongs to the same root stacking context. in terms of stacking contexts, div #1 and div #3 are simply assimilated into the root element, and the resulting hierarchy is the following: root stacking context div #2 (z-index 1) div #4 (z-index 2) note: div #1 and div #3 are not translucent. it is important to remember that assigning an opacity less than 1 to a positioned element implicitly creates a stacking context, just like adding a z-index value. and this example shows what happens when a parent element does not create a stacking context. example html...
Stacking context example 3 - CSS: Cascading Style Sheets
only relatively positioned, so no stacking context is created. the second-level menu is absolutely positioned inside the parent element. in order to put it above all first-level menus, a z-index is used. the problem is that for each second-level menu, a stacking context is created and each third-level menu belongs to the context of its parent. so a third-level menu will be stacked under the following second-level menus, because all second-level menus share the same z-index value and the default stacking rules apply. to better understand the situation, here is the stacking context hierarchy: root stacking context level #1 level #2 (z-index: 1) level #3 ... level #3 level #2 (z-index: 1) ... level #2 (z-index: 1) ...
Stacking without the z-index property - CSS: Cascading Style Sheets
when the z-index property is not specified on any element, elements are stacked in the following order (from bottom to top): the background and borders of the root element descendant non-positioned blocks, in order of appearance in the html descendant positioned elements, in order of appearance in the html keep in mind, when the order property alters rendering from the "order of appearance in the html" within flex containers, it similarly affects the order for stacking context. 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...
Understanding CSS z-index - CSS: Cascading Style Sheets
in the most basic cases, html pages can be considered two-dimensional, because text, images, and other elements are arranged on the page without overlapping. in this case, there is a single rendering flow, and all elements are aware of the space taken by others. the z-index attribute lets you adjust the order of the layering of objects when rendering content. in css 2.1, each box has a position in three dimensions. in addition to their horizontal and vertical positions, boxes lie along a "z-axis" and are formatted one on top of the other. z-axis positions are particularly relevant when boxes overlap visually. (from css 2.1 section 9.9.1 - layered presentation) this means that css style rules allow you to position boxes on layers in addition to the normal rendering layer (layer 0). the z...
CSS Scrollbars - CSS: Cascading Style Sheets
css scrollbars standardizes the obsolete scrollbar color properties introduced in 2000 by windows ie 5.5. basic example in this example we have chosen to use a thin scrollbar, with a green track and purple thumb. .scroller { width: 300px; height: 100px; overflow-y: scroll; scrollbar-color: rebeccapurple green; scrollbar-width: thin; } html <div class="scroller"> veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic. gumbo beet greens corn soko endive gumbo gourd. parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. dandelion cucumber earthnut pea peanut soko zucchini. </div> result reference css properties scrollbar-width scrollba...
Using the :target pseudo-class in selectors - CSS: Cascading Style Sheets
f the document. this is done using the same identifying value that is found in the uri. thus, to add a border to the #example fragment, we would write: #example:target { border: 1px solid black; } targeting all elements if the intent is to create a "blanket" style that will apply to all targeted elements, then the universal selector comes in handy: :target { color: red; } example in the following example, there are five links that point to elements in the same document. selecting the "first" link, for example, will cause <h1 id="one"> to become the target element. note that the document may jump to a new scroll position, since target elements are placed on the top of the browser window if possible. <h4 id="one">...</h4> <p id="two">...</p> <div id="three">...</div> <a id="four">...</...
CSS Shapes - CSS: Cascading Style Sheets
css shapes describe geometric shapes for use in css. for the level 1 specification, css shapes can be applied to floating elements. the specification defines a number of different ways to define a shape on a floated element, causing wrapping lines to wrap round the shape rather than following the rectangle of the element's box. basic example the example below shows an image that has been floated left, and the shape-outside property applied with a value of circle(50%). this creates a circle shape, and the content wrapping the float now wraps around that shape. this changes the length of the wrapping text's line boxes. reference properties shape-image-threshold shape-margin shape-outside data types <basic-shape> guides overview of css shapes shapes from box values ba...
CSS Text - CSS: Cascading Style Sheets
Web › CSS › CSS Text
css text is a module of css that defines how to perform text manipulation, like line breaking, justification and alignment, white space handling, and text transformation. reference properties hanging-punctuation hyphens letter-spacing line-break overflow-wrap tab-size text-align text-align-last text-indent text-justify text-size-adjust text-transform white-space word-break word-spacing specifications specification status comment css logical properties and values level 1 editor's draft updates some properties to be independent of the directionality of the text. css text module level 3 working draft css level 2 (revision 1) recommendation css level 1 recommendation initial definition ...
CSS Text Decoration - CSS: Cascading Style Sheets
"over">this text has a line over it.</p> <p class="line">this text has a line going through it.</p> <p>this <a class="plain" href="#">link will not be underlined</a>, as links generally are by default. ...
CSS data types - CSS: Cascading Style Sheets
Web › CSS › CSS Types
css data types define typical values (including keywords and units) accepted by css properties and functions. they are a special kind of component value type. in formal syntax, data types are denoted by a keyword placed between the inequality signs "<" and ">". ...
CSS Custom Properties for Cascading Variables - CSS: Cascading Style Sheets
css custom properties for cascading variables is a css module that allows for the creation of custom properties that can be used over and over. css properties --* specifications specification status comment css custom properties for cascading variables module level 1 candidate recommendation initial definition ...
Class selectors - CSS: Cascading Style Sheets
elements with class="spacious" */ .spacious { margin: 2em; } /* all <li> elements with class="spacious" */ li.spacious { margin: 2em; } /* all <li> elements with a class list that includes both "spacious" and "elegant" */ /* for example, class="elegant retro spacious" */ li.spacious.elegant { margin: 2em; } syntax .class_name { style properties } note that this is equivalent to the following attribute selector: [class~=class_name] { style properties } examples css .red { color: #f33; } .yellow-bg { background: #ffa; } .fancy { font-weight: bold; text-shadow: 4px 4px 3px #77f; } html <p class="red">this paragraph has red text.</p> <p class="red yellow-bg">this paragraph has red text and a yellow background.</p> <p class="red fancy">this paragraph has red text and "...
Questions about CSS - CSS: Cascading Style Sheets
Web › CSS › FAQ
css gives more control over the appearance of a web page to the page creator than to the browser designer or the viewer. with css, the sources of style definition for a given document element are in this order of precedence: the style attribute on an individual element tag the style element that defines a specific style sheet containing style declarations or a link element that links to a separate document containing the style element. in a web page, the style element is placed between the title statement and the body statement. ...
General sibling combinator - CSS: Cascading Style Sheets
the general sibling combinator (~) separates two selectors and matches the second element only if it follows the first element (though not necessarily immediately), and both are children of the same parent element. /* paragraphs that are siblings of and subsequent to any image */ img ~ p { color: red; } syntax former_element ~ target_element { style properties } examples css p ~ span { color: red; } html <span>this is not red.</span> <p>here is a paragraph.</p> <code>here is some code.</code> <span>and here is a red span!</span> <code>more code...</code> <span>and this is a red span!</span> result specifications specification status comment selectors level 4the definition of 'subsequent-sibling combinator' in that specification. working dr...
ID selectors - CSS: Cascading Style Sheets
the css id selector matches an element based on the value of the element’s id attribute. in order for the element to be selected, its id attribute must match exactly the value given in the selector. /* the element with id="demo" */ #demo { border: red 2px solid; } syntax #id_value { style properties } note that syntactically (but not specificity-wise), this is equivalent to the following attribute selector: [id=id_value] { style properties } examples css #identified { background-color: skyblue; } html <div id="identified">this div has a special id on it!</div> <div>this is just a regular div.</div> result specifications specification status comment selectors level 4the definition of 'id selectors' in that specification. working draft ...
Card - CSS: Cascading Style Sheets
the same height, and footers should stick to the bottom of the card. when added to a collection of cards, the cards should line up in two dimensions. recipe download this example choices made the card is laid out using css grid layout despite being a single dimensional layout, as it enables the use of content sizing for the grid tracks. when setting up the single column grid i use the following: .card { display: grid; grid-template-rows: max-content 200px 1fr; } the heading track is set to max-content, which prevents it from stretching. i have decided that i want my image to live within a track that is 200 pixels tall. i then set the next track — which is where the content lives — to 1fr. this means it will take up any additional space. if the track does have a footer it ...
Column layouts - CSS: Cascading Style Sheets
d. therefore to create gaps between items use a margin. download this example flexbox can also be used to create layouts where the flex items wrap onto new rows, by setting the flex-wrap property on the container to wrap. these new flex lines will distribute space along that line only — the items in the new line will not line up with items in the line above, as you'll see in the example below. this is why flexbox is described as one-dimensional. it is designed for controlling layout as a row or a column, but not both at the same time. download this example use flexbox: for single rows or columns of items. when you want to do alignment on the cross axis after laying out your items. when you are happy for wrapped items to share out space along their line only and not line up ...
Cookbook template - CSS: Cascading Style Sheets
s cookbook page. please use this as a raw template when you create a new cookbook page. comment in italics are information about how to use part of the template. description of the problem this recipe solves or the pattern you are demonstrating. requirements what does this pattern need to include, or what problems does it need to solve? list that here. recipe change the path to the example below to point to your merged example. the last parameter is the live example height, which you can change as needed. change the link to point to your merged download version. download the example choices made explain your decisions when creating the pattern. why did you choose a certain method? if you want to add an additional example here — for example a version with fallbacks, please do. thi...
Recipe: Media objects - CSS: Cascading Style Sheets
the media object is a pattern we see all over the web. named by nicole sullivan it refers to a two-column box with an image on one side and descriptive text on the other, e.g. a facebook post or tweet. requirements media object pattern needs some or all of the following characteristics: stacked on mobile, two columns on desktop. the image can be on the left or right. the image might be small or large. media objects can be nested. the media object should clear the contents no matter which side is tallest. the recipe download this example choices made i have chosen to use grid layout for the media object as it allows me to control the layout in two dimensions when i need to. this means that when we have a footer, with short content above, the footer can be pushed down to th...
Sticky footers - CSS: Cascading Style Sheets
a sticky footer pattern is one where the footer of your page "sticks" to the bottom of the viewport in cases where the content is shorter than the viewport height. we'll look at a couple of techniques for creating one 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 containe...
Layout mode - CSS: Cascading Style Sheets
a css layout mode, sometimes simply called layout, is an algorithm that determines the position and size of boxes based on the way they interact with their sibling and ancestor boxes. 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. positioned layout, designed for positioning elements without much interaction with other elements. multi-column layout, designed for laying content out in c...
Paged media - CSS: Cascading Style Sheets
paged media properties control the presentation of content for print or any other media that splits content into discrete pages. it allows you to set page breaks, control printable area, style left and right pages differently, and control breaks inside elements. widely supported properties include: page-break-before page-break-after page-break-inside orphans widows @page ...
Pseudo-elements - CSS: Cascading Style Sheets
er versions of the w3c spec, most browsers support both syntaxes for the original pseudo-elements. ...
Scaling of SVG backgrounds - CSS: Cascading Style Sheets
trinsic ratio this image doesn't specify either a width or a height; instead, it specifies an intrinsic ratio of 1:1. think of this like a program icon. it's always square, and is usable at any size, such as 32x32, 128x128, or 512x512, for example. svg source scaling examples now let's see some examples of what happens as we apply different scaling to these images. in each of the examples below, the enclosing rectangles are 300 pixels wide and 200 pixels tall. in addition, the backgrounds have background-repeat set to no-repeat for clarity. note: the screenshots below show the expected rendering. not all browsers currently render these correctly. specifying fixed lengths for both dimensions if you use background-size to specify fixed lengths for both dimensions, those lengths are alw...
Selector list - CSS: Cascading Style Sheets
ent { style properties } examples single line grouping grouping selectors in a single line using a comma-separated lists. h1, h2, h3, h4, h5, h6 { font-family: helvetica; } multi line grouping grouping selectors in a multiple lines using a comma-separated lists. #main, .content, article { font-size: 1.1em; } selector list invalidation a downside to using selector lists is that the following aren't equivalent: h1 { font-family: sans-serif } h2:maybe-unsupported { font-family: sans-serif } h3 { font-family: sans-serif } h1, h2:maybe-unsupported, h3 { font-family: sans-serif } this is because a single unsupported selector in a selector list invalidates the whole rule. a way to remedy this us to use the :is() selector, which simply ignores invalid selectors in its arguments, but ...
Universal selectors - CSS: Cascading Style Sheets
agraph. </p> result specifications specification status comment selectors level 4the definition of 'universal selector' in that specification. working draft no changes selectors level 3the definition of 'universal selector' in that specification. recommendation defines behavior regarding namespaces and adds hint that omitting the selector is allowed within pseudo-elements css level 2 (revision 1)the definition of 'universal selector' in that specification. recommendation initial definition ...
all - CSS: Cascading Style Sheets
Web › CSS › all
kquote id="quote">lorem ipsum dolor sit amet, consectetur adipiscing elit.</blockquote> phasellus eget velit sagittis. body { font-size: small; background-color: #f0f0f0; color:blue; } blockquote { background-color: skyblue; color: red; } the <blockquote> uses the browser's default styling together with a specific background and text color. it also behaves as a block element: the text that follows it is beneath it. all:unset <blockquote id="quote">lorem ipsum dolor sit amet, consectetur adipiscing elit.</blockquote> phasellus eget velit sagittis. body { font-size: small; background-color: #f0f0f0; color:blue; } blockquote { background-color: skyblue; color: red; } blockquote { all: unset; } the <blockquote> doesn't use the browser default styling: it is an inline element now (init...
<angle-percentage> - CSS: Cascading Style Sheets
the <angle-percentage> css data type represents a value that can be either a <angle> or a <percentage>. syntax refer to the documentation for <angle> and <percentage> for details of the individual syntaxes allowed by this type. use in calc() where an <angle-percentage> is specified as an allowable type, this means that the percentage resolves to an angle and therefore can be used in a calc() expression. specifications specification status comment css values and units module level 4the definition of '<angle-percentage>' in that specification. editor's draft css values and units module level 3the definition of '<angle-percentage>' in that specification. candidate recommendation defines <angle-percentage>. adds calc() ...
<angle> - CSS: Cascading Style Sheets
Web › CSS › angle
d in degrees, gradians, radians, or turns. it is used, for example, in <gradient>s and in some transform functions. 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 <angle> data type consists of a <number> followed by one of the units listed below. as with all dimensions, there is no space between the unit literal and the number. the angle unit is optional after the number 0. optionally, it may be preceded by a single + or - sign. positive numbers represent clockwise angles, while negative numbers represent counterclockwise angles. for static properties of a given unit, any angle can be represented by va...
aspect-ratio - CSS: Cascading Style Sheets
the aspect-ratio css property sets a preferred aspect ratio for the box, which will be used in the calculation of auto sizes and some other layout functions. this property is not yet implemented in browsers, however some browsers are implementing this internally in order to provide the aspect ratio mapping described below. syntax aspect-ratio: 1 / 1; /* global values */ aspect-ratio: inherit; aspect-ratio: initial; aspect-ratio: unset; values <auto> replaced elements with an intrinsic aspect ratio use that aspect ratio, otherwise the box has no preferred aspect ratio. size calculations involving intrinsic aspect ratio always work with the content box dimensions. <ratio> the box’s preferred aspect ratio is the specified ratio of width / height. size calculations involving pr...
backface-visibility - CSS: Cascading Style Sheets
n causes the element to be rotated in 3d space. (this property has no effect on 2d transforms, which have no perspective.) syntax /* keyword values */ backface-visibility: visible; backface-visibility: hidden; /* global values */ backface-visibility: inherit; backface-visibility: initial; backface-visibility: unset; the backface-visibility property is specified as one of the keywords listed below. values visible the back face is visible when turned towards the user. hidden the back face is hidden, effectively making the element invisible when turned away from the user. formal definition initial valuevisibleapplies totransformable elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax visible | hidden examples cube with transparent and opaque faces ...
background-clip - CSS: Cascading Style Sheets
rder.</p> <p class="padding-box">the background extends to the inside edge of the border.</p> <p class="content-box">the background extends only to the edge of the content box.</p> <p class="text">the background is clipped to the foreground text.</p> css p { border: .8em darkviolet; border-style: dotted double; margin: 1em 0; padding: 1.4em; background: linear-gradient(60deg, red, yellow, red, yellow, red); font: 900 1.2em sans-serif; text-decoration: underline; } .border-box { background-clip: border-box; } .padding-box { background-clip: padding-box; } .content-box { background-clip: content-box; } .text { background-clip: text; -webkit-background-clip: text; color: rgba(0,0,0,.2); } result specifications specification status comment ...
background-color - CSS: Cascading Style Sheets
<color> value. values <color> the uniform color of the background. it is rendered behind any 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. ...
background-origin - CSS: Cascading Style Sheets
l request. note that background-origin is ignored when background-attachment is fixed. syntax /* keyword values */ background-origin: border-box; background-origin: padding-box; background-origin: content-box; /* global values */ background-origin: inherit; background-origin: initial; background-origin: unset; the background-origin property is specified as one of the keyword values listed below. values border-box the background is positioned relative to the border box. padding-box the background is positioned relative to the padding box. content-box the background is positioned relative to the content box. formal definition initial valuepadding-boxapplies toall elements. it also applies to ::first-letter and ::first-line.inheritednocomputed valueas specifiedanimation typedis...
block-size - CSS: Cascading Style Sheets
ies. formal definition initial valueautoapplies tosame as width and heightinheritednopercentagesblock-size of containing blockcomputed valuesame as width and heightanimation typea length, percentage or calc(); formal syntax <'width'> examples block size with vertical text html <p class="exampletext">example text</p> css .exampletext { writing-mode: vertical-rl; background-color: yellow; block-size: 200px; } result specifications specification status comment css logical properties and values level 1the definition of 'block-size' in that specification. editor's draft initial definition ...
border-block-end-style - CSS: Cascading Style Sheets
styles of the element. values <'border-style'> the line style of the border. see border-style. formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <'border-top-style'> examples dashed border with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 5px solid blue; border-block-end-style: dashed; } results specifications specification status comment css logical properties and values level 1the definition of 'border-block-end-style' in that specification. editor's draft initial definition ...
border-block-end-width - CSS: Cascading Style Sheets
rder-width. formal definition initial valuemediumapplies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueabsolute length; 0 if the border style is none or hiddenanimation typea length formal syntax <'border-top-width'> examples border width with veritcal text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 1px solid blue; border-block-end-width: 5px; } results specifications specification status comment css logical properties and values level 1the definition of 'border-block-end-width' in that specification. editor's draft initial definition ...
border-block-start-color - CSS: Cascading Style Sheets
which define the other border colors of the element. values <'color'> see border-color formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typea color formal syntax <'border-top-color'> examples border color with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 10px solid blue; border-block-start-color: red; } results specifications specification status comment css logical properties and values level 1the definition of 'border-block-start-color' in that specification. editor's draft initial definition ...
border-block-start-style - CSS: Cascading Style Sheets
styles of the element. values <'border-style'> the line style of the border. see border-style. formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <'border-top-style'> examples dashed border wtih vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 5px solid blue; border-block-start-style: dashed; } results specifications specification status comment css logical properties and values level 1the definition of 'border-block-start-style' in that specification. editor's draft initial definition ...
border-block-start-width - CSS: Cascading Style Sheets
rder-width. formal definition initial valuemediumapplies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueabsolute length; 0 if the border style is none or hiddenanimation typea length formal syntax <'border-top-width'> examples border width with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 1px solid blue; border-block-start-width: 5px; } results specifications specification status comment css logical properties and values level 1the definition of 'border-block-start-width' in that specification. editor's draft initial definition ...
border-block-style - CSS: Cascading Style Sheets
line-end-style. syntax values <'border-style'> the line style of the border. see border-style. formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <'border-top-style'> examples dashed border with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 5px solid blue; border-block-style: dashed; } results specifications specification status comment css logical properties and values level 1the definition of 'border-block-style' in that specification. editor's draft initial definition ...
border-block-width - CSS: Cascading Style Sheets
rder-width. formal definition initial valuemediumapplies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueabsolute length; 0 if the border style is none or hiddenanimation typediscrete formal syntax <'border-top-width'> examples border width with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 1px solid blue; border-block-width: 5px; } results specifications specification status comment css logical properties and values level 1the definition of 'border-block-width' in that specification. editor's draft initial definition ...
border-bottom-left-radius - CSS: Cascading Style Sheets
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-table elements when border-collapse is collapse. the behavior on internal table ele...
border-bottom-right-radius - CSS: Cascading Style Sheets
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-table elements when border-collapse is collapse. the behavior on internal table ele...
border-bottom - CSS: Cascading Style Sheets
yle: dotted; border-bottom: thick green; ... is actually the same as ... border-bottom-style: dotted; border-bottom: none thick green; ... and the value of border-bottom-style given before border-bottom is ignored. since the default value of border-bottom-style is none, not specifying the border-style part results in no border. constituent properties this property is a shorthand for the following css properties: border-bottom-color border-bottom-style border-bottom-width syntax border-bottom: 1px; border-bottom: 2px dotted; border-bottom: medium dashed blue; the three values of the shorthand property can be specified in any order, and one or two of them may be omitted. values <br-width> see border-bottom-width. <br-style> see border-bottom-style. <color> see border-b...
border-end-end-radius - CSS: Cascading Style Sheets
*/ 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-table elements when border-collapse is collapse. the behavior on internal table ele...
border-end-start-radius - CSS: Cascading Style Sheets
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-table elements when border-collapse is collapse. the behavior on internal table ele...
border-image-outset - 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. ...
border-image-repeat - CSS: Cascading Style Sheets
/ border-image-repeat: stretch; border-image-repeat: repeat; border-image-repeat: round; border-image-repeat: space; /* vertical | horizontal */ border-image-repeat: round stretch; /* global values */ border-image-repeat: inherit; border-image-repeat: initial; border-image-repeat: unset; the border-image-repeat property may be specified using one or two values chosen from the list of values below. when one value is specified, it applies the same behavior on all four sides. when two values are specified, the first applies to the top and bottom, the second to the left and right. values stretch the source image's edge regions are stretched to fill the gap between each border. repeat the source image's edge regions are tiled (repeated) to fill the gap between each border. tiles ma...
border-image-source - CSS: Cascading Style Sheets
t, please clone https://github.com/mdn/interactive-examples and send us a pull request. the border-image-slice property is used to divide the source image into regions, which are then dynamically applied to the final border image. syntax /* keyword value */ border-image-source: none; /* <image> values */ border-image-source: url(image.jpg); border-image-source: linear-gradient(to top, red, yellow); /* global values */ border-image-source: inherit; border-image-source: initial; border-image-source: unset; values none no border image is used. the appearance defined by border-style is displayed instead. <image> image reference to use for the border. formal definition initial valuenoneapplies toall elements, except internal table elements when border-collapse is collapse. it also ...
border-inline-end-color - CSS: Cascading Style Sheets
lementsinheritednocomputed valuecomputed coloranimation typea color values <'color'> the color of the border. see color. formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typea color formal syntax <'border-top-color'> examples html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 10px solid blue; border-inline-end-color: red; } specifications specification status comment css logical properties and values level 1the definition of 'border-inline-end-color' in that specification. editor's draft initial definition ...
border-inline-end-style - CSS: Cascading Style Sheets
yle, which define the other border styles of the element. values <'border-style'> the line style of the border. see border-style. formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <'border-top-style'> examples html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 5px solid blue; border-inline-end-style: dashed; } results specifications specification status comment css logical properties and values level 1the definition of 'border-inline-end-style' in that specification. editor's draft initial definition ...
border-inline-end-width - CSS: Cascading Style Sheets
width. formal definition initial valuemediumapplies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueabsolute length; 0 if the border style is none or hiddenanimation typea length formal syntax <'border-top-width'> examples applying a border with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 1px solid blue; border-inline-end-width: 5px; } results specifications specification status comment css logical properties and values level 1the definition of 'border-inline-end-width' in that specification. editor's draft initial definition ...
border-inline-start-color - CSS: Cascading Style Sheets
ine-end-color, which define the other border colors of the element. values <'color'> the color of the border. see color. formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typea color formal syntax <'border-top-color'> examples html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 10px solid blue; border-inline-start-color: red; } specifications specification status comment css logical properties and values level 1the definition of 'border-inline-start-color' in that specification. editor's draft initial definition ...
border-inline-start-style - CSS: Cascading Style Sheets
heritednocomputed valueas specifiedanimation typediscrete values <'border-style'> the line style of the border. see border-style. formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <'border-top-style'> examples html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 5px solid blue; border-inline-start-style: dashed; } specifications specification status comment css logical properties and values level 1the definition of 'border-inline-start-style' in that specification. editor's draft initial definition ...
border-inline-start-width - CSS: Cascading Style Sheets
the width of the border. see border-width. formal definition initial valuemediumapplies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueabsolute length; 0 if the border style is none or hiddenanimation typea length formal syntax <'border-top-width'> examples html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 1px solid blue; border-inline-start-width: 5px; } specifications specification status comment css logical properties and values level 1the definition of 'border-inline-start-width' in that specification. editor's draft initial definition ...
border-inline-style - CSS: Cascading Style Sheets
tyle, and border-block-end-style. syntax values <'border-style'> the line style of the border. see border-style. formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <'border-top-style'> examples html content <div> <p class="exampletext">example text</p> </div> css content div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 5px solid blue; border-inline-style: dashed; } specifications specification status comment css logical properties and values level 1the definition of 'border-inline-style' in that specification. editor's draft initial definition ...
border-inline-width - CSS: Cascading Style Sheets
the width of the border. see border-width. formal definition initial valuemediumapplies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueabsolute length; 0 if the border style is none or hiddenanimation typediscrete formal syntax <'border-top-width'> examples html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 1px solid blue; border-inline-width: 5px 10px; } specifications specification status comment css logical properties and values level 1the definition of 'border-inline-width' in that specification. editor's draft initial definition ...
border-left - CSS: Cascading Style Sheets
rder-left-style: dotted; border-left: thick green; ... is actually the same as ... border-left-style: dotted; border-left: none thick green; ... and the value of border-left-style given before border-left is ignored. since the default value of border-left-style is none, not specifying the border-style part results in no border. constituent properties this property is a shorthand for the following css properties: border-left-color border-left-style border-left-width syntax border-left: 1px; border-left: 2px dotted; border-left: medium dashed green; the three values of the shorthand property can be specified in any order, and one or two of them may be omitted. values <br-width> see border-left-width. <br-style> see border-left-style. <color> see border-left-color. fo...
border-right - CSS: Cascading Style Sheets
ght-style: dotted; border-right: thick green; ... is actually the same as ... border-right-style: dotted; border-right: none thick green; ... and the value of border-right-style given before border-right is ignored. since the default value of border-right-style is none, not specifying the border-style part results in no border. constituent properties this property is a shorthand for the following css properties: border-right-color border-right-style border-right-width syntax border-right: 1px; border-right: 2px dotted; border-right: medium dashed green; the three values of the shorthand property can be specified in any order, and one or two of them may be omitted. values <br-width> see border-right-width. <br-style> see border-right-style. <color> see border-right-co...
border-start-end-radius - CSS: Cascading Style Sheets
rder-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-table elements when border-collapse is collapse. the behavior on internal table ele...
border-start-start-radius - CSS: Cascading Style Sheets
r-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-table elements when border-collapse is collapse. the behavior on internal table ele...
border-top-left-radius - CSS: Cascading Style Sheets
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-table elements when border-collapse is collapse. the behavior on internal table ele...
border-top-right-radius - CSS: Cascading Style Sheets
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-table elements when border-collapse is collapse. the behavior on internal table ele...
border-top - CSS: Cascading Style Sheets
... border-top-style: dotted; border-top: thick green; ... is actually the same as ... border-top-style: dotted; border-top: none thick green; ... and the value of border-top-style given before border-top is ignored. since the default value of border-top-style is none, not specifying the border-style part results in no border. constituent properties this property is a shorthand for the following css properties: border-top-color border-top-style border-top-width syntax border-top: 1px; border-top: 2px dotted; border-top: medium dashed green; the three values of the shorthand property can be specified in any order, and one or two of them may be omitted. values <br-width> see border-top-width. <br-style> see border-top-style. <color> see border-top-color. formal defi...
box-align - CSS: Cascading Style Sheets
Web › CSS › box-align
ation about the current standard. /* keyword values */ box-align: start; box-align: center; box-align: end; box-align: baseline; box-align: stretch; /* global values */ box-lines: inherit; box-lines: initial; box-lines: unset; the direction of layout depends on the element's orientation: horizontal or vertical. syntax the box-align property is specified as one of the keyword values listed below. values start the box aligns contents at the start, leaving any extra space at the end. center the box aligns contents in the center, dividing any extra space equally between the start and the end. end the box aligns contents at the end, leaving any extra space at the start. baseline the box aligns the baselines of the contents (lining up the text). this only applies if the box's orien...
box-direction - CSS: Cascading Style Sheets
rection css property specifies whether a box lays out its contents normally (from the top or left edge), or in reverse (from the bottom or right edge). /* keyword values */ box-direction: normal; box-direction: reverse; /* global values */ box-direction: inherit; box-direction: initial; box-direction: unset; syntax the box-direction property is specified as one of the keyword values listed below. values normal the box lays out its contents from the start (the left or top edge). reverse the box lays out its contents from the end (the right or bottom edge). notes the edge of the box designated the start for layout purposes depends on the box's orientation: horizontal left vertical top the edge opposite to the start is designated the end. if the di...
box-orient - CSS: Cascading Style Sheets
t standard. the box-orient css property sets whether an element lays out its contents horizontally or vertically. /* keyword values */ box-orient: horizontal; box-orient: vertical; box-orient: inline-axis; box-orient: block-axis; /* global values */ box-orient: inherit; box-orient: initial; box-orient: unset; syntax the box-orient property is specified as one of the keyword values listed below. values horizontal the box lays out its contents horizontally. vertical the box lays out its contents vertically. inline-axis (html) the box displays its children along the inline axis. block-axis (html) the box displays its children along the block axis. the inline and block axes are the writing-mode dependent keywords which, in english, map to horizontal and vertical respectively. ...
box-pack - CSS: Cascading Style Sheets
Web › CSS › box-pack
ct of this is only visible if there is extra space in the box. /* keyword values */ box-pack: start; box-pack: center; box-pack: end; box-pack: justify; /* global values */ box-pack: inherit; box-pack: initial; box-pack: unset; the direction of layout depends on the element's orientation: horizontal or vertical. syntax the box-pack property is specified as one of the keyword values listed below. values start the box packs contents at the start, leaving any extra space at the end. center the box packs contents in the center, dividing any extra space equally between the start and the end. end the box packs contents at the end, leaving any extra space at the start. justify the space is divided evenly in-between each child, with none of the extra space placed before the first chi...
column-count - CSS: Cascading Style Sheets
/* 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 boxesinheritednocomputed valueas specifiedanimation typean integer formal syntax <integer> | auto examples splitting a paragraph across three columns html <p class="content-box"> this is a bu...
column-fill - CSS: Cascading Style Sheets
ike to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax /* keyword values */ column-fill: auto; column-fill: balance; column-fill: balance-all; /* global values */ column-fill: inherit; column-fill: initial; column-fill: unset; the column-fill property is specified as one of the keyword values listed below. the initial value is balance so the content will be balanced across the columns. values auto columns are filled sequentially. content takes up only the room it needs, this may result in some columns remaining empty. balance content is equally divided between columns. in fragmented contexts, such as paged media, only the last fragment is balanced. therefore in paged media, only the last pa...
column-gap (grid-column-gap) - CSS: Cascading Style Sheets
lemented grid-column-gap and not column-gap for grid, you will need to use the prefixed property. syntax /* keyword value */ column-gap: normal; /* <length> values */ column-gap: 3px; column-gap: 2.5em; /* <percentage> value */ column-gap: 3%; /* global values */ column-gap: inherit; column-gap: initial; column-gap: unset; the column-gap property is specified as one of the values listed below. values normal the browser's default spacing is used between columns. for multi-column layout this is specified as 1em. for all other layout types it is 0. <length> the size of the gap between columns, defined as a <length>. the <length> property's value must be non-negative. <percentage> the size of the gap between columns, defined as a <percentage>. the <percentage> property's value mu...
column-rule - CSS: Cascading Style Sheets
is set to its corresponding initial value (possibly overriding values previously set using non-shorthand properties). syntax column-rule: dotted; column-rule: solid 8px; column-rule: solid blue; column-rule: thick inset blue; /* global values */ column-rule: inherit; column-rule: initial; column-rule: unset; the column-rule property is specified as one, two, or three of the values listed below, in any order. values <'column-rule-width'> is a <length> or one of the three keywords, thin, medium, or thick. see border-width for details. <'column-rule-style'> see border-style for possible values and details. <'column-rule-color'> is a <color> value. formal definition initial valueas each of the properties of the shorthand:column-rule-width: mediumcolumn-rule-style: nonecolumn-ru...
column-width - CSS: Cascading Style Sheets
exact column width. in horizontal text these are width, column-width, column-gap, and column-rule-width. syntax /* keyword value */ column-width: auto; /* <length> values */ column-width: 60px; column-width: 15.5em; column-width: 3.3vw; /* global values */ column-width: inherit; column-width: initial; column-width: unset; the column-width property is specified as 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,...
counter() - CSS: Cascading Style Sheets
Web › CSS › counter
| symbols()where <counter-style-name> = <custom-ident> examples default value compared to upper roman html <ol> <li></li> <li></li> <li></li> </ol> css ol { counter-reset: listcounter; } li { counter-increment: listcounter; } li::after { content: "[" counter(listcounter) "] == [" counter(listcounter, upper-roman) "]"; } result decimal-leading-zero compared to lower-alpha html <ol> <li></li> <li></li> <li></li> </ol> css ol { counter-reset: count; } li { counter-increment: count; } li::after { content: "[" counter(count, decimal-leading-zero) "] == [" counter(count, lower-alpha) "]"; } result specifications specification status comment css lists module level 3the definition of 'css counters' i...
<dimension> - CSS: Cascading Style Sheets
Web › CSS › dimension
unit identifiers are case insensitive. ...
<display-box> - CSS: Cascading Style Sheets
value should affect "unusual elements" — elements that aren’t rendered purely by css box concepts such as replaced elements. see appendix b: effects of display: contents on unusual elements for more details. due to a bug in browsers this will currently remove the element from the accessibility tree — screen readers will not look at what's inside. see the accessibility concerns section below for more details. none turns off the display of an element so that it has no effect on layout (the document is rendered as though the element did not exist). all descendant elements also have their display turned off. to have an element take up the space that it would normally take, but without actually rendering anything, use the visibility property instead. accessibility concerns current ...
<display-internal> - CSS: Cascading Style Sheets
able-caption these elements behave like <caption> html elements. ruby-base these elements behave like <rb> html elements. ruby-text these elements behave like <rt> html elements. ruby-base-container these elements behave like <rbc> html elements generated as anonymous boxes. ruby-text-container these elements behave like <rtc> html elements. examples css tables example the following example demonstrates laying out a simple form using css table layout. html <main> <div> <label for="name">name</label> <input type="text" id="name" name="name"> </div> <div> <label for="age">age</label> <input type="text" id="age" name="age"> </div> </main> css main { display: table; } div { display: table-row; } label, input { display: table-cell; margin:...
<display-listitem> - CSS: Cascading Style Sheets
ment with the content specified by its list-style properties (for example a bullet point) together with a principal box of the specified type for its own contents. syntax a single value of list-item will cause the element to behave like a list item. this can be used together with list-style-type and list-style-position. list-item can also be combined with any <display-outside> keyword and the flow or flow-root <display-inside> keywords. note: in browsers that support the two-value syntax, if no inner value is specified it will default to flow. if no outer value is specified, the principal box will have an outer display type of block. examples html <div class="fake-list">i will display as a list item</div> css .fake-list { display: list-item; list-style-position: inside; } re...
empty-cells - CSS: Cascading Style Sheets
t, please clone https://github.com/mdn/interactive-examples and send us a pull request. this property has an effect only when the border-collapse property is separate. syntax /* keyword values */ empty-cells: show; empty-cells: hide; /* global values */ empty-cells: inherit; empty-cells: initial; empty-cells: unset; the empty-cells property is specified as one of the keyword values listed below. values show borders and backgrounds are drawn like in normal cells. hide no borders or backgrounds are drawn. formal definition initial valueshowapplies totable-cell elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax show | hide example showing and hiding empty table cells html <table class="table_1"> <tr> <td>moe</td> <td>larry</td> </...
sepia() - CSS: Cascading Style Sheets
its result is a <filter-function>. 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 sepia(amount) parameters amount the amount of the conversion, specified as a <number> or a <percentage>. a value of 100% is completely sepia, while a value of 0% leaves the input unchanged. values between 0% and 100% are linear multipliers on the effect. the lacuna value for interpolation is 0. ...
flex-basis - CSS: Cascading Style Sheets
as the "look at my width or height property" keyword. it was implemented in bug 1032922. then, that change was reverted in bug 1093316, so auto once again means "look at my width or height property"; and a new content keyword is being introduced to trigger automatic sizing. (bug 1105111 covers adding that keyword). ...
<flex> - CSS: Cascading Style Sheets
the fr unit represents a fraction of the leftover space in the grid container. as with all css dimensions, there is no space between the unit and the number. ...
font-kerning - CSS: Cascading Style Sheets
e 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. 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 fon...
font-language-override - CSS: Cascading Style Sheets
ture would incorrectly transform a dotted "i" into a dotless "i." the font-language-override property lets you override the typeface behavior for a specific language. this is useful, for example, when the typeface you're using lacks proper support for the language. for instance, if a typeface doesn't have proper rules for the azeri language, you can force the font to use turkish glyphs, which follow similar rules. syntax the font-language-override property is specified as the keyword normal or a <string>. values normal tells the browser to use font glyphs that are appropriate for the language specified by the lang attribute. this is the default value. <string> tells the browser to use font glyphs that are appropriate for the language specified by the string. the string must match a ...
font-synthesis - CSS: Cascading Style Sheets
the font-synthesis css property controls which missing typefaces, bold or italic, may be synthesized by the browser. 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 this property can take any one of the following forms: the keyword value none. either of the keyword values weight and style. both the keyword values weight and style. values none indicates that neither bold nor italic typeface may be synthesized. weight indicates that a bold typeface may be synthesized if needed. style indicates that an italic typeface may be synthesized if needed. description most standard western fonts inclu...
font-variant-ligatures - CSS: Cascading Style Sheets
* <historical-lig-values> */ font-variant-ligatures: contextual; /* <contextual-alt-values> */ font-variant-ligatures: no-contextual; /* <contextual-alt-values> */ /* global values */ font-variant-ligatures: inherit; font-variant-ligatures: initial; font-variant-ligatures: unset; the font-variant-ligatures property is specified as one of the keyword values listed below. values normal this keyword leads to the activation of the usual ligatures and contextual forms needed for correct rendering. the ligatures and forms activated depend on the font, language and kind of script. this is the default value. none this keyword specifies that all ligatures and contextual forms are disabled, even common ones. <common-lig-values> these values control the most comm...
font-variant-position - CSS: Cascading Style Sheets
the whole set of characters of the run is rendered using a fallback method, synthesizing these glyphs. these alternate glyphs share the same em-box and the same baseline as the rest of the font. they are merely graphically enhanced, and have no effect on the line-height and other box characteristics. syntax the font-variant-position property is specified as one of the keyword values listed below. values normal deactivates alternate superscript and subscript glyphs. sub activates subscript alternate glyphs. if, in a given run, one such glyph is not available for a character, all the characters in the run are rendered using synthesized glyphs. super activates superscript alternate glyphs. if, in a given run, one such glyph is not available for a character, all the characters in th...
gap (grid-gap) - CSS: Cascading Style Sheets
Web › CSS › gap
if <'column-gap'> is omitted, it’s set to the same value as <'row-gap'>. <'row-gap'> and <'column-gap'> are each specified as a <length> or a <percentage>. values <length> is the width of the gutter separating the grid lines. <percentage> is the width of the gutter separating the grid lines, relative to the dimension of the element. formal d...
image-set() - CSS: Cascading Style Sheets
Web › CSS › image-set
ens. resolution and bandwidth differ by device and network access. the image-set() function delivers the most appropriate image resolution for a user’s device, providing a set of image options — each with an associated 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> i...
image() - CSS: Cascading Style Sheets
better to describe it semantically in the document. mdn understanding wcag, guideline 1.1 explanations understanding success criterion 1.1.1 | w3c understanding wcag 2.0 this feature can help improve accessibility by providing a fallback color when an image fails to load. while this can and should be done by including a background-color on every background image, the css image() function allows adding allows only including background colors should an image fail to load, which means you can add a fall back color should a transparent png/gif/webp not load. examples directionally-sensitive images <ul> <li dir="ltr">bullet is a right facing arrow on the left</li> <li dir="rtl">bullet is the same arrow, flipped to point left.</li> </ul> ul { list-style-image: image(ltr 'https://m...
Inheritance - CSS: Cascading Style Sheets
that property (as specified in the property's summary). a typical example of a non-inherited property is the border property. given the style rules: p { border: medium solid; } ... and the markup: <p>this paragraph has <em>emphasized text</em> in it.</p> ... the words "emphasized text" will not have a border (since the initial value of border-style is none). notes the inherit keyword allows authors to explicitly specify inheritance. it works on both inherited and non-inherited properties. you can control inheritance for all properties at once using the all shorthand property, which applies its value to all properties. for example: font { all: revert; font-size: 200%; font-weight: bold; } this reverts the style of the font property to the user agent's default unless a user ...
initial-letter-align - CSS: Cascading Style Sheets
ial-letter-align css property specifies the alignment of initial letters within a paragraph. /* keyword values */ initial-letter-align: auto; initial-letter-align: alphabetic; initial-letter-align: hanging; initial-letter-align: ideographic; /* global values */ initial-letter-align: inherit; initial-letter-align: initial; initial-letter-align: unset; syntax one of the keyword values listed below. values auto the user agent selects the value which corresponds to the language of the text. western languages would default to alphabetic, cjk languages to ideographic, and some indic languages to hanging. alphabetic as described above, the cap height of the initial letter aligns with the cap height of the first line of text. the baseline of the initial letter aligns with the baseline of ...
inline-size - CSS: Cascading Style Sheets
es. formal definition initial valueautoapplies tosame as width and heightinheritednopercentagesinline-size of containing blockcomputed valuesame as width and heightanimation typea length, percentage or calc(); formal syntax <'width'> examples setting inline size in pixels html <p class="exampletext">example text</p> css .exampletext { writing-mode: vertical-rl; background-color: yellow; inline-size: 110px; } result specifications specification status comment css logical properties and values level 1the definition of 'inline-size' in that specification. editor's draft initial definition ...
inset-block-end - CSS: Cascading Style Sheets
editor's draft initial definition ...
inset-block-start - CSS: Cascading Style Sheets
editor's draft initial definition ...
inset-inline-end - CSS: Cascading Style Sheets
editor's draft initial definition ...
inset-inline-start - CSS: Cascading Style Sheets
editor's draft initial definition ...
inset - CSS: Cascading Style Sheets
Web › CSS › inset
editor's draft initial definition...
<integer> - CSS: Cascading Style Sheets
Web › CSS › integer
mation. 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 an integer. 12. decimal points are not allowed. +---12 only one leading +/- is allowed. ten letters are not allowed. _5 special characters are not allowed. \35 escaped unicode characters are not allowed, even if they are an integer (here: 5). \4e94 non-arabic numerals are not allowed, even when escaped (here: the japanese 5, 五). 3e4 scientific notation is not allowed. specifications ...
isolation - CSS: Cascading Style Sheets
Web › CSS › isolation
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. isolate a new stacking context must be created. formal definition initial valueautoapplies toall elements. in svg, it applies to container elements, graphics elements, and graphics referencing elements.inheritednocomputed valueas specifiedanimation typediscrete formal syntax...
left - CSS: Cascading Style Sheets
Web › CSS › left
itions itself in relation to it.</p> </div> <div id="example_2"> <pre> position: relative; top: 0; right: 0; </pre> <p>relative position in relation to its siblings.</p> </div> <div id="example_3"> <pre> float: right; position: relative; top: 20px; left: 20px; </pre> <p>relative to its sibling div above, but removed from flow of content.</p> <div id="example_4"> <pre> position: absolute; bottom: 10px; right: 20px; </pre> <p>absolute position inside of a parent with relative position</p> </div> <div id="example_5"> <pre> position: absolute; right: 0; left: 0; top: 200px; </pre> <p>absolute position with both left a...
letter-spacing - CSS: Cascading Style Sheets
ub.com/mdn/interactive-examples and send us a pull request. syntax /* keyword value */ letter-spacing: normal; /* <length> values */ letter-spacing: 0.3em; letter-spacing: 3px; letter-spacing: .3px; /* global values */ letter-spacing: inherit; letter-spacing: initial; letter-spacing: unset; values normal the normal letter spacing for the current font. unlike a value of 0, this keyword allows the user agent to alter the space between characters in order to justify text. <length> specifies extra inter-character space in addition to the default space between characters. values may be negative, but there may be implementation-specific limits. user agents may not further increase or decrease the inter-character space in order to justify text. accessibility concerns a large positive ...
list-style-position - CSS: Cascading Style Sheets
ereas firefox, internet explorer, and opera place it on the next line. for more information on this, see bug 36854. syntax /* keyword values */ list-style-position: inside; list-style-position: outside; /* global values */ list-style-position: inherit; list-style-position: initial; list-style-position: unset; the list-style-position property is specified as one of the keyword values listed below. values inside the ::marker is the first element among the list item's contents. outside the ::marker is outside the principal block box. formal definition initial valueoutsideapplies tolist itemsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax inside | outside examples setting list item position html <ul class="inside">list 1 <li>list item 1-1</li> <...
margin-block-end - CSS: Cascading Style Sheets
editor's draft initial definition ...
margin-block-start - CSS: Cascading Style Sheets
editor's draft initial definition ...
margin-inline-end - CSS: Cascading Style Sheets
editor's draft initial definition ...
margin-inline-start - CSS: Cascading Style Sheets
editor's draft initial definition ...
mask-border-repeat - CSS: Cascading Style Sheets
d value */ mask-border-repeat: stretch; mask-border-repeat: repeat; mask-border-repeat: round; mask-border-repeat: space; /* vertical | horizontal */ mask-border-repeat: round stretch; /* global values */ mask-border-repeat: inherit; mask-border-repeat: initial; mask-border-repeat: unset; the mask-border-repeat property may be specified using one or two values chosen from the list of values below. when one value is specified, it applies the same behavior on all four sides. when two values are specified, the first applies to the top and bottom, the second to the left and right. values stretch the source image's edge regions are stretched to fill the gap between each border. repeat the source image's edge regions are tiled (repeated) to fill the gap between each border. tiles ma...
mask-border-source - CSS: Cascading Style Sheets
sk-border-source css property sets the source image used to create an element's mask border. the mask-border-slice property is used to divide the source image into regions, which are then dynamically applied to the final mask border. syntax /* keyword value */ mask-border-source: none; /* <image> values */ mask-border-source: url(image.jpg); mask-border-source: linear-gradient(to top, red, yellow); /* global values */ mask-border-source: inherit; mask-border-source: initial; mask-border-source: unset; values none no mask border is used. <image> image reference to use for the mask border. formal definition initial valuenoneapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednocomputed valueas specified, b...
mask-border-width - CSS: Cascading Style Sheets
orizontal */ mask-border-width: 2em 3em; /* top | horizontal | bottom */ mask-border-width: 5% 15% 10%; /* top | right | bottom | left */ mask-border-width: 5% 2em 10% auto; /* global values */ mask-border-width: inherit; mask-border-width: initial; mask-border-width: unset; the mask-border-width property may be specified using one, two, three, or four values chosen from the list of values below. when one value is specified, it applies the same width to all four sides. when two values are specified, the first width applies to the top and bottom, the second to the left and right. when three values are specified, the first width applies to the top, the second to the left and right, the third to the bottom. when four values are specified, the widths apply to the top, right, bottom, an...
mask-border - CSS: Cascading Style Sheets
the mask-border css shorthand property lets you create a mask along the edge of an element's border. constituent properties this property is a shorthand for the following css properties: mask-border-mode mask-border-outset mask-border-repeat mask-border-slice mask-border-source mask-border-width syntax /* source | slice */ mask-border: url('border-mask.png') 25; /* source | slice | repeat */ mask-border: url('border-mask.png') 25 space; /* source | slice | width */ mask-border: url('border-mask.png') 25 / 35px; /* source | slice | width | outset | repeat | mode */ mask-border: url('border-mask.png') 25 / 35px / 12px space alpha; values <'mask-border-source'> the source image. see mask-border-source. <'mask-border-slice'> the dimensions for slicing the source...
mask-clip - CSS: Cascading Style Sheets
Web › CSS › mask-clip
values content-box the painted content is clipped to the content box. padding-box the painted content is clipped to the padding box. border-box the painted content is clipped to the border box. margin-box the painted content is clipped to the margin box. fill-box the painted content is clipped to the object bounding box. stroke-box the painted content is clipp...
mask-mode - CSS: Cascading Style Sheets
Web › CSS › mask-mode
her 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 luminance values of the mask layer ima...
mask-origin - CSS: Cascading Style Sheets
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. margin-box the position is relative to the margin box. fill-box the position is rela...
mask-repeat - CSS: Cascading Style Sheets
epeated as much as possible without clipping. the first and last images are pinned to either side of the element, and whitespace is distributed evenly between the images. the mask-position property is ignored unless only one image can be displayed without clipping. the only case where clipping happens using space is when there isn't enough room to display one image. round as the allowed space increases in size, the repeated images will stretch (leaving no gaps) until there is room for another one to be added. when the next image is added, all of the current ones compress to allow room. example: an image with an original width of 260px, repeated three times, might stretch until each repetition is 300px wide, and then another image will be added. they will then compress to 225px...
mask-type - CSS: Cascading Style Sheets
Web › CSS › mask-type
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 alpha mask, i.e., that its alpha channel values must be used when applying it. formal definition initial valueluminanceapplies to<mask> elementsinheritednoc...
max-inline-size - CSS: Cascading Style Sheets
editor's draft initial definition ...
min-block-size - CSS: Cascading Style Sheets
editor's draft initial definition ...
min-inline-size - CSS: Cascading Style Sheets
editor's draft initial definition ...
min() - CSS: Cascading Style Sheets
Web › CSS › min
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. ...
mix-blend-mode - CSS: Cascading Style Sheets
l,body { height: 100%; box-sizing: border-box; background: #eee; } .grid { width: 100%; display: flex; font: 1em monospace; } .row { display: flex; flex: 1 auto; flex-direction: row; flex-wrap: wrap; height: auto; } .col { display: flex; flex: 1 auto; flex-direction: column; height: auto; } .cell { margin: .5em; padding: .5em; background-color: #fff; overflow: hidden; text-align: center; } .note { background: #fff3d4; padding: 1em; margin: .5em .5em 0; font: .8em sans-serif; text-align: left; white-space: nowrap; } .note + .row .cell { margin-top: 0; } .container { position: relative; background: linear-gradient(to right, #000 0%, transparent 50%, #fff 100%), linear-gradient(to bottom, #ff0 0%, #f0f 50%, #0ff 100%)...
object-fit - CSS: Cascading Style Sheets
ntent object within the element's box using the object-position 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. syntax the object-fit property is specified as a single keyword chosen from the list of values below. values contain the replaced content is scaled to maintain its aspect ratio while fitting within the element’s content box. the entire object is made to fill the box, while preserving its aspect ratio, so the object will be "letterboxed" if its aspect ratio does not match the aspect ratio of the box. cover the replaced content is sized to maintain its aspect ratio while filling the eleme...
offset - CSS: Cascading Style Sheets
Web › CSS › offset
the offset css shorthand property sets all the properties required for animating an element along a defined path. note: early versions of the spec called this property motion. ...
order - CSS: Cascading Style Sheets
Web › CSS › order
only meant to affect the visual order of elements and not their logical or tab order. order must not be used on non-visual media such as speech. values <integer> represents the ordinal group to be used by the item. accessibility concerns using the order property will create a disconnect between the visual presentation of content and dom order. this will adversely affect users experiencing low vision navigating with the aid of assistive technology such as a screen reader. if the visual (css) order is important, then screen reader users will not have access to the correct reading order. flexbox & the keyboard navigation disconnect — tink source order matters | adrian roselli mdn understanding wcag, guideline 1.3 explanations understanding success criterion 1.3.2 | w3c understand...
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. formal definition initial value2applies toblock container elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax <integer> examples setting a minimum orphan size of three lines html...
outline-offset - CSS: Cascading Style Sheets
t element's background. formal definition initial value0applies toall elementsinheritednocomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typea length formal syntax <length> examples setting outline offset in pixels html <p>gallia est omnis divisa in partes tres.</p> css p { outline: 1px dashed red; outline-offset: 10px; background: yellow; border: 1px solid blue; margin: 15px; } result specifications specification status comment css basic user interface module level 3the definition of 'outline-offset' in that specification. recommendation initial definition browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to...
outline-width - CSS: Cascading Style Sheets
quest. it is often more convenient to use the shorthand property outline when defining the appearance of an outline. syntax /* keyword values */ outline-width: thin; outline-width: medium; outline-width: thick; /* <length> values */ outline-width: 1px; outline-width: 0.1em; /* global values */ outline-width: inherit; the outline-width property is specified as any one of the values listed below. values <length> the width of the outline specified as a <length>. thin depends on the user agent. typically equivalent to 1px in desktop browsers (including firefox). medium depends on the user agent. typically equivalent to 3px in desktop browsers (including firefox). thick depends on the user agent. typically equivalent to 5px in desktop browsers (including firefox). formal defini...
padding-block-end - CSS: Cascading Style Sheets
e the other paddings of the element. formal definition initial value0applies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueas <length>animation typea length formal syntax <'padding-left'> examples setting block end padding for vertical text html content <div> <p class="exampletext">example text</p> </div> css content div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; padding-block-end: 20px; background-color: #c8c800; } result specifications specification status comment css logical properties and values level 1the definition of 'padding-block-end' in that specification. editor's draft initial definition ...
padding-block-start - CSS: Cascading Style Sheets
end, which define the other paddings of the element. formal definition initial value0applies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueas <length>animation typea length formal syntax <'padding-left'> examples setting block start padding for vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; padding-block-start: 20px; background-color: #c8c800; } result specifications specification status comment css logical properties and values level 1the definition of 'padding-block-start' in that specification. editor's draft initial definition ...
padding-bottom - CSS: Cascading Style Sheets
used to set paddings on all four sides of an element with a single declaration. syntax /* <length> values */ padding-bottom: 0.5em; padding-bottom: 0; padding-bottom: 2cm; /* <percentage> value */ padding-bottom: 10%; /* global values */ padding-bottom: inherit; padding-bottom: initial; padding-bottom: unset; the padding-bottom property is specified as a single value chosen from the list below. unlike margins, negative values are not allowed for padding. values <length> the size of the padding as a fixed value. must be nonnegative. <percentage> the size of the padding as a percentage, relative to the width of the containing block. must be nonnegative. formal definition initial value0applies toall elements, except table-row-group, table-header-group, table-footer-group, table-...
padding-inline-end - CSS: Cascading Style Sheets
tart, which define the other paddings of the element. formal definition initial value0applies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueas <length>animation typea length formal syntax <'padding-left'> examples setting inline end padding for vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; padding-inline-end: 20px; background-color: #c8c800; } specifications specification status comment css logical properties and values level 1the definition of 'padding-inline-end' in that specification. editor's draft initial definition ...
padding-inline-start - CSS: Cascading Style Sheets
nd, which define the other paddings of the element. formal definition initial value0applies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueas <length>animation typea length formal syntax <'padding-left'> examples setting inline start padding for vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; padding-inline-start: 20px; background-color: #c8c800; } specifications specification status comment css logical properties and values level 1the definition of 'padding-inline-start' in that specification. editor's draft initial definition ...
padding-left - CSS: Cascading Style Sheets
property can be used to set paddings on all four sides of an element with a single declaration. syntax /* <length> values */ padding-left: 0.5em; padding-left: 0; padding-left: 2cm; /* <percentage> value */ padding-left: 10%; /* global values */ padding-left: inherit; padding-left: initial; padding-left: unset; the padding-left property is specified as a single value chosen from the list below. unlike margins, negative values are not allowed for padding. values <length> the size of the padding as a fixed value. must be nonnegative. <percentage> the size of the padding as a percentage, relative to the width of the containing block. must be nonnegative. formal definition initial value0applies toall elements, except table-row-group, table-header-group, table-footer-group, table-...
padding-right - CSS: Cascading Style Sheets
can be used to set paddings on all four sides of an element with a single declaration. syntax /* <length> values */ padding-right: 0.5em; padding-right: 0; padding-right: 2cm; /* <percentage> value */ padding-right: 10%; /* global values */ padding-right: inherit; padding-right: initial; padding-right: unset; the padding-right property is specified as a single value chosen from the list below. unlike margins, negative values are not allowed for padding. values <length> the size of the padding as a fixed value. must be nonnegative. <percentage> the size of the padding as a percentage, relative to the width of the containing block. must be nonnegative. formal definition initial value0applies toall elements, except table-row-group, table-header-group, table-footer-group, table-...
padding-top - CSS: Cascading Style Sheets
padding property can be used to set paddings on all four sides of an element with a single declaration. syntax /* <length> values */ padding-top: 0.5em; padding-top: 0; padding-top: 2cm; /* <percentage> value */ padding-top: 10%; /* global values */ padding-top: inherit; padding-top: initial; padding-top: unset; the padding-top property is specified as a single value chosen from the list below. unlike margins, negative values are not allowed for padding. values <length> the size of the padding as a fixed value. must be nonnegative. <percentage> the size of the padding as a percentage, relative to the width of the containing block. must be nonnegative. formal definition initial value0applies toall elements, except table-row-group, table-header-group, table-footer-group, table-...
padding - CSS: Cascading Style Sheets
Web › CSS › padding
'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. an element's padding area is the space between its content and its border. note: padding creates extra space within an element. in contrast, margin creates extra space around an element. ...
page-break-after - CSS: Cascading Style Sheets
s like left. if pages progress right-to-left, then this acts like right. page break aliases the page-break-after property is now a legacy property, replaced by break-after. for compatibility reasons, page-break-after should be treated by browsers as an alias of break-after. this ensures that sites using page-break-after continue to work as designed. a subset of values should be aliased as follows: page-break-after break-after auto auto left left right right avoid avoid always page formal definition initial valueautoapplies toblock-level elements in the normal flow of the root element. user agents may also apply it to other elements like table-row elements.inheritednocomputed valueas specifiedanimation ty...
page-break-before - CSS: Cascading Style Sheets
ke left. if pages progress right-to-left, then this acts like right. page break aliases the page-break-before property is now a legacy property, replaced by break-before. for compatibility reasons, page-break-before should be treated by browsers as an alias of break-before. this ensures that sites using page-break-before continue to work as designed. a subset of values should be aliased as follows: page-break-before break-before auto auto left left right right avoid avoid always page formal definition initial valueautoapplies toblock-level elements in the normal flow of the root element. user agents may also apply it to other elements like table-row elements.inheritednocomputed valueas specifiedanimation ...
paint-order - CSS: Cascading Style Sheets
/ paint-order: markers; /* draw the markers first, then fill and stroke */ /* multiple values */ paint-order: stroke fill; /* draw the stroke first, then the fill, then the markers */ paint-order: markers stroke fill; /* draw markers, then stroke, then fill */ if no value is specified, the default paint order is fill, stroke, markers. when one value is specified, that one is painted first, followed by the other two in their default 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, s...
<percentage> - CSS: Cascading Style Sheets
ous properties can use percentages, such as width, height, margin, padding, and font-size. note: only calculated values can be inherited. thus, even if a percentage value is used on the parent property, a real value (such as a width in pixels for a <length> value) will be accessible on the inherited property, not the percentage value. syntax the <percentage> data type consists of a <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 tim...
perspective - CSS: Cascading Style Sheets
formable elementsinheritednocomputed valuethe absolute length or noneanimation typea lengthcreates stacking contextyes formal syntax none | <length> examples setting perspective this example shows a cube with the perspective set at different positions. how quick the cube shrinks is defined by the perspective property. the smaller its value is, the deeper the perspective is. html the html below creates four copies of the same box, with the perspective set at different values. <table> <tbody> <tr> <th><code>perspective: 250px;</code> </th> <th><code>perspective: 350px;</code> </th> </tr> <tr> <td> <div class="container"> <div class="cube pers250"> <div class="face front">1</div> <div class="face back">...
radial-gradient() - CSS: Cascading Style Sheets
t exactly meets the farthest corner of the box from its center. note: early implementations of this function included other keywords (cover and contain) as synonyms of the standard farthest-corner and closest-side, respectively. use the standard keywords only, as some implementations have already dropped those older variants. <linear-color-stop> a color-stop's <color> value, followed by an one or two optional stop positions (either a <percentage> or a <length> along the gradient's axis). a percentage of 0%, or a length of 0, represents the center of the gradient; the value 100% represents the intersection of the ending shape with the virtual gradient ray. percentage values in between are linearly positioned on the gradient ray. including two stop positions is equivalent to ...
<ratio> - CSS: Cascading Style Sheets
Web › CSS › ratio
the <ratio> css data type, used for describing aspect ratios in media queries, denotes the proportion between two unitless values. syntax in media queries level 3, the <ratio> data type consisted of a strictly positive <integer> followed by a forward slash ('/', unicode u+002f solidus) and a second strictly positive <integer>. spaces before and after the slash are 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) { ... } co...
repeating-radial-gradient() - CSS: Cascading Style Sheets
that it exactly meets the farthest corner of the box from its center. note: early implementations of this function included other keywords (cover and contain) as synonyms of the standard farthest-corner and closest-side, respectively. use the standard keywords only, as some implementations have already dropped those older variants. <color-stop> a color-stop's <color> value, followed by an optional stop position (either a <percentage> or a <length> along the gradient's axis). a percentage of 0%, or a length of 0, represents the center of the gradient; the value 100% represents the intersection of the ending shape with the virtual gradient ray. percentage values in between are linearly positioned on the virtual gradient ray. formal syntax repeating-radial-gradient( ...
Resolved value - CSS: Cascading Style Sheets
the resolved value of a css property is the value returned by getcomputedstyle(). for most properties, it is the computed value, but for a few legacy properties (including width and height), it is instead the used value. see the specification link below for more per-property details. specifications specification status comment css object model (cssom)the definition of 'resolved value' in that specification. working draft initial definition. ...
revert - CSS: Cascading Style Sheets
Web › CSS › revert
contrast, user-agent stylesheets set default values on the basis of css selectors. for example, the initial value for the display property is inline, whereas a normal user-agent stylesheet sets the default display value of <div>s to block, of <table>s to table, etc. examples revert vs unset although revert and unset are similar they differ for some properties for some elements. so in the below example, we set custom font-weight in a global stylesheet, but then try to unset and revert. unset will keep the text normal because this is an initial value for font-weight property. revert will revert to bold because this is a default value for headers in most browsers. h3 { font-weight: normal; color: blue; } <h3 style="font-weight: unset; color: unset;">this will still have font-weight:...
rotate - CSS: Cascading Style Sheets
Web › CSS › rotate
this maps better to typical user interface usage, and saves having to remember the exact order of transform functions to specify in the transform property. syntax /* keyword values */ rotate: none; /* angle value */ rotate: 90deg; rotate: 0.25turn; rotate: 1.57rad; /* x, y, or z axis name plus angle */ rotate: x 90deg; rotate: y 0.25turn; rotate: z 1.57rad; /* vector plus angle value */ rotate: 1 1 1 90deg; values angle value an <angle> specifying the angle to rotate the affected element through, around the z axis. equivalent to a rotate() (2d rotation) function. ...
scale - CSS: Cascading Style Sheets
Web › CSS › scale
this maps better to typical user interface usage, and saves having to remember the exact order of transform functions to specify in the transform value. syntax /* keyword values */ scale: none; /* single values */ /* values of more than 1 make the element grow */ scale: 2; /* values of less than 1 make the element shrink */ scale: 0.5; /* two values */ scale: 2 0.5; /* three values */ scale: 2 0.5 2; values single number value a <number> specifying a scale factor to make the affected element scale by the same factor along both the x and y axes. equivalent to a scale() (2d scaling) function with a single value specified. ...
scroll-margin-block - CSS: Cascading Style Sheets
the scroll-margin-block shorthand property sets the scroll margins of an element in the block dimension. 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. constituent properties this property is a shorthand for the following css properties: scroll-margin-block-end scroll-margin-block-start syntax /* <length> values */ scroll-margin-block: 10px; scroll-margin-block: 1em .5em ; /* global values */ scroll-margin-block: inherit; scroll-margin-block: initial; scroll-margin-block: unset; values <length> an outset from the corresponding edge of the scroll container. description the scroll-margin values rep...
scroll-padding-block-end - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. ...
scroll-padding-block-start - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. ...
scroll-padding-bottom - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. ...
scroll-padding-inline-end - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. ...
scroll-padding-inline-start - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. ...
scroll-padding-left - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. ...
scroll-padding-right - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. ...
scroll-padding-top - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. ...
scroll-snap-coordinate - CSS: Cascading Style Sheets
ate25"> <div>1</div> <div>2</div> <div>3</div> </div> </div> <div> <p>at coordinate (50, 0)</p> <div class="scrollcontainer coordinate50"> <div>1</div> <div>2</div> <div>3</div> </div> </div> </div> css #container { display: flex; } #container > div:nth-child(-n+2) { margin-right: 20px; } .scrollcontainer { width: 100px; overflow: auto; white-space: nowrap; scroll-snap-type: mandatory; font-size: 0; } .scrollcontainer > div { width: 100px; height: 100px; display: inline-block; line-height: 100px; text-align: center; font-size: 50px; } .coordinate0 > div { scroll-snap-coordinate: 0 0; } .coordinate25 > div { scroll-snap-coordinate: 25px 0; } .coordinate50 > div { scroll-snap-coordinate: 50px 0; ...
scroll-snap-destination - CSS: Cascading Style Sheets
on25"> <div>1</div> <div>2</div> <div>3</div> </div> </div> <div> <p>at coordinate (50, 0)</p> <div class="scrollcontainer destination50"> <div>1</div> <div>2</div> <div>3</div> </div> </div> </div> css #container { display: flex; } #container > div:nth-child(-n+2) { margin-right: 20px; } .scrollcontainer { width: 100px; overflow: auto; white-space: nowrap; scroll-snap-points-x: repeat(100%); scroll-snap-type: mandatory; scroll-snap-destination: 20px 0; font-size: 0; } .destination0 { scroll-snap-destination: 0 0; } .destination25 { scroll-snap-destination: 25px 0; } .destination50 { scroll-snap-destination: 50px 0; } .scrollcontainer > div { width: 100px; height: 100px; display: inline-block; ...
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. ...
<string> - CSS: Cascading Style Sheets
Web › CSS › string
lly long awesome string" specifications specification status comment css values and units module level 3the definition of '<string>' in that specification. candidate recommendation no significant change from css level 2 (revision 1). css level 2 (revision 1)the definition of '<string>' in that specification. recommendation explicit definition; allows 6-digit unicode escaped characters. css level 1the definition of '<string>' in that specification. recommendation implicit definition; allows 4-digit unicode escaped characters. ...
symbols() - CSS: Cascading Style Sheets
Web › CSS › symbols
the symbols() css function lets you define counter styles inline, directly as the value of a property such as list-style. unlike @counter-style, symbols() is anonymous (i.e., it can only be used once). although less powerful, it is shorter and easier to write than @counter-style. syntax symbols() = symbols( <symbols-type>? [ <string> | <image> ]+ ); <symbols-type> can be one of the following: cyclic: the system cycles through the given values in the order of their definition, and returns to the start when it reaches the end. numeric: the system interprets the given values as the successive units of a place-value numbering system. alphabetic: the system interprets the given values as the digits of an alphabetic numbering system, like a place-value numbering system but without 0. sym...
text-align - CSS: Cascading Style Sheets
using a <string> value only, in which case the other value defaults to right. using both a keyword value and a <string> value. values start the same as left if direction is left-to-right and right if direction is right-to-left. end the same as right if direction is left-to-ri...
text-decoration-color - CSS: Cascading Style Sheets
transparent; /* global values */ text-decoration-color: inherit; text-decoration-color: initial; 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 exp...
text-emphasis-style - CSS: Cascading Style Sheets
double-circle; text-emphasis-style: triangle; text-emphasis-style: filled sesame; text-emphasis-style: open sesame; /* global values */ text-emphasis-style: inherit; text-emphasis-style: initial; text-emphasis-style: unset; syntax values none no emphasis marks. filled the shape is filled with solid color. if neither filled nor open is present, this is the default. open the shape is hollow. dot display small circles as marks. the filled dot is '•' (u+2022), and the open dot is '◦' (u+25e6). circle display large circles as marks. the filled circle is '●' (u+25cf), and the open circle is '○' (u+25cb). double-circle display double circles as marks. the filled double-circle is '◉' (u+25c9), and the open double-circle is '◎' (u+25ce). triangle display triangles as ma...
text-indent - CSS: Cascading Style Sheets
mm; text-indent: 40px; /* <percentage> value relative to the containing block width */ text-indent: 15%; /* keyword values */ text-indent: 5em each-line; text-indent: 5em hanging; text-indent: 5em hanging each-line; /* global values */ text-indent: inherit; text-indent: initial; text-indent: unset; values <length> indentation is specified as an absolute <length>. negative values are allowed. see <length> values for possible units. <percentage> indentation is a <percentage> of the containing block's width. each-line indentation affects the first line of the block container as well as each line after a forced line break, but does not affect lines after a soft wrap break. hanging inverts which lines are indented. all lines except the first line will be indented. formal de...
text-justify - CSS: Cascading Style Sheets
the text-justify css property sets what type of justification should be applied to text when text-align: justify; is set on an element. text-justify: none; text-justify: auto; text-justify: inter-word; text-justify: inter-character; text-justify: distribute; /* deprecated value */ syntax the text-justify property is specified as a single keyword chosen from the list of values below. values none the text justification is turned off. this has the same effect as not setting text-align at all, although it is useful if you need to turn justification on and off for some reason. auto the browser chooses the best type of justification for the current situation based on a balance between performance and quality, but also on what is most appropriate for the language of the text (e.g., engli...
text-orientation - CSS: Cascading Style Sheets
mples and send us a pull request. syntax /* keyword values */ text-orientation: mixed; text-orientation: upright; text-orientation: sideways-right; text-orientation: sideways; text-orientation: use-glyph-orientation; /* global values */ text-orientation: inherit; text-orientation: initial; text-orientation: unset; the text-orientation property is specified as a single keyword from the list below. values mixed rotates the characters of horizontal scripts 90° clockwise. lays out the characters of vertical scripts naturally. default value. upright lays out the characters of horizontal scripts naturally (upright), as well as the glyphs for vertical scripts. note that this keyword causes all characters to be considered as left-to-right: the used value of direction is forced to be ltr.
text-shadow - CSS: Cascading Style Sheets
text-shadow: 5px 5px #558abb; /* color | offset-x | offset-y */ text-shadow: white 2px 5px; /* offset-x | offset-y /* use defaults for color and blur-radius */ text-shadow: 5px 10px; /* global values */ text-shadow: inherit; text-shadow: initial; text-shadow: unset; this property is specified as a comma-separated list of shadows. each shadow is specified as two or three <length> values, followed optionally by a <color> value. the first two <length> values are the <offset-x> and <offset-y> values. the third, optional, <length> value is the <blur-radius>. the<color> value is the shadow's color. when more than one shadow is given, shadows are applied front-to-back, with the first-specified shadow on top. this property applies to both ::first-line and ::first-letter pseudo-elements. val...
text-size-adjust - CSS: Cascading Style Sheets
e whole render or scale the viewport down to fit. since text that has been scaled down to fit a 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> enable...
touch-action - CSS: Cascading Style Sheets
pler 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 | understanding wcag 2.0 formal definition initial valueautoapplies toall elements except: non-replaced inline elements, table rows, row groups, table columns, and column groupsinheritednocomputed valueas specifiedanimation typedisc...
transform-box - CSS: Cascading Style Sheets
box to which the transform and transform-origin properties relate. /* keyword values */ transform-box: content-box; transform-box: border-box; transform-box: fill-box; transform-box: stroke-box; transform-box: view-box; /* global values */ transform-box: inherit; transform-box: initial; transform-box: unset; syntax the transform-box property is specified as one of the keyword values listed below. values content-box the content box is used as the reference box. the reference box of a <table> is the border box of its table wrapper box, not its table box. border-box the border box is used as the reference box. the reference box of a <table> is the border box of its table wrapper box, not its table box. fill-box the object bounding box is used as the reference box. stroke-box ...
matrix() - CSS: Cascading Style Sheets
describing the linear transformation. tx ty are <number>s describing the translation to apply. ...
scale() - CSS: Cascading Style Sheets
ℝ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 user has reduced animation specified in their system preferences. find out more: mdn understanding wcag, guideline 2.3 explanations understanding success criterion 2.3.3 | w3c understanding wcag 2.1 ...
transform-origin - CSS: Cascading Style Sheets
e box the origin of the transform is set. y-offset-keyword is one of the top, bottom, or center keyword describing how far from the top edge of the box the origin of the transform is set. z-offset is a <length> (and never a <percentage> which would make the statement invalid) describing how far from the user eye the z=0 origin is set. ...
transform-style - CSS: Cascading Style Sheets
ed valueas specifiedanimation typediscretecreates stacking contextyes formal syntax flat | preserve-3d examples transform style demonstration in this example we have a 3d cube created using transforms. the parent container of the cube faces has transform-style: preserve-3d set on it by default, so it is transformed in the 3d space and you can see it as intended. we also provide a checkbox allowing you to toggle between this, and transform-style: flat. in this alternative state, the cube faces are all flattened onto the plane of their parent, and you might not be able to see them at all, depending on the browser you are using. html <section id="example-element"> <div class="face front">1</div> <div class="face back">2</div> <div class="face right">3</div> <div class="face left"...
transform - CSS: Cascading Style Sheets
Web › CSS › transform
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 user has reduced animation specified in their system preferences. find out more: mdn understanding wcag, guideline 2.3 explanations understanding success criterion 2.3.3 | w3c understanding wcag 2.1 ...
transition - CSS: Cascading Style Sheets
ke 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. ...
translate - CSS: Cascading Style Sheets
Web › CSS › translate
this maps better to typical user interface usage, and saves having to remember the exact order of transform functions to specify in the transform value. syntax /* keyword values */ translate: none; /* single values */ translate: 100px; translate: 50%; /* two values */ translate: 100px 200px; translate: 50% 105px; /* three values */ translate: 50% 105px 5rem; values single <length-percentage> value a <length> or <percentage> that specifies a 2d translation, with the same translation along both the x and y axes. equivalent to a translate() (2d translation) function with a single value specified. ...
<url> - CSS: Cascading Style Sheets
Web › CSS › url
ge was not only awkward but, debatably, unnecessary, since urns are almost never used in actual css. to alleviate the confusion, css level 3 returned to the narrower, initial definition. now, url() denotes only true <url>s. syntax the <url> data type is specified using the url() functional notation. it may be written without quotes, or surrounded by single or double quotes. relative urls are allowed, and are relative to the url of the stylesheet (not to the url of the web page). if you choose to write the url without quotes, use a backslash (\) before any parentheses, whitespace characters, single quotes (') and double quotes (") that are part of the url. <a_css_property>: url("http://mysite.example.com/mycursor.png") <a_css_property>: url('http://mysite.example.com/mycursor.png') <a_css...
Used value - CSS: Cascading Style Sheets
ss 2.0 defined only computed value as the last step in a property's calculation. then, css 2.1 introduced the distinct definition of used value. an element could then explicitly inherit a width/height of a parent, whose computed value is a percentage. for css properties that don't depend on layout (e.g., display, font-size, or line-height), the computed values and used values are the same. ...
user-modify - CSS: Cascading Style Sheets
the content of an element can be edited by a user. /* 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. read-write-plaintext-only same as read-write, but rich text formatting will be lost. write-only the user is able to edit the content, but not to read it. formal definition value not found in db! formal syntax syntax not found in db! examples html <div class="readwr...
var() - CSS: Cascading Style Sheets
Web › CSS › var
syntax the first argument to the function is the name of the custom property to be substituted. an optional second argument to the function serves as a fallback value. if the custom property referenced by the first argument is invalid, the function uses the second value. var( <custom-property-name> , <declaration-value>? ) note: the syntax of the fallback, like that of custom properties, allows commas. for example, var(--foo, red, blue) defines a fallback of red, blue; that is, anything between the first comma and the end of the function is considered a fallback value. values <custom-property-name> a custom property’s name represented by an identifier that starts with two dashes. custom properties are solely for use by authors and users; css will never give them a meaning beyon...
width - CSS: Cascading Style Sheets
Web › CSS › width
s 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 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...
word-spacing - CSS: Cascading Style Sheets
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 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. ...
z-index - CSS: Cascading Style Sheets
Web › CSS › z-index
mples and send us a pull request. for a positioned box (that is, one with any position other than static), the z-index property specifies: the stack level of the box in the current stacking context. whether the box establishes a local stacking context. syntax /* keyword value */ z-index: auto; /* <integer> values */ z-index: 0; z-index: 3; z-index: 289; z-index: -1; /* negative values to lower the priority */ /* global values */ z-index: inherit; z-index: initial; z-index: unset; the z-index property is specified as either the keyword auto or an <integer>. values auto the box does not establish a new local stacking context. the stack level of the generated box in the current stacking context is the same as its parent's box. <integer> this <integer> is the stack level of the...
CSS: Cascading Style Sheets
Web › CSS
document written in html or xml (including xml dialects such as svg, mathml or xhtml). css describes how elements should be rendered on screen, on paper, in speech, or on other media. css among the core languages of the open web and is standardized across web browsers according to the w3c specification. previously development of various parts of css specification was done synchronously, which allowed versioning of the latest recommendation. you might have heard about css1, css2.1, css3. however, css4 has never become an official version. from css3, the scope of the specification increased significantly and the progress on different css modules started to differ so much, that it became more effective to develop and release recommendations separately per module. instead of versioning the css...
exsl:object-type() - EXSLT
tain coercsions to raise error conditions. ...
math:min() - EXSLT
Web › EXSLT › math › min
, 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. ...
Math (math) - EXSLT
Web › EXSLT › math
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes 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. 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. ...
regexp:match() - EXSLT
Web › EXSLT › regexp › match
ement has the value of the portion of the string matched by the entire regular expression. ...
regexp:test() - EXSLT
Web › EXSLT › regexp › test
s to see whether a string matches a specified regular expression. syntax regexp:test(teststring, regexpstring[, flagsstring]) parameters teststring the string to test.. regexpstring the javascript style regular expression to evaluate. flagsstringoptional an optional string containing character flags. the character flags are: g global match has no effect for this function; it's allowed for consistency with other regexp functions. i case insensitive match if this flag is specified, the match is performed in a case insensitive fashion. returns true if the specified regexp matches the test string. specifications exslt - regexp:test ...
Regular expressions (regexp) - EXSLT
Web › EXSLT › regexp
the namespace for the regular expressions package is http://exslt.org/regular-expressions. ...
set:trailing() - EXSLT
Web › EXSLT › set › trailing
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes set:trailing() returns the nodes in one node-set that come after the first node in the other node-set. syntax set:trailing(nodeset1, nodeset2) parameters nodeset1 the node set to find nodes in that follow the first node in the second node set. nodeset2 the node set to compare against. returns a node-set containing the nodes from nodeset1 whose values follow the first node in nodeset2. note: if the first node in nodeset2 isn't contained in nodeset1, an empty set is returned. if nodeset2 is empty, then the result is nodeset1. specifications exslt - set:trailing ...
Strings (str) - EXSLT
Web › EXSLT › str
the namespace for the strings package is http://exslt.org/strings. ...
Ajax - Developer guides
Web › Guide › AJAX
file objects may be obtained from a filelist object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's datatransfer object, or from the mozgetasfile() api on an htmlcanvaselement. html in xmlhttprequest the xmlhttprequest specification adds html parsing support to xmlhttprequest, which originally supported only xml parsing. this feature allows web apps to obtain an html resource as a parsed dom using xmlhttprequest. view all... tools axios promise based http client, which uses xmlhttprequest internally. see also ajax: a new approach to web applications jesse james garrett, of adaptive path, wrote this article in february 2005, introducing ajax and its related concepts. xmlhttprequest specification whatwg living standa...
Writing Web Audio API code that works in every browser - Developer guides
code samples. things that are not ready yet second, ensure that your project doesn't use node types that are not implemented yet in firefox: mediastreamaudiosourcenode, mediaelementaudiosourcenode and oscillatornode. if it's using, for example, oscillatornode, you will have to wait until it is supported, or maybe, if you're really eager, hack in some replacement using scriptprocessornode, which allows you to write a node with callbacks that get called periodically, so that your javascript code generates or processes audio. the node parameters you use must also be supported 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 day...
Media events - Developer guides
y 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). waiting sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek). you can easily watch for these events, using code such as the following: var v = document.getelementsbytagname("video")[0]; v.addeventlistener("seeked", function() { v.play(); }, true); v.currenttime = 10.0; this example fetches the first video element in the document and attaches an event listener to it, watching for the seeked event, which is sent whenever a seek operation completes. the listener simply calls the element's play() method, which starts playbac...
Mouse gesture events - Developer guides
ch 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_counterclockwise counter-clockwise rotation. simplegestureevent.rotation_clockwise clockwise rotation. ...
Touch events (Mozilla experimental) - Developer guides
/ thunderbird 18.0 / seamonkey 2.15), when support for the standard touch events was implemented. the experimental touch events api described on this page was available from gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) to gecko/firefox 17. you should instead use the standard touch events api, supported since gecko/firefox 6 with multi-touch support added in gecko/firefox 12. this api allowed you to track the movement of the user's finger on a touch screen, monitoring the raw touch events generated by the system. although touch events were based on — and work similarly to — mouse events, each event included an identifier that allowed you to track multiple fingers moving on the screen at the same time. event fields touch events were based upon mouseevent, and thereby shared all m...
Using device orientation with 3D transforms - Developer guides
3d"); window.addeventlistener("deviceorientation", function(e) { // again, use vendor-prefixed transform property elem.style.transform = "rotatey(" + ( -e.gamma ) + "deg)" + "rotatex(" + e.beta + "deg) " + "rotatez(" + - ( e.alpha - 180 ) + "deg) "; }); rotate3d to orientation should you ever need to convert a rotate3d axis-angle to orientation euler angles, you can use the following algorithm: // convert a rotate3d axis-angle to deviceorientation angles function orient( aa ) { var x = aa.x, y = aa.y, z = aa.z, a = aa.a, c = math.cos( aa.a ), s = math.sin( aa.a ), t = 1 - c, // axis-angle to rotation matrix rm00 = c + x*x * t, rm10 = z*s + y*x * t, rm20 = -y*s + z*x * t, rm01 = -z*s + x*y * t, ...
Introduction to Web development - Developer guides
or beginners. google's html, css, and javascript from the ground up these easily digestible video tutorials from google's expert web developers cover the basics of html, css and javascript. csstutorial.net beginner tutorials a broad range of useful text and video tutorials that cover the basics through to intermediate aspects of css. tizag css tutorials an easy-to-follow reference for those wishing to learn css through short, concise tutorials. jquery fundamentals an open-source reference book featuring detailed introductions to both javascript and jquery for beginners. javascript from null: a video series a video series on javascript for absolute beginners looking for more 'visual'-based learning ...
Mobile Web Development - Developer guides
Web › Guide › Mobile
k with dom touch events. you won't be able to use the css :hover pseudo-class, and will need to design clickable items like buttons to respect the fact that fingers are fatter than mouse pointers. see this article on designing for touch screens. you can use the pointer or any-pointer media query to load different css on a touch-enabled device. optimizing images to help users whose devices have low or expensive bandwidth, you can optimize images by loading images appropriate to the device screen size and resolution. you do this in css by querying for screen height, width, and pixel ratio. you can also make use of css properties to implement visual effects like gradients and shadows without images. mobile apis finally, you can take advantage of the new possibilities offered by mobile devi...
Optimization and performance - Developer guides
when building modern web apps and sites, it's important to make your content perform well. that is, to make it work quickly and efficiently. this lets it work effectively both for users of powerful desktop systems as well as for handheld devices with less power. there are several tools available to check the performance of a website or blog. the most notable tools are listed below. google pagespeed insights lighthouse webpagetest browser developer tools the above resources also include web performance best practices. making web performance a priority by considering web performance throughout the development process is important in ensuring users get the best user experience possible. there are no subpages at this time. ...
The Web Open Font Format (WOFF) - Developer guides
Web › Guide › WOFF
woff (the web open font format) is a web font format developed by mozilla in concert with type supply, letterror, and other organizations. it uses a compressed version of the same table-based sfnt structure used by truetype, opentype, and open font format, but adds metadata and private-use data structures, including predefined fields allowing foundries and vendors to provide license information if desired. there are three main benefits to using woff: the font data is compressed, so sites using woff will use less bandwidth and will load faster than if they used equivalent uncompressed truetype or opentype files. 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 fo...
Developer guides
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 need to present graphics of varying sophistication. guide to web apis a list of all web apis and what they do. javascript javascript is the po...
HTML attribute: capture - HTML: Hypertext Markup Language
environment the outward-facing camera and/or microphone should be used note: capture was previously a boolean attribute which, if present, requested that the device's media capture device(s) such as camera or microphone be used instead of requesting a file input. examples when set on a file input type, operating systems with microphones and cameras will display a user interface allowing the selection from an existing file or the creating of a new one. <p> <label for="soundfile">what does your voice sound like?:</label> <input type="file" id="soundfile" capture="user" accept="audio/*"> </p> <p> <label for="videofile">upload a video:</label> <input type="file" id="videofile" capture="environment" accept="video/*"> </p> <p> <label for="imagefile">upload a photo of your...
HTML attribute: maxlength - HTML: Hypertext Markup Language
n 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-only toolong property of a validitystate object will be true. examples <input type="password" maxlength="4"/> specifications specification status html living standardthe definition of 'maxlength attribute' in that specification. living standard html 5.1the definition of 'maxlength attribu...
HTML attribute: size - HTML: Hypertext Markup Language
Web › HTML › Attributes › size
living standard html 5.1the definition of 'size attribute' in that specification. recommendation ...
<acronym> - HTML: Hypertext Markup Language
Web › HTML › Element › acronym
usage note: this element has been removed in html5 and shouldn't be used anymore. instead web developers should use the <abbr> element. attributes this element only has global attributes, which are common to all elements. dom interface this element implements the htmlelement interface. implementation note: up to gecko 1.9.2 inclusive, firefox implements the htmlspanelement interface for this element. ...
<article>: The Article Contents element - HTML: Hypertext Markup Language
Web › HTML › Element › article
interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. a given document can have multiple articles in it; for example, on a blog that shows the text of each article one after another as the reader scrolls, each post would be contained in an <article> element, possibly with one or more <section>s within. content categories flow content, sectioning content, palpable content permitted content flow content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. note that an <article> element must not be a descendant of an <address> element. implicit aria role article permitted aria roles applicat...
<b>: The Bring Attention To element - HTML: Hypertext Markup Language
Web › HTML › Element › b
ou should use the css font-weight property to create boldface text, or the <strong> element to indicate that text is of special importance. 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. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this el...
<bdi>: The Bidirectional Isolate element - HTML: Hypertext Markup Language
Web › HTML › Element › bdi
cause embedded-text is being read from a database or entered by the user - you should use <bdi> to prevent the directionality of embedded-text from affecting its surroundings. though the same visual effect can be achieved using the css rule unicode-bidi: isolate on a <span> or another text-formatting element, html authors should not use this approach because it is not semantic and browsers are allowed to ignore css styling. embedding the characters in <span dir="auto"> has the same effect as using <bdi>, but its semantics are less clear. content categories flow content, phrasing content, palpable content. permitted content phrasing content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that a...
<bdo>: The Bidirectional Text Override element - HTML: Hypertext Markup Language
Web › HTML › Element › bdo
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. the text's characters are drawn from the starting point in the given direction; the individual characters' orientation is not affected (so characters don't get drawn backward, for example). content categories flow content, phrasing content, palpable content. permitted content phrasing content. tag omission 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 any dom interface htmlelement up to gecko 1.9.2 (firefox...
<bgsound>: The Background Sound element (obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › bgsound
udio> 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. loop this attribute indicates the number of times a sound is to be played and either has a numeric value or the keyword infinite. src this attribute specifies the url of the sound file to be played, which must be one of the following types: .wav, .au, or .mid. volume this attribute defines a number between -10,000 and 0 that determines the loudness of a page's background sound. 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. however, even this is no l...
<big>: The Bigger Text element - HTML: Hypertext Markup Language
Web › HTML › Element › big
er's maximum permitted font size. usage note: as it was purely presentational, this element has been removed in html5 and shouldn't be used anymore. instead web developers should use the css font-size property to adjust the font size. attributes this element has no other attributes than the global attributes, common to all elements. examples here we see examples showing the use of <big> followed by an example showing how to accomplish the same results using modern css syntax instead. using <big> this example uses the obsolete <big> element to increase the size of some text. html <p> this is the first sentence. <big>this whole sentence is in bigger letters.</big> </p> result using css font-size this example uses the css font-size property to increase the font size by one ...
<blink>: The Blinking Text element (obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › blink
the html blink element (<blink>) is a non-standard element which causes the enclosed text to flash slowly. do not use this element as it is obsolete and is bad design practice. blinking text is frowned upon by several accessibility standards and the css specification allows browsers to ignore the <blink> element. dom interface this element is unsupported and thus implements the htmlunknownelement interface. example <blink>why would somebody use this?</blink> result (toned down!) specification this element is non-standard and not part of any specification. if you don't believe us, see for yourself in the html spec. css polyfill if you really do need a polyfill, then you can use the following css polyfill. works in ie10+. blink { -webkit-animation: 2s linear infinite...
<code>: The Inline Code element - HTML: Hypertext Markup Language
Web › HTML › Element › code
hat the text is a short fragment of computer code. by default, the content text is displayed using the user agent's default monospace font. 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. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement up to gecko 1.9.2 (firefox...
<command>: The HTML Command element - HTML: Hypertext Markup Language
Web › HTML › Element › command
ands are often used as part of a context menu or toolbar. however, they can be used anywhere on the page. the <command> element is included in the w3c specification, but not in the whatwg specification, and browser support is nonexistent. you should use the <menuitem> element instead, although that element is non-standard and only supported in edge and firefox. content categories flow content, phrasing content, metadata content. permitted content none, it is an empty element. tag omission the start tag is mandatory, but, as it is a void element, the use of an end tag is forbidden. permitted parent elements <colgroup> only, though it can be implicitly defined as its start tag is not mandatory. the <colgroup> must not have a <span> as child. ...
<datalist>: The HTML Data List element - HTML: Hypertext Markup Language
Web › HTML › Element › datalist
contains a set of <option> elements that represent the permissible or recommended options available to choose from within other controls. 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. permitted content either phrasing content or zero or more <option> elements. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. implicit aria role listbox permitted aria roles no role permitted dom interface htmldatalistele...
<dd>: The Description Details element - HTML: Hypertext Markup Language
Web › HTML › Element › dd
ides the description, definition, or value for the preceding term (<dt>) in a description list (<dl>). 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 none. permitted content flow content. tag omission the start tag is required. the end tag may be omitted if the <dd> element is immediately followed by another <dd> element or a <dt> element, or if there is no more content in the parent element. permitted parents <dl> or (in whatwg html) a <div> that is inside a <dl>. previous sibling <dt> or another <dd> element. implicit aria ro...
<dialog>: The Dialog element - HTML: Hypertext Markup Language
Web › HTML › Element › dialog
the html <dialog> element represents a dialog box or other interactive component, such as a dismissable alert, inspector, or subwindow. content categories flow content, sectioning root permitted content flow content tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content implicit aria role dialog permitted aria roles alertdialog dom interface htmldialogelement attributes this element includes the global attributes. the tabindex attribute must not be used on the <dialog> element. open indicates that the dialog is active and can be interacted with. when the open attribute is not set, the dialog shouldn't be shown to the user. u...
<figcaption>: The Figure Caption element - HTML: Hypertext Markup Language
ment represents a caption or legend describing the rest of the contents of its parent <figure> 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. content categories none. permitted content flow content. tag omission none, both the starting and ending tag are mandatory. permitted parents a <figure> element; the <figcaption> element must be its first or last child. implicit aria role no corresponding role permitted aria roles group, none, presentation dom interface htmlelement attributes this element only includes the glo...
<footer> - HTML: Hypertext Markup Language
Web › HTML › Element › footer
oning root element. a footer typically contains information about the author of the section, copyright data or links to related documents. 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, palpable content. permitted content flow content, but with no <footer> or <header> descendants. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. note that a <footer> element must not be a descendant of an <address>, <header> or another <footer> element. implicit aria ro...
<frame> - HTML: Hypertext Markup Language
Web › HTML › Element › frame
attribute is not used, the browser adds a scrollbar when necessary. there are two choices: "yes" for forcing a scrollbar even when it is not necessary and "no" for forcing no scrollbar even when it is necessary. marginheight this attribute defines the height of the margin between frames. marginwidth this attribute defines the width of the margin between frames. frameborder this attribute allows you to specify a frame’s border. example <frameset cols="50%,50%"> <frame src="https://udn.realityripple.com/docs/web/html/element/iframe" /> <frame src="https://udn.realityripple.com/docs/web/html/element/frame" /> </frameset> ...
<head>: The Document Metadata (Header) element - HTML: Hypertext Markup Language
Web › HTML › Element › head
rmation is available from a higher level protocol (like the subject line in html email), zero or more elements of metadata content. otherwise, one or more elements of metadata content where exactly one is a <title> element. tag omission the start tag may be omitted if the first thing inside the <head> element is an element. the end tag may be omitted if the first thing following the <head> element is not a space character or a comment. permitted parents an <html> element, as its first child. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlheadelement attributes this element includes the global attributes. profile the uris of one or more metadata profiles, se...
<hr>: The Thematic Break (Horizontal Rule) element - HTML: Hypertext Markup Language
Web › HTML › Element › hr
thub.com/mdn/interactive-examples and send us a pull request. historically, this has been presented as a horizontal rule or line. while it may still be displayed as a horizontal rule in visual browsers, this element is now defined in semantic terms, rather than presentational terms, so if you wish to draw a horizontal line, you should do so using appropriate css. content categories flow content. permitted content none, it is an empty element. tag omission it must have start tag, but must not have an end tag. permitted parents any element that accepts flow content. implicit aria role separator permitted aria roles presentation or none dom interface htmlhrelement attributes this element's attributes in...
<html>: The HTML Document / Root element - HTML: Hypertext Markup Language
Web › HTML › Element › 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. content categories none. permitted content one <head> element, followed by one <body> element. tag omission the start tag may be omitted if the first thing inside the <html> element is not a comment. the end tag may be omitted if the <html> element is not immediately followed by a comment. permitted parents none. this is the root element of a document. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlhtmlelement attributes this element includes the global attribut...
<i>: The Idiomatic Text element - HTML: Hypertext Markup Language
Web › HTML › Element › i
mong others. historically, these have been presented using italicized type, which is the original source of the <i> naming of this 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. content categories flow content, phrasing content, palpable content. permitted content phrasing content. tag omission 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 any dom interface htmlelement attributes this el...
<isindex> - HTML: Hypertext Markup Language
Web › HTML › Element › isindex
utes 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 different anchor type instead of isindex. on november 1992, indexes as links rather than documents started by dan connolly who is pushing the idea that indexes are more links than documents. in this thread, different t...
<label> - HTML: Hypertext Markup Language
Web › HTML › Element › label
ur-name"> your name <input id="your-name" name="your-name" type="text"> </label> buttons an <input> element with a type="button" declaration and a valid value attribute does not need a label associated with it. doing so may actually interfere with how assistive technology parses the button input. the same applies for the <button> element. technical summary content categories flow content, phrasing content, interactive content, form-associated element, palpable content. permitted content phrasing content, but no descendant label elements. no labelable elements other than the labeled control are allowed. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. ...
<marquee>: The Marquee element (Obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › marquee
h means the marquee will scroll continuously. scrollamount sets the amount of scrolling at each interval in pixels. the default value is 6. scrolldelay sets the interval between each scroll movement in milliseconds. the default value is 85. note that any value smaller than 60 is ignored and the value 60 is used instead, unless truespeed is specified. truespeed by default, scrolldelay values lower than 60 are ignored. if truespeed is present, those values are not ignored. vspace sets the vertical margin in pixels or percentage value. width sets the width in pixels or percentage value. event handlers onbounce fires when the marquee has reached the end of its scroll position. it can only fire when the behavior attribute is set to alternate. onfinish fires when the marquee has f...
theme-color - HTML: Hypertext Markup Language
Web › HTML › Element › meta › name › theme-color
the theme-color value for the name attribute of the <meta> element indicates a suggested color that user agents should use to customize the display of the page or of the surrounding user interface. if specified, the content attribute must contain a valid css <color>. example <meta name="theme-color" content="#4285f4"> the following image shows the effect that the <meta> element above will have on a document displayed in chrome running on an android mobile device. image credit: from icons & browser colors, created and shared by google and used according to terms described in the creative commons 4.0 attribution license. specifications specification html living standardthe definition of 'theme-color' in that specification. ...
<multicol>: The HTML Multi-Column Layout element (Obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › multicol
it never got any significant traction and is not implemented in any major browsers. it's covered here only to warn you off in case you stumble on it in any other documentation. ...
<nav>: The Navigation Section element - HTML: Hypertext Markup Language
Web › HTML › Element › nav
ther within the current document or to other documents. common examples of navigation sections are menus, tables of contents, and indexes. 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, sectioning content, palpable content. permitted content flow content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. implicit aria role navigation permitted aria roles no role permitted dom interface htmlelement attributes this eleme...
<nextid>: The NeXT ID element (Obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › nextid
rm that simply used the numeric value alone as an "attribute." html "0.d" - from november 26, 1992 through may 24, 1993 during this span, next and the oldest surviving dtd's show <nextid> to take only a number for a value of its newly-introduced attribute n. html "1.k" - version 1 (first release) in this first published draft of html, <nextid> is the same as it would take in html 2, finally allowing the use of a name instead of only a number for its attribute value. html "1.m" - version 1 (second release) in the next published draft of html, <nextid> <nextid> can be individually deselected for display with a simple sgml command. html version 2 level 1 this is like the level 2 default but it excludes all the forms elements, i. e. <form>, <input>, <textarea>, <select>, and <option> htm...
<noembed>: The Embed Fallback element (Obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › noembed
object> element. ...
<noscript> - HTML: Hypertext Markup Language
Web › HTML › Element › noscript
the html <noscript> element defines a section of html to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser. content categories metadata content, flow content, phrasing content. permitted content when scripting is disabled and when it is a descendant of the <head> element: in any order, zero or more <link> elements, zero or more <style> elements, and zero or more <meta> elements. when scripting is disabled and when it isn't a descendant of the <head> element: any transparent content, but no <noscript> element must be among its descendants. otherwise: flow content or phrasing content. tag omission none, both the starting and ending tag are mandatory. permitted parents any eleme...
<optgroup> - HTML: Hypertext Markup Language
Web › HTML › Element › optgroup
ple 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 none. permitted content zero or more <option> elements. tag omission the start tag is mandatory. the end tag is optional if this element is immediately followed by another <optgroup> element, or if the parent element has no more content. permitted parents a <select> element. implicit aria role group permitted aria roles no role permitted dom interface htmloptgroupelement note: optgroup elements may not be nested. attributes this element includes the global attributes. disabled if this boolean...
<option>: The HTML Option element - HTML: Hypertext Markup Language
Web › HTML › Element › option
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. content categories none. permitted content text, possibly with escaped characters (like &eacute;). tag omission the start tag is mandatory. the end tag is optional if this element is immediately followed by another <option> element or an <optgroup>, or if the parent element has no more content. permitted parents a <select>, an <optgroup> or a <datalist> element. implicit aria role option permitted aria roles no role permitted dom interface htmloptionelement attributes this element includes the global attributes. disabled if this boolea...
<param>: The Object Parameter element - HTML: Hypertext Markup Language
Web › HTML › Element › param
the html <param> element defines parameters for an <object> element. content categories none. permitted content none, it is an empty element. tag omission as it is a void element, the start tag must be present and the end tag must not be present. permitted parents an <object> before any flow content. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlparamelement attributes this element includes the global attributes. name name of the parameter. value specifies the value of the parameter. deprecated attributes type only used if the valuetype is set to ref. specifies the mime type of values found at the uri specified by value. value...
<plaintext>: The Plain Text element (Deprecated) - HTML: Hypertext Markup Language
there is no closing tag, since everything after it is considered raw text. note: do not use this element. <plaintext> is deprecated since html 2, and not all browsers implemented it. browsers that did implement it didn't do so consistently. <plaintext> is obsolete in html5; browsers that accept it may instead treat it as a <pre> element that still interprets html within. if <plaintext> is the first element on the page (other than any non-displayed elements, like <head>), do not use html at all. instead serve a text file with the text/plain mime-type. ...
<q>: The Inline Quotation element - HTML: Hypertext Markup Language
Web › HTML › Element › q
marks. this element is intended for short quotations that don't require paragraph breaks; for long quotations use the <blockquote> 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. content categories flow content, phrasing content, palpable content. permitted content phrasing content. tag omission 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 any dom interface htmlquoteelement usage note: m...
<rb>: The Ruby Base element - HTML: Hypertext Markup Language
Web › HTML › Element › rb
e 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 none. permitted content as a child of a <ruby> element. tag omission the end tag can be omitted if the element is immediately followed by an <rt>, <rtc>, or <rp> element or another <rb> element, or if there is no more content in the parent element. permitted parents a <ruby> element. permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes. usage notes ruby annotations are for showing pronunciation of east asian characters, li...
<rp>: The Ruby Fallback Parenthesis element - HTML: Hypertext Markup Language
Web › HTML › Element › rp
tation's 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. content categories none. permitted content text tag omission the end tag can be omitted if the element is immediately followed by an <rt> or another <rp> element, or if there is no more content in the parent element. permitted parents a <ruby> element. <rp> must be positioned immediately before or after an <rt> element. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this element only includes the global attri...
<rt>: The Ruby Text element - HTML: Hypertext Markup Language
Web › HTML › Element › rt
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. see the article about the <ruby> element for more examples. content categories none. permitted content phrasing content. tag omission the end tag may be omitted if the <rt> element is immediately followed by an <rt> or <rp> element, or if there is no more content in the parent element permitted parents a <ruby> element. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes. examples this simple example provides romaji transliteration for the ...
<rtc>: The Ruby Text Container element - HTML: Hypertext Markup Language
Web › HTML › Element › rtc
rce 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 none. permitted content phrasing content or <rt> elements. tag omission the closing tag can be omitted if it is immediately followed by a <rb>, <rtc> or <rt> element opening tag or by its parent closing tag. permitted parents a <ruby> element. permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes. examples <div class="info"> <ruby> <rbc> <rb>旧</rb><rt>jiù</rt> <rb>金</rb><rt>jīn</rt> <rb>山</rb...
<ruby> - HTML: Hypertext Markup Language
Web › HTML › Element › ruby
the html <ruby> element represents a ruby annotation. ruby annotations are for showing pronunciation of east asian characters. 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. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this element only i...
<section>: The Generic Section element - HTML: Hypertext Markup Language
Web › HTML › Element › section
nd send us a pull request. as an example, a navigation menu should be wrapped in a <nav> element, but a list of search results and a map display and its controls don't have specific elements, and could be put inside a <section>. note: if the contents of the element would make sense syndicated as a standalone piece, the <article> element may be a better choice. content categories flow content, sectioning content, palpable content. permitted content flow content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. note that a <section> element must not be a descendant of an <address> element. implicit aria role region if the element has an accessible name, oth...
<slot> - HTML: Hypertext Markup Language
Web › HTML › Element › slot
the html <slot> element—part of the web components technology suite—is a placeholder inside a web component that you can fill with your own markup, which lets you create separate dom trees and present them together. content categories flow content, phrasing content permitted content transparent events slotchange tag omission 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 htmlslotelement attributes this element includes the global attributes. name the slot's name. a named slot is a <slot> element with a name attribute. e...
<small>: the side comment element - HTML: Hypertext Markup Language
Web › HTML › Element › small
text, independent of its styled presentation. by default, it renders text within it one font-size smaller, such as from small to x-small. 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 permitted content phrasing content tag omission none, must have both a start tag and an end tag. permitted parents any element that accepts phrasing content, or any element that accepts flow content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement at...
<spacer> - HTML: Hypertext Markup Language
Web › HTML › Element › spacer
it was devised by netscape to accomplish the same effect as a single-pixel layout image, which was something web designers used to use to add white spaces to web pages without actually using an image. however, <spacer> no longer supported by any major browser and the same effects can now be achieved using simple css. 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. ...
<span> - HTML: Hypertext Markup Language
Web › HTML › Element › span
element is appropriate. <span> is very much like a <div> element, but <div> is a block-level element whereas a <span> is an inline 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. content categories flow content, phrasing content. permitted content phrasing content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content, or any element that accepts flow content. implicit aria role no corresponding role permitted aria roles any dom interface htmlspanelemen...
<strong>: The Strong Importance element - HTML: Hypertext Markup Language
Web › HTML › Element › strong
<strong>) indicates that its contents have strong importance, seriousness, or urgency. browsers typically render the contents in bold 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. content categories flow content, phrasing content, palpable content. permitted content phrasing content. tag omission none, must have both a start tag and an end tag. permitted parents any element that accepts phrasing content, or any element that accepts flow content. implicit aria role no corresponding role permitted aria roles any dom interface h...
<summary>: The Disclosure Summary element - HTML: Hypertext Markup Language
Web › HTML › Element › summary
includes display: list-item. this makes it possible to change or remove the icon displayed as the disclosure widget next to the label from the default, which is typically a triangle. you can also change the style to display: block to remove the disclosure triangle. see the browser compatibility section for details, as not all browsers support full functionality of this element yet. examples below are some examples showing <summary> in use. you can find more examples in the documentation for the <details> element. basic example a simple example showing the use of <summary> in a <details> element: <details open> <summary>overview</summary> <ol> <li>cash on hand: $500.00</li> <li>current invoice: $75.30</li> <li>due date: 5/6/19</li> </ol> </details> summaries as head...
<tbody>: The Table Body element - HTML: Hypertext Markup Language
Web › HTML › Element › tbody
splay the entire table, the user agent may let the user scroll the contents of the <thead>, <tbody>, <tfoot>, and <caption> blocks separately from one another for the same parent table. you may use more than one <tbody> per table as long as they are all consecutive. this lets you divide the rows in large tables into sections, each of which may be separately formatted if so desired. examples below are some examples showing the use of the <tbody> element. for more examples of this tag in use, see the examples for <table>. basic example in this relatively simple example, we create a table listing information about a group of students with a <thead> and a <tbody>, with a number of rows in the body. html the table's html is shown here. note that all of the body cells including information ...
<tfoot>: The Table Foot element - HTML: Hypertext Markup Language
Web › HTML › Element › tfoot
of each cell of the column. it is one of the 6-digit hexadecimal code as defined in srgb, prefixed by a '#'. ...
<track>: The Embed Text Track element - HTML: Hypertext Markup Language
Web › HTML › Element › track
ack should be enabled unless the user's preferences indicate that another track is more appropriate. this may only be used on one track element per media element. kind how the text track is meant to be used. if omitted the default kind is subtitles. if the attribute contains an invalid value, it will use metadata (versions of chrome earlier than 52 treated an invalid value as subtitles). the following keywords are allowed: subtitles subtitles provide translation of content that cannot be understood by the viewer. for example dialogue or text that is not english in an english language film. subtitles may contain additional content, usually extra background information. for example the text at the beginning of the star wars films, or the date, time, and location of a scene. ...
<ul>: The Unordered List element - HTML: Hypertext Markup Language
Web › HTML › Element › ul
the html <ul> element represents an unordered list of items, typically rendered as a bulleted list. 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, and if the <ul> element's children include at least one <li> element, palpable content. permitted content zero or more <li>, <script> and <template> elements. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts flow content. implicit aria role list permitted aria roles directory, group, listbox, menu, menubar...
<wbr> - HTML: Hypertext Markup Language
Web › HTML › Element › wbr
in text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location. 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. permitted content empty tag omission it is an empty element; it must have a start tag, but must not have an end tag. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this elemen...
<xmp> - HTML: Hypertext Markup Language
Web › HTML › Element › xmp
note: do not use this element. it has been deprecated since html3.2 and was not implemented in a consistent way. it was completely removed from the language in html5. use the <pre> element or, if semantically adequate, the <code> element instead. ...
autocapitalize - HTML: Hypertext Markup Language
the autocapitalize global attribute is an enumerated attribute that controls whether and how text input is automatically capitalized as it is entered/edited by the user. the attribute must take one of the following values: off or none: no autocapitalization is applied (all letters default to lowercase) on or sentences: the first letter of each sentence defaults to a capital letter; all other letters default to lowercase words: the first letter of each word defaults to a capital letter; all other letters default to lowercase characters: all letters should default to uppercase the autocapitalize attribute doesn’t affect behavior when typing on a physical keyboard. instead, it affects the behavior of other input mechanisms, such as virtual keyboards on mobile devices and voice input. ...
class - 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. ...
draggable - HTML: Hypertext Markup Language
false: the element cannot be dragged. this attribute is enumerated and not boolean. a value of true or false is mandatory, and shorthand like <img draggable> is forbidden. the correct usage is <img draggable="false">. ...
dropzone - HTML: Hypertext Markup Language
move, which indicates that the element that was dragged will be moved to this new location. link, which will create a link to the dragged data. ...
id - HTML: Hypertext Markup Language
ld 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 with a letter for compatibility. specifications specification status comment html living stan...
inputmode - HTML: Hypertext Markup Language
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. ...
itemid - HTML: Hypertext Markup Language
supports global identifiers. the exact meaning of an itemtype's global identifier is provided by the definition of that identifier within the specified vocabulary. the vocabulary defines whether several items with the same global identifier can coexist and, if so, how items with the same identifier are handled. note: the whatwg definition specifies that an itemid must be a url. however, the following example correctly illustrates that a urn may also be used. this inconsistency may reflect the incomplete nature of the microdata specification. example html <dl itemscope itemtype="http://vocab.example.net/book" itemid="urn:isbn:0-330-34032-8"> <dt>title <dd itemprop="title">the reality dysfunction <dt>author <dd itemprop="author">peter f. hamilton <dt>publication date <dd><time ite...
itemref - HTML: Hypertext Markup Language
emref provides a list of element ids (not itemids) elsewhere in the document, with additional properties the itemref attribute can only be specified on elements that have an itemscope attribute specified. note: the itemref attribute is not part of the microdata data model. it is merely a syntactic construct to aid authors in adding annotations to pages where the data to be annotated does not follow a convenient tree structure. for example, it allows authors to mark up data in a table so that each column defines a separate item while keeping the properties in the cells. example html <div itemscope id="amanda" itemref="a b"></div> <p id="a">name: <span itemprop="name">amanda</span> </p> <div id="b" itemprop="band" itemscope itemref="c"></div> <div id="c"> <p>band: <span itemprop="name"...
itemtype - HTML: Hypertext Markup Language
temscope 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"> <span itemprop="brand">acme</span> <span itemprop="name">executive anvil</span> </div> structured data itemscope itemtype schema.org product itemprop name ...
lang - HTML: Hypertext Markup Language
tag syntax the full bcp47 syntax is in-depth enough to mark extremely specific language dialects, but most usage is much simpler. a language tag is made of hyphen-separated language subtags, where each subtag indicates a certain property of the language. the 3 most common subtags are: language subtag required. a 2-or-3-character code that defines the basic language, typically written in all lowercase. for example, the language code for english is en, and the code for badeshi is bdz. script subtag optional. this subtag defines the writing system used for the language, and is always 4 characters long, with the first letter capitalized. for example, french-in-braille is fr-brai and ja-kana is japanese written with the katakana alphabet. if the language is written in a highly typical way,...
part - HTML: Hypertext Markup Language
see our shadow part example for a usage example. ...
spellcheck - HTML: Hypertext Markup Language
the spellcheck global attribute is an enumerated attribute defines whether the element may be checked for spelling errors. 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 may have the following values: true, which indicates that the element should be, if possible, checked for spelling errors; false, which indicates that the element should not be checked for spelling errors. note: the spellcheck attribute is an enumerated one and not a boolean one. this means that the explicit usage of one of the values true or false is mandatory, and that a shorthand like <textarea spellcheck></textarea> is not allowed. ...
style - 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. ...
tabindex - HTML: Hypertext Markup Language
values and its order is defined by the document's source order. a positive value means the element should be focusable in sequential keyboard navigation, with its order defined by the value of the number. that is, tabindex="4" is focused before tabindex="5" and tabindex="0", but after tabindex="3". if multiple elements share the same positive tabindex value, their order relative to each other follows their position in the document source. the maximum value for tabindex is 32767. if not specified, it takes the default value 0. avoid using tabindex values greater than 0. doing so makes it difficult for people who rely on assistive technology to navigate and operate page content. instead, write the document with the elements in a logical sequence. if you set the tabindex attribute o...
title - HTML: Hypertext Markup Language
ssociated label for an <input> element as a fallback for a real <label> labeling controls in data tables additional semantics are attached to the title attributes of the <link>, <abbr>, <input>, and <menuitem> elements. multiline titles the title attribute may contain several lines. each u+000a line feed (lf) character represents a line break. some caution must be taken, as this means the following renders across two lines: html <p>newlines in <code>title</code> should be taken into account, like <abbr title="this is a multiline title">example</abbr>.</p> result title attribute inheritance if an element has no title attribute, then it inherits it from its parent node, which in turn may inherit it from its parent, and so on. if this attribute is set to the empty string, it means i...
translate - HTML: Hypertext Markup Language
"no", which indicates that the element must not be translated. ...
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. ...
Microdata - HTML: Hypertext Markup Language
microdata is part of the whatwg html standard and is used to nest metadata within existing content on web pages. search engines and web crawlers can extract and process microdata from a web page and use it to provide a richer browsing experience for users. search engines benefit greatly from direct access to this structured data because it allows search engines to understand the information on web pages and provide more relevant results to users. microdata uses a supporting vocabulary to describe an item and name-value pairs to assign values to its properties. microdata is an attempt to provide a simpler way of annotating html elements with machine-readable tags than the similar approaches of using rdfa and classic microformats. at a high level, microdata consists of a group of name-...
Microformats - HTML: Hypertext Markup Language
element content and semantic attributes. microformats2 is an update to microformats that provides a simpler way of annotating html structured syntax & vocabularies than previous approaches of using rdfa and microdata which require learning new attributes. microformats are supported by all major search engines. search engines benefit greatly from direct access to this structured data because it allows them to understand the information on web pages and provide more relevant results to users. in addition to being machine-readable, their format is designed to be easily read by humans. to create a microformats object, h-* class names are used in the class attribute. to add a property to an object, the p-*, u-*, dt-*, e-* class names are used on one of the object's descendants. there are op...
Common MIME types - HTTP
interchange format (gif) image/gif .htm .html hypertext markup language (html) text/html .ico icon format image/vnd.microsoft.icon .ics icalendar format text/calendar .jar java archive (jar) application/java-archive .jpeg .jpg jpeg images image/jpeg .js javascript text/javascript, per the following specifications: https://html.spec.whatwg.org/multipage/#scriptinglanguages https://html.spec.whatwg.org/multipage/#dependencies:willful-violation https://datatracker.ietf.org/doc/draft-ietf-dispatch-javascript-mjs/ .json json format application/json .jsonld json-ld format application/ld+json .mid .midi musical instrume...
Reason: CORS header ‘Origin’ cannot be added - HTTP
...
Connection management in HTTP/1.x - HTTP
d of having all resources on the same domain, say www.example.com, it could split over several domains, www1.example.com, www2.example.com, www3.example.com. each of these domains resolve to the same server, and the web browser will open 6 connections to each (in our example, boosting the connections to 18). this technique is called domain sharding. conclusion improved connection management allows considerable boosting of performance in http. with http/1.1 or http/1.0, using a persistent connection – at least until it becomes idle – leads to the best performance. however, the failure of pipelining has lead to designing superior connection management models, which have been incorporated into http/2. ...
Cross-Origin Resource Policy (CORP) - HTTP
, the actual request is not prevented—rather, the browser prevents the result from being leaked by stripping the response body. history the concept was originally proposed in 2012 (as from-origin), but resurrected in q2 of 2018 and implemented in safari and chromium. in early 2018, two side-channel hardware vulnerabilities known as meltdown and spectre were disclosed. these vulnerabilities allowed sensitive data disclosure due to a race condition which arose as part of speculative execution functionality, designed to improve performance. in response, chromium shipped cross-origin read blocking, which automatically protects certain resources (of content-type html, json and xml) against cross-origin reads. if the application does not serve a no-sniff directive, chromium will attempt to gu...
Accept-Charset - HTTP
set request http header advertises which character encodings the client understands. using content negotiation, the server selects one of the encodings, uses it, and informs the client of its choice within the content-type response header, usually in a charset= parameter. browsers usually don't send this header, as the default value for each resource is usually correct and transmitting it would allow fingerprinting. if the server cannot serve any character encoding from this request header, it can theoretically send back a 406 not acceptable error code. but for a better user experience, this is rarely done and the accept-charset header is ignored. in early versions of http/1.1, a default character encoding was defined: iso-8859-1. this is no longer recommended, and now each content-type ma...
Accept-Language - HTTP
, a-z, space or *,-.;=. syntax accept-language: <language> accept-language: * // multiple types, weighted with the quality value syntax: accept-language: fr-ch, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5 directives <language> a language tag (which is sometimes referred to as a "locale identifier"). this consists of a 2-3 letter base language tag representing the language, optionally followed by additional subtags separated by '-'. the most common extra information is the country or region variant (like 'en-us' or 'fr-ca') or the type of alphabet to use (like 'sr-latn'). other variants like the type of orthography ('de-de-1996') are usually not used in the context of this header. * any language; '*' is used as a wildcard. ;q= (q-factor weighting) any value placed in an order o...
Accept-Patch - HTTP
two common cases lead to this: a server receiving a patch request with an unsupported media type could reply with 415 unsupported media type and an accept-patch header referencing one or more supported media types. notes: an iana registry maintains a complete list of official content encodings. two others content encoding, bzip and bzip2, are sometimes used, though not standard. ...
Access-Control-Max-Age - HTTP
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). chromium (prior to v76) caps at 10 minutes (600 seconds). chromium (starting in v76) caps at 2 hours (7200 seconds). ...
Clear-Site-Data - HTTP
header type response header forbidden header name no syntax the clear-site-data header accepts one or more directives. if all types of data should be cleared, the wildcard directive ("*") can be used. ...
Connection - HTTP
connection-specific header fields such as connection and keep-alive are prohibited in http/2. chrome and firefox ignore them in http/2 responses, but safari conforms to the http/2 spec requirements and won’t load any response which contains them. ...
CSP: block-all-mixed-content - HTTP
if the former is set, the latter does nothing, so set one directive or the other – not both, unless you want to force https on older browsers that do not force it after a redirect to http. syntax content-security-policy: block-all-mixed-content; examples content-security-policy: block-all-mixed-content; <meta http-equiv="content-security-policy" content="block-all-mixed-content"> to disallow http assets on a more granular level, you can also set individual directives to https:. for example, to disallow nonsecure http images: content-security-policy: img-src https: specifications specification status comment mixed contentthe definition of 'block-all-mixed-content' in that specification. candidate recommendation initial definition. ...
CSP: referrer - HTTP
the http content-security-policy (csp) referrer directive used to specify information in the referer header (with a single r as this was a typo in the original spec) for links away from a page. this api is deprecated and removed from browsers. use the referrer-policy header instead. syntax content-security-policy: referrer <referrer-policy>; where <referrer-policy> can be one of the following values: "no-referrer" the referer header will be omitted entirely. no referrer information is sent along with requests. "none-when-downgrade" this is the user agent's default behavior if no policy is specified. 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 t...
CSP: require-sri-for - HTTP
y: require-sri-for style; content-security-policy: require-sri-for script style; script requires sri for scripts. style requires sri for style sheets. script style requires sri for both, scripts and style sheets. examples if you set your site to require sri for script and styles using this directive: content-security-policy: require-sri-for script style <script> elements like the following will be loaded as they use a valid integrity attribute. <script src="https://code.jquery.com/jquery-3.1.1.slim.js" integrity="sha256-5i/mq300m779n2ovdrl16lbohwxnudzl/r2avuxyxwa=" crossorigin="anonymous"></script> however, scripts without integrity won't load anymore: <script src="https://code.jquery.com/jquery-3.1.1.slim.js"></script> ...
Content-Type - HTTP
in requests, (such as post or put), the client tells the server what type of data is actually sent. ...
Cross-Origin-Embedder-Policy - HTTP
http cross-origin-embedder-policy (coep) response header prevents a document from loading any cross-origin resources that don't explicitly grant the document permission (using corp or cors). header type response header forbidden header name no syntax cross-origin-embedder-policy: unsafe-none | require-corp directives unsafe-none this is the default value. allows the document to fetch cross-origin resources without giving explicit permission through the cors protocol or the cross-origin-resource-policy header. require-corp a document can only load resources from the same origin, or resources explicitly marked as loadable from another origin. if a cross origin resource supports cors, the crossorigin attribute or the cross-origin-resource-policy header ...
Cross-Origin-Resource-Policy - HTTP
g this header in a production environment. the http cross-origin-resource-policy response header conveys a desire that the browser blocks no-cors cross-origin/cross-site requests to the given resource. header type response header forbidden header name no syntax cross-origin-resource-policy: same-site | same-origin | cross-origin examples the response header below will cause compatible user agents to disallow cross-origin no-cors requests: cross-origin-resource-policy: same-origin for more examples, see https://resourcepolicy.fyi/. specifications specification status comment fetch living standard initial definition ...
DNT - HTTP
Web › HTTP › Headers › DNT
1 the user prefers not to be tracked on the target site. ...
Device-Memory - HTTP
note: client hints are accessible only on secure origins (via tls). server has to opt in to receive device-memory header from the client by sending accept-ch and accept-ch-lifetime response headers. syntax the amount of device ram can be used as a fingerprinting variable, so values for the header are intentionally coarse to reduce the potential for its misuse. the header takes on the following values: 0.25, 0.5, 1, 2, 4, 8. device-memory: <number> examples server first needs to opt in to receive device-memory header by sending the response headers accept-ch containing device-memory and accept-ch-lifetime. accept-ch: device-memory accept-ch-lifetime: 86400 then on subsequent requests the client might send device-memory header back: device-memory: 1 specifications ...
If-None-Match - HTTP
equest will be processed only if the eventually existing resource's etag doesn't match any of the values listed. when the condition fails for get and head methods, then the server must return http status code 304 (not modified). for methods that apply server-side changes, the status code 412 (precondition failed) is used. note that the server generating a 304 response must generate any of the following header fields that would have been sent in a 200 (ok) response to the same request: cache-control, content-location, date, etag, expires, and vary. the comparison with the stored etag uses the weak comparison algorithm, meaning two files are considered identical if the content is equivalent — they don't have to be identical byte for byte. for example, two pages that differ by the date of ge...
Large-Allocation - HTTP
a new process currently, so the document must load in the current process. the document with the large-allocation header was loaded in a window which was opened by window.open(), <a target="_blank"> or other similar methods without rel="noopener" or the "noopener" feature being set. these windows must remain in the same process as their opener, as they can communicate, meaning that we cannot allow them to switch processes. the document with the large-allocation header has opened another window with window.open(), <a target="_blank"> or other similar methods without rel="noopener" or the "noopener" feature being set. this is for the same reason as above, namely that they can communicate and thus we cannot allow them to switch processes. a large-allocation header was ignored due to th...
Proxy-Authenticate - HTTP
the proxy-authenticate header is sent along with a 407 proxy authentication required. header type response header forbidden header name no syntax proxy-authenticate: <type> realm=<realm> directives <type> authentication type. a common type is "basic". iana maintains a list of authentication schemes. ...
Public-Key-Pins - HTTP
me no syntax public-key-pins: pin-sha256="<pin-value>"; max-age=<expire-time>; includesubdomains; report-uri="<uri>" directives pin-sha256="<pin-value>" the quoted string is the base64 encoded subject public key information (spki) fingerprint. it is possible to specify multiple pins for different public keys. some browsers might allow other hashing algorithms than sha-256 in the future. max-age=<expire-time> the time, in seconds, that the browser should remember that this site is only to be accessed using one of the defined keys. includesubdomains optional if this optional parameter is specified, this rule applies to all of the site's subdomains as well. report-uri="<uri>" optional if this optional parameter is specified...
Referrer-Policy - HTTP
ndividual requests with the referrerpolicy attribute on <a>, <area>, <img>, <iframe>, <script>, or <link> elements: <a href="http://example.com" referrerpolicy="origin"> alternatively, a noreferrer link relation on an a, area, or link element can be set: <a href="http://example.com" rel="noreferrer"> integration with css css can fetch resources referenced from stylesheets. these resources follow a referrer policy as well: external css stylesheets use the default policy (no-referrer-when-downgrade), unless it's overwritten via a referrer-policy http header on the css stylesheet’s response. for <style> elements or style attributes, the owner document's referrer policy is used. examples policy document navigation to referrer no-referrer https://exa...
Retry-After - HTTP
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. ...
Transfer-Encoding - HTTP
ing: compress transfer-encoding: deflate transfer-encoding: gzip transfer-encoding: 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 ...
Upgrade - HTTP
Web › HTTP › Headers › Upgrade
the http 1.1 (only) upgrade header can be used to upgrade an already established client/server connection to a different protocol (over the same transport protocol). for example, it can be used by a client to upgrade a connection from http 1.1 to http 2.0, or an http or https connection into a websocket. http/2 explicitly disallows the use of this mechanism/header; it is specific to http/1.1. header type request header, response header forbidden header name yes overview the upgrade header field may be used by clients to invite a server to switch to one (or more) of the listed protocols, in descending preference order. for example, the client might send a get request as shown, listing the preferred protocols to switch to (in this case "example/1" and "foo/...
User-Agent - HTTP
5.0 is the general token that says the browser is mozilla-compatible. for historical reasons, almost every browser today sends it. platform describes the native platform the browser is running on (windows, mac, linux, android, etc.), and if it's a mobile phone. firefox os phones simply say mobile — the web is the platform. note that platform can consist of multiple "; "-separated tokens. see below for further details and examples. rv:geckoversion indicates the release version of gecko (such as "17.0"). in recent browsers, geckoversion is the same as firefoxversion. gecko/geckotrail indicates that the browser is based on gecko. (on desktop, geckotrail is always the fixed string 20100101.) firefox/firefoxversion indicates the browser is firefox, and provides the version (such as "17.0"). ...
WWW-Authenticate - HTTP
m>[, charset="utf-8"] directives <type> authentication type. a common type is "basic". iana maintains a list of authentication schemes. realm=<realm> a description of the protected area. if no realm is specified, clients often display a formatted hostname instead. charset=<charset> tells the client the server's prefered encoding scheme when submitting a username and password. the only allowed value is the case insensitive string "utf-8". this does not relate to the encoding of the realm string. examples typically, a server response contains a www-authenticate header that looks like these: www-authenticate: basic www-authenticate: basic realm="access to the staging site", charset="utf-8" see also http authentication for examples on how to configure apache or nginx servers to p...
X-Content-Type-Options - HTTP
this is a way to opt out of mime type sniffing, or, in other words, to say that the mime types are deliberately configured. this header was introduced by microsoft in ie 8 as a way for webmasters to block content sniffing that was happening and could transform non-executable mime types into executable mime types. since then, other browsers have introduced it, even if their mime sniffing algorithms were less aggressive. ...
X-XSS-Protection - HTTP
f inline javascript ('unsafe-inline'), they can still provide protections for users of older web browsers that don't yet support csp. chrome has removed their xss auditor firefox have not, and will not implement x-xss-protection edge have retired their xss filter this means that if you do not need to support legacy browsers, it is recommended that you use content-security-policy without allowing unsafe-inline scripts instead. header type response header forbidden header name no syntax x-xss-protection: 0 x-xss-protection: 1 x-xss-protection: 1; mode=block x-xss-protection: 1; report=<reporting-uri> 0 disables xss filtering. 1 enables xss filtering (usually default in browsers). if a cross-site scripting attack is detected, the browser will sani...
CONNECT - HTTP
Web › HTTP › Methods › CONNECT
n. the server then proceeds to make the connection on behalf of the client. once the connection has been established by the server, the proxy server continues to proxy the tcp stream to and from the client. connect is a hop-by-hop method. request has body no successful response has body yes safe no idempotent no cacheable no allowed in html forms no syntax connect www.example.com:443 http/1.1 example some proxy servers might need authority to create a tunnel. see also the proxy-authorization header. connect server.example.com:80 http/1.1 host: server.example.com:80 proxy-authorization: basic agvsbg86d29ybgq= specifications specification title rfc 7231, section 4.3.6: connect hyp...
DELETE - HTTP
Web › HTTP › Methods › DELETE
the http delete request method deletes the specified resource. request has body may successful response has body may safe no idempotent yes cacheable no allowed in html forms no syntax delete /file.html http/1.1 example request delete /file.html http/1.1 responses if a delete method is successfully applied, there are several response status codes possible: a 202 (accepted) status code if the action will likely succeed but has not yet been enacted. a 204 (no content) status code if the action has been enacted and no further information is to be supplied. a 200 (ok) status code if the action has been enacted and the response message includes a representation describing the status. http/1.1 200 ok date...
GET - HTTP
Web › HTTP › Methods › GET
the http get method requests a representation of the specified resource. requests using get should only retrieve data. ...
HEAD - HTTP
Web › HTTP › Methods › HEAD
stead assumed to describe the response which a similar get request would have received. ...
PUT - HTTP
Web › HTTP › Methods › PUT
nd post is that put is idempotent: calling it once or several times successively has the same effect (that is no side effect), whereas successive identical post requests may have additional effects, akin to placing an order several times. request has body yes successful response has body no safe no idempotent yes cacheable no allowed in html forms no syntax put /new.html http/1.1 example request put /new.html http/1.1 host: example.com content-type: text/html content-length: 16 <p>new file</p> responses if the target resource does not have a current representation and the put request successfully creates one, then the origin server must inform the user agent by sending a 201 (created) response. http/1.1 2...
103 Early Hints - HTTP
Web › HTTP › Status › 103
syntax 103 early hints specifications specification status comments rfc 8297: 103 early hints ietf rfc initial definition 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. ...
202 Accepted - HTTP
Web › HTTP › Status › 202
the hypertext transfer protocol (http) 202 accepted response status code indicates that the request has been accepted for processing, but the processing has not been completed; in fact, processing may not have started yet. the request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. 202 is non-committal, meaning that there is no way for the http to later send an asynchronous response indicating the outcome of processing the request. it is intended for cases where another process or server handles the request, or for batch processing. status 202 accepted specifications specification title rfc 7231, section 6.3.3: 202 accepted hypertext transfer protocol (http/1.1): semantics and content ...
404 Not Found - HTTP
Web › HTTP › Status › 404
the resource is temporarily or permanently missing. but if a resource is permanently removed, a 410 (gone) should be used instead of a 404 status. status 404 not found custom error pages many web sites customize the look of a 404 page to be more helpful to the user and provide guidance on what to do next. apache servers can be configured using an .htaccess file and a code snippet like the following example. errordocument 404 /notfound.html for an example of a custom 404 page, see mdn's 404 page. custom design is a good thing, in moderation. feel free to make your 404 page humorous and human, but don't confuse your users. specifications specification title rfc 7231, section 6.5.4: 404 not found hypertext transfer protocol (http/1.1): semantics and conten...
406 Not Acceptable - HTTP
Web › HTTP › Status › 406
this error code, which would be cryptic for the end user and difficult to fix, servers ignore the relevant header and serve an actual page to the user. it is assumed that even if the user won't be completely happy, they will prefer this to an error code. if a server returns such an error status, the body of the message should contain the list of the available representations of the resources, allowing the user to choose among them. status 406 not acceptable specifications specification title rfc 7231, section 6.5.6: 406 not acceptable hypertext transfer protocol (http/1.1): semantics and content ...
416 Range Not Satisfiable - HTTP
Web › HTTP › Status › 416
he hypertext transfer protocol (http) 416 range not satisfiable error response code indicates that a server cannot serve the requested ranges. the most likely reason is that the document doesn't contain such ranges, or that the range header value, though syntactically correct, doesn't make sense. the 416 response message contains a content-range indicating an unsatisfied range (that is a '*') followed by a '/' and the current length of the resource. e.g. content-range: bytes */12777 faced with this error, browsers usually either abort the operation (for example, a download will be considered as non-resumable) or ask for the whole document again. status 416 range not satisfiable specifications specification title rfc 7233, section 4.4: 416 request not satisfiable...
501 Not Implemented - HTTP
Web › HTTP › Status › 501
is supported by then. 501 is the appropriate response when the server does not recognize the request method and is incapable of supporting it for any resource. the only methods that servers are required to support (and therefore that must not return 501) are get and head. if the server does recognize the method, but intentionally does not support it, the appropriate response is 405 method not allowed. a 501 error is not something you can fix, but requires a fix by the web server you are trying to access. a 501 response is cacheable by default; that is, unless caching headers instruct otherwise. status 501 not implemented specifications specification title rfc 7231, section 6.6.2: 501 not implemented hypertext transfer protocol (http/1.1): semantics and...
About JavaScript - JavaScript
rototype) 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 primarily by no...
JavaScript Guide - JavaScript
tion about a language feature, have a look at the javascript reference. ...
JavaScript language resources - JavaScript
ecmascript is the scripting language that forms the basis of javascript. ecmascript standardized by the ecma international standards organization in the ecma-262 and ecma-402 specifications. ...
static - JavaScript
ass itself. these are often utility functions, such as functions to create or clone objects. 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 static methodname() { ... } examples using static in classes the following example demonstrates several things: how a static method is implemented on a class. that a class with a static member can be sub-classed. how a static method can and cannot be called. class triple { static triple(n = 1) { return n * 3; } } class biggertriple extends triple { static triple(n) { return super.triple(n) * super.triple(n); } } console.log(triple.triple()); ...
The legacy Iterator protocol - JavaScript
spidermonkey-specific feature, which is removed in firefox 58+. for future-facing usages, consider using for..of loops and the iterator protocol. the deprecated firefox-only iterator protocol firefox, prior to version 26 implemented another iterator protocol that is similar to the standard es2015 iterator protocol. an object is an legacy iterator when it implements 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 st...
TypeError: can't assign to property "x" on "y": not an object - JavaScript
: can't assign to property "x" on {y}: not an object (firefox) typeerror: cannot create property 'x' on {y} (chrome) error type typeerror. what went wrong? in strict_mode, a typeerror is raised when attempting to create a property on primitive value such as a symbol, a string, a number or a boolean. primitive values cannot hold any property. the problem might be that an unexpected value is flowing at an unexpected place, or that an object variant of a string or a number is expected. examples invalid cases 'use strict'; var foo = "my string"; // the following line does nothing if not in strict mode. foo.bar = {}; // typeerror: can't assign to property "bar" on "my string": not an object fixing the issue either fix the code to prevent the primitive from being used in such places, o...
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
(firefox) typeerror: cannot delete property 'x' of #<object> (chrome) error type typeerror in strict mode only. what went wrong? it was attempted to delete a property, but that property is non-configurable. ...
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated - JavaScript
the javascript strict mode-only exception "applying the 'delete' operator to an unqualified name is deprecated" occurs when variables are attempted to be deleted using the delete operator. message syntaxerror: calling delete on expression not allowed in strict mode (edge) syntaxerror: applying the 'delete' operator to an unqualified name is deprecated (firefox) syntaxerror: delete of an unqualified identifier in strict mode. (chrome) error type syntaxerror in strict mode only. what went wrong? normal variables in javascript can't be deleted using the delete operator. in strict mode, an attempt to delete a variable will throw an error and is not allowed. the delete operator can only delete properties on an object. object properties are "qualified" if they are configurable. unlike wha...
Warning: Date.prototype.toLocaleFormat is deprecated - JavaScript
you can now either use the date.prototype.tolocaledatestring method if you just want to format one date. var today = new date(); var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var date = today.tolocaledatestring('de-de', options); console.log(date); // "freitag, 10. märz 2017" or, you can make use of the intl.datetimeformat object, which allows you to cache an object with most of the computations done so that formatting is fast. this is useful if you have a loop of dates to format. var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var dateformatter = new intl.datetimeformat('de-de', options) var dates = [date.utc(2012, 11, 20, 3, 0, 0), date.utc(2014, 04, 12, 8, 0, 0)]; d...
SyntaxError: test for equality (==) mistyped as assignment (=)? - JavaScript
ou would normally expect a test for equality (==). to help debugging, javascript (with strict warnings enabled) warns about this pattern. examples assignment within conditional expressions it is advisable to not use simple assignments in a conditional expression (such as if...else), because the assignment can be confused with equality when glancing over the code. for example, do not use the following code: if (x = y) { // do the right thing } if you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. for example: if ((x = y)) { // do the right thing } otherwise, you probably meant to use a comparison operator (e.g. == or ===): if (x == y) { // do the right thing } ...
TypeError: setting getter-only property "x" - JavaScript
the javascript strict mode-only exception "setting getter-only property" occurs when there is an attempt to set a new value to a property for which only a getter is specified. message typeerror: assignment to read-only properties is not allowed in strict mode (edge) typeerror: setting getter-only property "x" (firefox) typeerror: cannot set property "prop" of #<object> which has only a getter (chrome) error type typeerror in strict mode only. what went wrong? there is an attempt to set a new value to a property for which only a getter is specified. while this will be silently ignored in non-strict mode, it will throw a typeerror in strict mode. examples property with no setter the example below shows how to set a getter for a property. it doesn't specify a setter, so a typeerror wi...
SyntaxError: identifier starts immediately after numeric literal - JavaScript
ent wrong? the names of variables, called identifiers, conform to certain rules, which your code must adhere to! a javascript identifier must start with a letter, underscore (_), or dollar sign ($). they can't start with a digit! only subsequent characters can be digits (0-9). examples variable names starting with numeric literals variable names can't start with numbers in javascript. the following fails: var 1life = 'foo'; // syntaxerror: identifier starts immediately after numeric literal var foo = 1life; // syntaxerror: identifier starts immediately after numeric literal alert(1.foo); // syntaxerror: identifier starts immediately after numeric literal you will need to rename your variable to avoid the leading number. var life1 = 'foo'; var foo = life1; ...
RangeError: invalid date - JavaScript
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(1317826080); // unix time stamp for 05 october 2011 14:48:00 utc ...
SyntaxError: a declaration in the head of a for-of loop can't have an initializer - JavaScript
the javascript exception "a declaration in the head of a for-of loop can't have an initializer" occurs when the head of a for...of loop contains an initializer expression such as |for (var i = 0 of iterable)|. this is not allowed in for-of loops. message syntaxerror: for-of loop head declarations cannot have an initializer (edge) syntaxerror: a declaration in the head of a for-of loop can't have an initializer (firefox) syntaxerror: for-of loop variable declaration may not have an initializer. (chrome) error type syntaxerror what went wrong? the head of a for...of loop contains an initializer expression. that is, a variable is declared and assigned a value |for (var i = 0 of iterable)|. this is not allowed in for-of loops. you might want a for loop that does allow an initializer. exa...
URIError: malformed URI sequence - JavaScript
ri, encodeuricomponent, or decodeuricomponent function was not valid, so that the function was unable encode or decode properly. examples encoding encoding replaces each instance of certain characters by one, two, three, or four escape sequences representing the utf-8 encoding of the character. an urierror will be thrown if there is an attempt to encode a surrogate which is not part of a high-low pair, for example: encodeuri('\ud800'); // "urierror: malformed uri sequence" encodeuri('\udfff'); // "urierror: malformed uri sequence" a high-low pair is ok. for example: encodeuri('\ud800\udfff'); // "%f0%90%8f%bf" decoding decoding replaces each escape sequence in the encoded uri component with the character that it represents. if there isn't such a character, an error will be thrown: ...
SyntaxError: missing name after . operator - JavaScript
ot operator (.) is used for property access. message syntaxerror: missing name after . operator error type syntaxerror what went wrong? the dot operator (.) is used for property access. you will have to specify the name of the property that you want to access. for computed property access, you might need to change your property access from using a dot to using square brackets. these will allow you to compute an expression. maybe you intended to do concatenation instead? a plus operator (+) is needed in that case. please see the examples below. examples property access property accessors in javascript use either the dot (.) or square brackets ([]), but not both. square brackets allow computed property access. var obj = { foo: { bar: "baz", bar2: "baz2" } }; var i = 2; obj.[foo].[ba...
RangeError: repeat count must be non-negative - JavaScript
rror: argument out of range rangeerror: repeat count must be non-negative (firefox) rangeerror: invalid count value (chrome) error type rangeerror what went wrong? the string.prototype.repeat() method has been used. it has a count parameter indicating the number of times to repeat the string. it must be between 0 and less than positive infinity and cannot be a negative number. the range of allowed values can be described like this: [0, +∞). examples invalid cases 'abc'.repeat(-1); // rangeerror valid cases 'abc'.repeat(0); // '' 'abc'.repeat(1); // 'abc' 'abc'.repeat(2); // 'abcabc' 'abc'.repeat(3.5); // 'abcabcabc' (count will be converted to integer) ...
TypeError: "x" is read-only - JavaScript
the javascript strict mode-only exception "is read-only" occurs when a global variable or object property that was assigned to is a read-only property. message typeerror: assignment to read-only properties is not allowed in strict mode (edge) typeerror: "x" is read-only (firefox) typeerror: 0 is read-only (firefox) typeerror: cannot assign to read only property 'x' of #<object> (chrome) typeerror: cannot assign to read only property '0' of [object array] (chrome) error type typeerror what went wrong? the global variable or object property that was assigned to is a read-only property. (technically, it is a non-writable data property.) this error happens only in strict mode code. in non-strict code, the assignment is silently ignored. examples invalid cases read-only properties are ...
SyntaxError: redeclaration of formal parameter "x" - JavaScript
laration (edge) syntaxerror: redeclaration of formal parameter "x" (firefox) syntaxerror: identifier "x" has already been declared (chrome) error type syntaxerror what went wrong? the same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again. redeclaring the same variable within the same function or block scope using let is not allowed in javascript. examples redeclared argument in this case, the variable "arg" redeclares the argument. function f(arg) { let arg = 'foo'; } // syntaxerror: redeclaration of formal parameter "arg" if you want to change the value of "arg" in the function body, you can do so, but you do not need to declare the same variable again. in other words: you can omit the let keyword. if you want t...
SyntaxError: "x" is a reserved identifier - JavaScript
words are used as identifiers. message syntaxerror: the use of a future reserved word for an identifier is invalid (edge) syntaxerror: "x" is a reserved identifier (firefox) syntaxerror: unexpected reserved word (chrome) error type syntaxerror what went wrong? reserved keywords will throw in if they are used as identifiers. these are reserved in strict mode and sloppy mode: enum the following are only reserved when they are found in strict mode code: implements interface let package private protected public static examples strict and non-strict reserved keywords the enum identifier is generally reserved. var enum = { red: 0, green: 1, blue: 2 }; // syntaxerror: enum is a reserved identifier in strict mode code, more identifiers are reserved. "use strict"; var pack...
RangeError: repeat count must be less than infinity - JavaScript
the javascript exception "repeat count must be less than infinity" occurs when the string.prototype.repeat() method is used with a count argument that is infinity. message rangeerror: argument out of range (edge) rangeerror: repeat count must be less than infinity and not overflow maximum string size (firefox) rangeerror: invalid count value (chrome) error type rangeerror what went wrong? the string.prototype.repeat() method has been used. it has a count parameter indicating the number of times to repeat the string. it must be between 0 and less than positive infinity and cannot be a negative number. the range of allowed values can be described like this: [0, +∞). the resulting string can also not be larger than the maximum string size, which can differ in javascript engines. in fi...
SyntaxError: function statement requires a name - JavaScript
de a function name after the function keyword. this doesn't work: function greeter() { german: function () { return "moin"; } } // syntaxerror: function statement requires a name this would work, for example: function greeter() { german: function g() { return "moin"; } } object methods if you intended to create a method of an object, you will need to create an object. the following syntax without a name after the function keyword is valid then. var greeter = { german: function () { return "moin"; } }; callback syntax also, check your syntax when using callbacks. brackets and commas can get difficult easily. promise.then( function() { console.log("success"); }); function() { console.log("error"); } // syntaxerror: function statement requires a na...
Method definitions - JavaScript
{}, async* generator( parameters… ) {}, // with computed keys get [property]() {}, set [property](value) {}, [property]( parameters… ) {}, *[generator]( parameters… ) {}, async [property]( parameters… ) {}, async* [generator]( parameters… ) {}, }; description the shorthand syntax is similar to the getter and setter syntax introduced in ecmascript 2015. given the following code: const obj = { foo: function() { // ... }, bar: function() { // ... } } you are now able to shorten this to: const obj = { foo() { // ... }, bar() { // ... } } generator methods generator methods can be defined using the shorthand syntax as well. when doing so: the asterisk (*) in the shorthand syntax must be before the generator property name. ...
Array.prototype[@@unscopables] - JavaScript
: copywithin() entries() fill() find() findindex() includes() keys() values() see symbol.unscopables for how to set unscopables for your own objects. property attributes of array.prototype[@@unscopables] writable no enumerable no configurable yes examples use in with environments the following code works fine in es5 and below. however, in ecmascript 2015 and later, the array.prototype.keys() method was introduced. that means that inside with environments, "keys" would now be the method and not the variable. this is where now the built-in @@unscopables array.prototype[@@unscopables] symbol property comes into play and prevents that some of the array methods are being scoped into the ...
Array() constructor - JavaScript
the array() constructor is used to create array objects. syntax [element0, element1, ..., elementn] new array(element0, element1[, ...[, elementn]]) new array(arraylength) parameters elementn a javascript array is initialized with the given elements, except in the case where a single argument is passed to the array constructor and that argument is a number (see the arraylength parameter below). note that this special case only applies to javascript arrays created with the array constructor, not array literals created with the bracket syntax. arraylength if the only argument passed to the array constructor is an integer between 0 and 232-1 (inclusive), this returns a new javascript array with its length property set to that number (note: this implies an array of arraylength empty slo...
Array.prototype.copyWithin() - 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 arr.copywithin(target[, start[, end]]) parameters target zero-based index at which to copy the sequence to. if negative, target will be counted from the end. if target is at or greater than arr.length, nothing will be copied. if target is positioned after start, the copied sequence will be trimmed to fit arr.length. start optional zero-based index at which to start copying elements from. ...
Array.prototype.includes() - JavaScript
3 + (-100) = -97 let arr = ['a', 'b', 'c'] arr.includes('a', -100) // true arr.includes('b', -100) // true arr.includes('c', -100) // true arr.includes('a', -2) // false includes() used as a generic method includes() method is intentionally generic. it does not require this value to be an array object, so it can be applied to other kinds of objects (e.g. array-like objects). the example below illustrates includes() method called on the function's arguments object. (function() { console.log(array.prototype.includes.call(arguments, 'a')) // true console.log(array.prototype.includes.call(arguments, 'd')) // false })('a','b','c') please do not add polyfills on reference articles. for more details and discussion, see https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shou...
Array.of() - JavaScript
// array of 7 empty slots array(1, 2, 3); // [1, 2, 3] syntax array.of(element0[, element1[, ...[, elementn]]]) parameters elementn elements used to create the array. return value a new array instance. description this function is part of the ecmascript 2015 standard. for more information, see: array.of() array.from() proposal array.of() polyfill polyfill running the following code before any other code will create array.of() if it's not natively available. if (!array.of) { array.of = function() { return array.prototype.slice.call(arguments); // or let vals = []; for(let prop in arguments){ vals.push(arguments[prop]); } return vals; } } examples using array.of array.of(1); // [1] array.of(1, 2, 3); // [1, 2, 3] arra...
Array.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the array. syntax arr.tosource() return value a string representing the source code of the array. description the tosource method returns the following values: for the built-in array object, tosource returns the following string indicating that the source code is not available: function array() { [native code] } for instances of array, tosource returns a string representing the source code. 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();...
AsyncFunction - JavaScript
argn names to be used by the function as formal argument names. ...
Atomics.add() - JavaScript
value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to add a value to. value the number to add. return value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using add() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.add(ta, 0, 12); // returns 0, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.add' in that specification. ...
Atomics.and() - JavaScript
an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to compute the bitwise and. value the number to compute the bitwise and with. return value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. description the bitwise and operation only yields 1, if both a and b are 1. the truth table for the and operation is: a b a & b 0 0 0 0 1 0 1 0 0 1 1 1 for example, a bitwise and of 5 & 1 results in 0001 which is 1 in decimal...
Atomics.compareExchange() - JavaScript
nt8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to exchange a value. expectedvalue the value to check for equality. replacementvalue the number to exchange. return value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using compareexchange() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 7; atomics.compareexchange(ta, 0, 7, 12); // returns 7, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomic...
Atomics.exchange() - JavaScript
parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to exchange a value. value the number to exchange. return value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using exchange() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.exchange(ta, 0, 12); // returns 0, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.exchange' in that specific...
Atomics.load() - JavaScript
. syntax atomics.load(typedarray, index) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to load from. return value the value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using load const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.add(ta, 0, 12); atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.load' in that specification. ...
Atomics.or() - JavaScript
y an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to compute the bitwise or. value the number to compute the bitwise or with. return value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. description the bitwise or operation yields 1, if either a or b are 1. the truth table for the or operation is: a b a | b 0 0 0 0 1 1 1 0 1 1 1 1 for example, a bitwise or of 5 & 1 results in 0101 which is 5 in decimal. 5 0...
Atomics.store() - JavaScript
e(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to store a value in. value the number to store. return value the value that has been stored. exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using store() var sab = new sharedarraybuffer(1024); var ta = new uint8array(sab); atomics.store(ta, 0, 12); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.store' in that specification. ...
Atomics.sub() - JavaScript
ameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to subtract a value from. value the number to subtract. return value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using sub const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 48; atomics.sub(ta, 0, 12); // returns 48, the old value atomics.load(ta, 0); // 36 specifications specification ecmascript (ecma-262)the definition of 'atomics.sub' in that specification. ...
Atomics.wait() - JavaScript
syntax atomics.wait(typedarray, index, value[, timeout]) parameters typedarray a shared int32array. index the position in the typedarray to wait on. ...
Atomics.xor() - JavaScript
an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to compute the bitwise xor. value the number to compute the bitwise xor with. return value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. description the bitwise xor operation yields 1, if a and b are different. the truth table for the xor operation is: a b a ^ b 0 0 0 0 1 1 1 0 1 1 1 0 for example, a bitwise xor of 5 ^ 1 results in 0100 which is 4 in decimal. ...
Atomics - JavaScript
that index. atomics.store() stores a value at the specified index of the array. returns the value. atomics.sub() subtracts a value at the specified index of the array. returns the old value at that index. atomics.wait() verifies that the specified index of the array still contains a value and sleeps awaiting or times out. returns either "ok", "not-equal", or "timed-out". if waiting is not allowed in the calling agent then it throws an error exception. (most browsers will not allow wait() on the browser's main thread.) atomics.xor() computes a bitwise xor on the value at the specified index of the array with the provided value. returns the old value at that index. examples using atomics const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 5; atomics.add...
BigInt.asIntN() - JavaScript
clamp to fit into the supplied bits. returns the value of bigint modulo 2width as a signed integer. examples staying in 64-bit ranges the bigint.asintn() method can be useful to stay in the range of 64-bit arithmetic. const max = 2n ** (64n - 1n) - 1n; bigint.asintn(64, max); // ↪ 9223372036854775807n bigint.asintn(64, max + 1n); // ↪ -9223372036854775807n // negative because of overflow specifications specification ecmascript (ecma-262)the definition of 'bigint.asintn()' in that specification. ...
BigInt.asUintN() - JavaScript
bigint the integer to clamp to fit into the supplied bits. returns the value of bigint modulo 2width as an unsigned integer. examples staying in 64-bit ranges the bigint.asuintn() method can be useful to stay in the range of 64-bit arithmetic. const max = 2n ** 64n - 1n; bigint.asuintn(64, max); // ↪ 18446744073709551615n bigint.asuintn(64, max + 1n); // ↪ 0n // zero because of overflow specifications specification ecmascript (ecma-262)the definition of 'bigint.asuintn()' in that specification. ...
BigInt - JavaScript
ck and forth, however, as the precision of a bigint may be lost when it is coerced to a number. type information when tested against typeof, a bigint will give "bigint": typeof 1n === 'bigint' // true typeof bigint('1') === 'bigint' // true when wrapped in an object, a bigint will be considered as a normal "object" type: typeof object(1n) === 'object' // true operators the following operators may be used with bigints (or object-wrapped bigints): +, *, -, **, %. bitwise operators are supported as well, except >>> (zero-fill right shift) as all bigints are signed. also unsupported is the unary operator (+), in order to not break asm.js. const previousmaxsafe = bigint(number.max_safe_integer) // ↪ 9007199254740991n const maxplusone = previousmaxsafe + 1n // ↪ 9007199...
Boolean.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. syntax booleanobj.tosource() boolean.tosource() return value a string representing the source code of the object. examples native function for the built-in boolean object, tosource returns the following string indicating that the source code is not available: function boolean() { [native code] } specifications not part of any standard. ...
Boolean.prototype.toString() - JavaScript
returns a string representation of the object. javascript calls the tostring() method automatically when a boolean is to be represented as a text value or when a boolean is referred to in a string concatenation. for boolean objects and values, the built-in tostring() method returns the string "true" or "false" depending on the value of the boolean object. examples using tostring() in the following code, flag.tostring() returns "true": var flag = new boolean(true); var myvar = flag.tostring(); specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.tostring' in that specification. ...
Boolean - JavaScript
y array ([]), or the string "false", create an object with an initial value of true. do not confuse the primitive boolean values true and false with the true and false values of the boolean object. any object of which the value is not undefined or null, including a boolean object whose value is false, evaluates to true when passed to a conditional statement. for example, the condition in the following if statement evaluates to true: var x = new boolean(false); if (x) { // this code is executed } this behavior does not apply to boolean primitives. for example, the condition in the following if statement evaluates to false: var x = false; if (x) { // this code is not executed } do not use a boolean object to convert a non-boolean value to a boolean value. to perform this task, inste...
DataView.prototype.setBigInt64() - JavaScript
e https://github.com/mdn/interactive-examples and send us a pull request. syntax dataview.setbigint64(byteoffset, value [, littleendian]) parameters byteoffset the offset, in bytes, from the start of the view to store the data from. value the value to set as a bigint. the highest possible value that fits in a signed 64-bit integer is 2n ** (64n -1n) - 1n (9223372036854775807n). upon overflow, it will be negative (-9223372036854775808n). littleendian optional indicates whether the 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined. errors thrown rangeerror thrown if the byteoffset is set such that it would store beyond the end of the view. examples using the setbigint64 method var buffer = ne...
DataView.prototype.setBigUint64() - JavaScript
ne https://github.com/mdn/interactive-examples and send us a pull request. syntax dataview.setbiguint64(byteoffset, value [, littleendian]) parameters byteoffset the offset, in bytes, from the start of the view to store the data from. value the value to set as a bigint. the highest possible value that fits in an unsigned 64-bit integer is 2n ** 64n - 1n (18446744073709551615n). upon overflow, it will be zero (0n). littleendian optional indicates whether the 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined. errors thrown rangeerror thrown if the byteoffset is set such that it would store beyond the end of the view. examples using the setbiguint64 method var buffer = new arraybuffer(8); var ...
Date.UTC() - JavaScript
a date object. if a parameter is outside of the expected range, the utc() method updates the other parameters to accommodate the value. for example, if 15 is used for month, the year will be incremented by 1 (year + 1) and 3 will be used for the month. utc() is a static method of date, so it's called as date.utc() rather than as a method of a date instance. examples using date.utc() the following statement creates a date object with the arguments treated as utc instead of local: let utcdate = new date(date.utc(2018, 11, 1, 0, 0, 0)); specifications specification ecmascript (ecma-262)the definition of 'date.utc' in that specification. ...
Date.prototype.getDate() - JavaScript
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.getdate() return value an integer number, between 1 and 31, representing the day of the month for the given date according to local time. examples using getdate() the second statement below assigns the value 25 to the variable day, based on the value of the date object xmas95. var xmas95 = new date('december 25, 1995 23:15:30'); var day = xmas95.getdate(); console.log(day); // 25 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getdate' in that specification. ...
Date.prototype.getDay() - JavaScript
to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.getday() return value an integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for sunday, 1 for monday, 2 for tuesday, and so on. examples using getday() the second statement below assigns the value 1 to weekday, based on the value of the date object xmas95. december 25, 1995, is a monday. var xmas95 = new date('december 25, 1995 23:15:30'); var weekday = xmas95.getday(); console.log(weekday); // 1 note: if needed, the full name of a day ("monday" for example) can be obtained by using intl.datetimeformat with an options parameter. using this method, the internationaliz...
Date.prototype.getFullYear() - JavaScript
.getfullyear() return value a number corresponding to the year of the given date, according to local time. description the value returned by getfullyear() is an absolute number. for dates between the years 1000 and 9999, getfullyear() returns a four-digit number, for example, 1995. use this function to make sure a year is compliant with years after 2000. examples using getfullyear() the following example assigns the four-digit value of the current year to the variable year. var today = new date(); var year = today.getfullyear(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getfullyear' in that specification. ...
Date.prototype.getHours() - JavaScript
teractive 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.gethours() return value an integer number, between 0 and 23, representing the hour for the given date according to local time. examples using gethours() the second statement below assigns the value 23 to the variable hours, based on the value of the date object xmas95. let xmas95 = new date('december 25, 1995 23:15:30'); let hours = xmas95.gethours(); console.log(hours); // 23 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.gethours' in that specification. ...
Date.prototype.getMilliseconds() - JavaScript
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.getmilliseconds() return value a number, between 0 and 999, representing the milliseconds for the given date according to local time. examples using getmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds: var today = new date(); var milliseconds = today.getmilliseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getmilliseconds' in that specification. ...
Date.prototype.getMinutes() - JavaScript
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.getMonth() - JavaScript
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.getmonth() return value an integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to january, 1 to february, and so on. examples using getmonth() the second statement below assigns the value 11 to the variable month, based on the value of the date object xmas95. var xmas95 = new date('december 25, 1995 23:15:30'); var month = xmas95.getmonth(); console.log(month); // 11 note: if needed, the full name of a month ("january" for example) can be obtained by using intl.datetimeformat() with an options parameter. using this method, internationalization is made easier...
Date.prototype.getSeconds() - JavaScript
ive 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.getseconds() return value an integer number, between 0 and 59, representing the seconds in the given date according to local time. examples using getseconds() the second statement below assigns the value 30 to the variable seconds, based on the value of the date object xmas95. var xmas95 = new date('december 25, 1995 23:15:30'); var seconds = xmas95.getseconds(); console.log(seconds); // 30 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getseconds' in that specification. ...
Date.prototype.getUTCDate() - JavaScript
the getutcdate() method returns the day (date) of the month in the specified date according to universal time. syntax dateobj.getutcdate() return value an integer number, between 1 and 31, representing the day of the month in the given date according to universal time. examples using getutcdate() the following example assigns the day portion of the current date to the variable day. var today = new date(); var day = today.getutcdate(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcdate' in that specification. ...
Date.prototype.getUTCDay() - JavaScript
epository. 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.getutcday() return value an integer number corresponding to the day of the week for the given date, according to universal time: 0 for sunday, 1 for monday, 2 for tuesday, and so on. examples using getutcday() the following example assigns the weekday portion of the current date to the variable weekday. var today = new date(); var weekday = today.getutcday(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcday' in that specification. ...
Date.prototype.getUTCFullYear() - JavaScript
examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.getutcfullyear() return value a number representing the year in the given date according to universal time. description the value returned by getutcfullyear() is an absolute number that is compliant with year-2000, for example, 1995. examples using getutcfullyear() the following example assigns the four-digit value of the current year to the variable year. var today = new date(); var year = today.getutcfullyear(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcfullyear' in that specification. ...
Date.prototype.getUTCHours() - JavaScript
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. syntax dateobj.getutchours() return value an integer number, between 0 and 23, representing the hours in the given date according to universal time. examples using getutchours() the following example assigns the hours portion of the current time to the variable hours. var today = new date(); var hours = today.getutchours(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutchours' in that specification. ...
Date.prototype.getUTCMilliseconds() - JavaScript
number, between 0 and 999, representing the milliseconds portion of the given date object. this method is a companion to the other utc based methods that give hour portion, minute portion, etc.; this method gives milliseconds portion. not to be confused with unix epoch time. to get total milliseconds since 1970/01/01, use the method ".gettime()". examples using getutcmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds. var today = new date(); var milliseconds = today.getutcmilliseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcmilliseconds' 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. ...
Date.prototype.getUTCMonth() - JavaScript
f 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.getutcmonth() return value an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for january, 1 for february, 2 for march, and so on. examples using getutcmonth() the following example assigns the month portion of the current date to the variable month. var today = new date(); var month = today.getutcmonth(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcmonth' in that specification. ...
Date.prototype.getUTCSeconds() - JavaScript
the getutcseconds() method returns the seconds in the specified date according to universal time. syntax dateobj.getutcseconds() return value an integer number, between 0 and 59, representing the seconds in the given date according to universal time. examples using getutcseconds() the following example assigns the seconds portion of the current time to the variable seconds. var today = new date(); var seconds = today.getutcseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcseconds' in that specification. ...
Date.prototype.getYear() - JavaScript
ned is 2026. examples years between 1900 and 1999 the second statement assigns the value 95 to the variable year. var xmas = new date('december 25, 1995 23:15:00'); var year = xmas.getyear(); // returns 95 years above 1999 the second statement assigns the value 100 to the variable year. var xmas = new date('december 25, 2000 23:15:00'); var year = xmas.getyear(); // returns 100 years below 1900 the second statement assigns the value -100 to the variable year. var xmas = new date('december 25, 1800 23:15:00'); var year = xmas.getyear(); // returns -100 setting and getting a year between 1900 and 1999 the third statement assigns the value 95 to the variable year, representing the year 1995. var xmas = new date('december 25, 2015 23:15:00'); xmas.setyear(95); var year = xmas.get...
Date.now() - JavaScript
date.now() method returns the number of milliseconds elapsed since january 1, 1970 00:00:00 utc. syntax var timeinms = date.now(); return value a number representing 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 ...
Date.prototype.setMonth() - JavaScript
cording to the currently set year. syntax dateobj.setmonth(monthvalue[, dayvalue]) versions prior to javascript 1.3 dateobj.setmonth(monthvalue) parameters monthvalue a zero-based integer representing the month of the year offset from the start of the year. so, 0 represents january, 11 represents december, -1 represents december of the previous year, and 12 represents january of the following year. dayvalue optional. an integer from 1 to 31, representing the day of the month. 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 dayvalue parameter, the value returned from the getdate() method is used. if a parameter you specify is outside of the expected range, setmonth() attempts to update th...
Date.prototype.toGMTString() - JavaScript
act format of the value returned by togmtstring() varies according to the platform and browser, in general it should represent a human readable date string. note: togmtstring() is deprecated and should no longer be used. it remains implemented only for backward compatibility; please use toutcstring() instead. syntax dateobj.togmtstring() return value a string representing the given date following the internet greenwich mean time (gmt) convention. examples simple example in this example, the togmtstring() method converts the date to gmt (utc) using the operating system's time-zone offset and returns a string value that is similar to the following form. the exact format depends on the platform. var today = new date(); var str = today.togmtstring(); // deprecated! use toutcstring() ...
Date.prototype.toISOString() - JavaScript
lease clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.toisostring() return value a string representing the given date in the iso 8601 format according to universal time. polyfill this method was standardized in ecma-262 5th edition. ...
Date.prototype.toLocaleTimeString() - JavaScript
n e​.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized time formats. ...
Date.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. syntax dateobj.tosource() date.tosource() return value a string representing the source code of the given date object. examples native function for the built-in date object, tosource() returns the following string indicating that the source code is not available: function date() { [native code] } specifications not part of any standard. ...
Date.prototype.toString() - JavaScript
nation, such as var today = 'today is ' + new date(). tostring() is a generic method, it does not require that its this is a date instance. however, it must have an internal [[timevalue]] property that can't be constructed using native javascript, so it's effectively limited to use with date instances. if called on a non–date instance, a typeerror is thrown. examples using tostring() the following assigns the tostring() value of a date object to myvar: var x = new date(); var myvar = x.tostring(); // assigns a string value to myvar in the same format as: // mon sep 08 1998 14:36:22 gmt-0700 (pdt) specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tostring' in that specification. ...
Date.prototype.toTimeString() - JavaScript
pull request. syntax dateobj.totimestring() 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-dependen...
Error.prototype.lineNumber - JavaScript
error. examples using linenumber var e = new error('could not parse input'); throw e; console.log(e.linenumber) // 2 alternative example using error event window.addeventlistener('error', function(e) { console.log(e.linenumber); // 5 }); var e = new error('could not parse input'); throw e; this is not a standard feature and lacks widespread support. see the browser compatability table below. specifications not part of any standard. ...
Error.prototype.toSource() - JavaScript
could eval to the same error. syntax e.tosource() return value a string containing the source code of the error. examples using tosource calling the tosource method of an error instance (including nativeerrors) will return a string containing the source code of the error. this string can be evaluated to create an (approximately) equal object. naturally, the string containing the source follows the structure of the error constructor. for example: (newname(message ,filename,linenumber)) where these attributes correspond to the respective properties of the error instance. note: be aware that the properties used by the tosource method in the creation of this string are mutable and may not accurately reflect the function used to create an error instance or the filename or line number ...
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. ...
Function() constructor - JavaScript
names of the identifiers of the parameters in the function to be created, in the order in which they are passed. omitting an argument will result in the value of that parameter being undefined. invoking the function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. examples specifying arguments with the function constructor the following code creates a function object that takes two arguments. // example can be run directly in your javascript console // create a function that takes two arguments, and returns the sum of those arguments const adder = new function('a', 'b', 'return a + b'); // call the function adder(2, 6); // 8 the arguments "a" and "b" are formal argument names that are used in the function body, "return a...
Function.displayName - JavaScript
the function.displayname property returns the display name of the function. examples setting a displayname it is usually preferred by consoles and profilers over func.name to display the name of a function. ...
Function.prototype.toSource() - JavaScript
string representing the source code of the object. 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 object. syntax function.tosource(); return value a string representing the source code of the object. examples native functions for the built-in function object, tosource() returns the following string indicating that the source code is not available: function function() { [native code] } custom functions for custom functions, tosource() returns the javascript source that defines the object as a string. // for example: function hello() { console.log("hello, world!"); } hello.tosource(); // results in: "function hello() { console.log(\"hello, world!\"); }" specificatio...
Generator.prototype.next() - JavaScript
rator is past the end of the iterated sequence. in this case value optionally specifies the return value of the iterator. has the value false if the iterator was able to produce the next value in the sequence. this is equivalent of not specifying the done property altogether. value any javascript value returned by the iterator. can be omitted when done is true. ...
Generator.prototype.return() - JavaScript
the return() method returns the given value and finishes the generator. syntax gen.return(value) parameters value the value to return. return value the value that is given as an argument. examples using return() the following example shows a simple generator and the return method. function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.return('foo'); // { value: "foo", done: true } g.next(); // { value: undefined, done: true } if return(value) is called on a generator that is already in "completed" state, the generator will remain in "completed" state. if no argument is provided, the value property of returned object is the same as if .next(). if an argument is provided, it will be set to the value of the...
Generator.prototype.throw() - JavaScript
is past the end of the iterated sequence. in this case value optionally specifies the return value of the iterator. has the value false if the iterator was able to produce the next value in the sequence. this is equivalent of not specifying the done property altogether. value any javascript value returned by the iterator. can be omitted when done is true. examples using throw() the following example shows a simple generator and an error that is thrown using the throw method. an error can be caught by a try...catch block as usual. function* gen() { while(true) { try { yield 42; } catch(e) { console.log('error caught!'); } } } const g = gen(); g.next(); // { value: 42, done: false } g.throw(new error('something went wrong')); // "error caught!" // { va...
GeneratorFunction - JavaScript
object.getprototypeof(function*(){}).constructor syntax new generatorfunction ([arg1[, arg2[, ...argn]],] functionbody) parameters arg1, arg2, ... argn names to be used by the function as formal argument names. ...
Intl.Collator.prototype.resolvedOptions() - JavaScript
ub 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 collator.resolvedoptions() return value a new object with properties reflecting the locale and collation options computed during the initialization of the given collator object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 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. usage sensitivity ignorepunctuation the values provided for these properties in the options argument or filled i...
Intl.Collator.supportedLocalesOf() - JavaScript
tribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax intl.collator.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: 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. return value an array of strings representing a subset of the given locale tags that are supported in collation without having to fall back to the runtime's default locale. description returns...
Intl.Collator - JavaScript
back to the runtime's default locale. instance methods intl.collator.prototype.compare getter function that compares two strings according to the sort order of this intl.collator object. intl.collator.prototype.resolvedoptions() returns a new object with properties reflecting the locale and collation options computed during initialization of the object. ...
Intl.DateTimeFormat.prototype.formatRangeToParts() - 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 intl.datetimeformat.prototype.formatrangetoparts(startdate, enddate) examples basic formatrangetoparts usage this method receives two dates and returns an array of objects containing the locale-specific tokens representing each part of the formatted date range. ...
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
the intl.datetimeformat.prototype.formattoparts() method allows locale-aware formatting of strings produced by datetimeformat formatters. syntax datetimeformat.formattoparts(date) parameters date optional the date to format. return value an array of objects containing the formatted date in parts. description the formattoparts() method is useful for custom formatting of date strings. it returns an array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. the structure the formattoparts() method returns, looks like this: [ { type: 'day', value: '17' }, { type: 'weekday', value: 'monday' } ] possible types are the following: day the string used for the day, for example "17". dayperiod ...
Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript
e to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax datetimeformat.resolvedoptions() return value a new object with properties reflecting the locale and date and time formatting options computed during the initialization of the given datetimeformat object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 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. calendar e.g. "gregory" numberingsystem the values requested using the unicode extension keys "ca" and "nu" or f...
Intl.DateTimeFormat.supportedLocalesOf() - JavaScript
e to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax intl.datetimeformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: 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. return value an array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale. descr...
Intl.DateTimeFormat - JavaScript
d time zone america/los_angeles (utc-0800) using locales this example shows some of the variations in localized date and time formats. ...
Intl.DisplayNames.prototype.resolvedOptions() - JavaScript
ject with properties reflecting the locale and style formatting options computed during the construction of the current displaynames object. syntax displaynames.resolvedoptions() return value an object with properties reflecting the locale and formatting options computed during the construction of the given displaynames object. description the object returned by resolvedoptions() has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 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. style the value provided for this property in the options argument of the constructor or the default value ("long"...
Intl.DisplayNames.supportedLocalesOf() - JavaScript
provided locales that are supported in date and time formatting without having to fall back to the runtime's default locale. syntax intl.displaynames.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: 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. return value an array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale. descr...
Intl​.ListFormat.prototype​.format() - JavaScript
uage-specific formatted string representing the elements of the list description the format() method returns a string that has been formatted based on parameters provided in the intl.listformat object. the locales and options parameters customize the behavior of format() and let applications specify the language conventions that should be used to format the list. examples using format the following example shows how to create a list formatter using the english language. const list = ['motorcycle', 'bus', 'car']; console.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).format(list)); // > motorcycle, bus and car console.log(new intl.listformat('en-gb', { style: 'short', type: 'disjunction' }).format(list)); // > motorcycle, bus or car console.log(new intl.li...
Intl​.List​Format​.prototype​.resolvedOptions() - JavaScript
new object with properties reflecting the locale and style formatting options computed during the construction of the current listformat object. syntax listformat.resolvedoptions() return value an object with properties reflecting the locale and formatting options computed during the construction of the given listformat object. description the object returned by resolvedoptions() has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 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. style the value provided for this property in the options argument of the constructor or the default value ("long"...
Intl.ListFormat.supportedLocalesOf() - JavaScript
he provided locales that are supported in date and time formatting without having to fall back to the runtime's default locale. syntax intl.listformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: 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. return value an array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale. descr...
Intl.Locale.prototype.calendar - JavaScript
the intl.locale.prototype.calendar property is an accessor property which returns the type of calendar used in the locale. description the calendar property returns the part of the locale that indicates the locale's calendar era. while most of the world uses the gregorian calendar, there are several regional calendar eras used around the world. the following table shows all the valid unicode calendar key strings, along with a description of the calendar era they represent. unicode calendar keys unicode calendar keys calendar key (name) description buddhist thai buddhist calendar chinese traditional chinese calendar coptic coptic calendar dangi traditional korean calendar ethioaa ethiopic calendar, amete alem (ep...
Intl.Locale.prototype.collation - JavaScript
whenever strings must be sorted and placed into a certain order, from search query results to ordering records in a database. while the idea of placing strings in order might seem trivial, the idea of order can vary from region to region and language to language. the collation property helps to make it easier for javascript programmers to access the collation type used by a particular locale. below is a table with the available collation types, taken from the unicode collation specification. valid collation types collation type description big5han pinyin ordering for latin, big5 charset ordering for cjk characters (used in chinese) compat a previous version of the ordering, for compatibility dict dictionary style ordering (such as in sin...
Intl.Locale.prototype.hourCycle - JavaScript
used around the world: the 12 hour clock and the 24 hour clock. the hourcycle property makes it easier for javascript programmers to access the clock type used by a particular locale. like other additional locale data, hour cycle type is an extension subtag, which extends the data contained in a locale string. the hour cycle type can have several different values, which are listed in the table below. valid hour cycle types hour cycle type description h12 hour system using 1–12; corresponds to 'h' in patterns. the 12 hour clock, with midnight starting at 12:00 am. h23 hour system using 0–23; corresponds to 'h' in patterns. the 24 hour clock, with midnight starting at 0:00. h11 hour system using 0–11; corresponds to 'k' in patterns. t...
Intl.Locale.prototype.toString() - JavaScript
of a concept unicode locale identifier. information about a particular locale (language, script, calendar type, etc.) can be encoded in a locale identifier string. to make it easier to work with these locale identifiers, the locale object was introduced to javascript. calling the tostring method on a locale object will return the identifier string for that particular locale. the tostring method allows locale instances to be provided as an argument to existing intl constructors, serialized in json, or any other context where an exact string representation is useful. examples using tostring let mylocale = new intl.locale("fr-latn-fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // prints "fr-latn-fr" console.log(mylocale.tostring()); // prints "fr-latn-fr-u-ca-g...
Intl.Locale - JavaScript
unicode represents locales with a string, called a locale identifier. the locale identifier consists of a language identifier and extension tags. language identifiers are the core of the locale, consisting of language, script, and region subtags. additional information about the locale is stored in the optional extension tags. ...
Intl.NumberFormat.prototype.format() - JavaScript
ptions); console.log(numberformat.format(654321.987)); // → "654 321,99 руб." using format with map use the format getter function for formatting all numbers in an array. note that the function is bound to the numberformat from which it was obtained, so it can be passed directly to array.prototype.map. this is considered a historical artefact, as part of a convention which is no longer followed for new features, but is preserved to maintain compatibility with existing programs. var a = [123456.789, 987654.321, 456789.123]; var numberformat = new intl.numberformat('es-es'); var formatted = a.map(n => numberformat.format(n)); console.log(formatted.join('; ')); // → "123.456,789; 987.654,321; 456.789,123" specifications specification ecmascript internationalizat...
Intl.NumberFormat.supportedLocalesOf() - JavaScript
ute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax intl.numberformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: 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. return value an array of strings representing a subset of the given locale tags that are supported in number formatting without having to fall back to the runtime's default locale. description ...
Intl.PluralRules.supportedLocalesOf() - JavaScript
e of the provided locales that are supported in plural formatting without having to fall back to the runtime's default locale. syntax intl.pluralrules.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: 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. return value an array of strings representing a subset of the given locale tags that are supported in plural formatting without having to fall back to the runtime's default locale. description retur...
Intl.RelativeTimeFormat.supportedLocalesOf() - JavaScript
the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax intl.relativetimeformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: 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. return value an array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale. descr...
Map.prototype.set() - JavaScript
value the value of the element to add to the map object. return value the map object. examples using set() let mymap = new map() // add new elements to the map mymap.set('bar', 'foo') mymap.set(1, 'foobar') // update an element in the map mymap.set('bar', 'baz') using the set() with chaining since the set() method returns back the same map object, you can chain the method call like below: // add new elements to the map with chaining. mymap.set('bar', 'foo') .set(1, 'foobar') .set(2, 'baz'); specifications specification ecmascript (ecma-262)the definition of 'map.prototype.set' in that specification. ...
Math.E - JavaScript
les and send us a pull request. property attributes of math.e writable no enumerable no configurable no description because e is a static property of math, you always use it as math.e, rather than as a property of a math object you created (math is not a constructor). examples using math.e the following function returns e: function getnapier() { return math.e; } getnapier(); // 2.718281828459045 specifications specification ecmascript (ecma-262)the definition of 'math.e' in that specification. ...
Math.LN10 - JavaScript
us a pull request. property attributes of math.ln10 writable no enumerable no configurable no description because ln10 is a static property of math, you always use it as math.ln10, rather than as a property of a math object you created (math is not a constructor). examples using math.ln10 the following function returns the natural log of 10: function getnatlog10() { return math.ln10; } getnatlog10(); // 2.302585092994046 specifications specification ecmascript (ecma-262)the definition of 'math.ln10' in that specification. ...
Math.LN2 - JavaScript
send us a pull request. property attributes of math.ln2 writable no enumerable no configurable no description because ln2 is a static property of math, you always use it as math.ln2, rather than as a property of a math object you created (math is not a constructor). examples using math.ln2 the following function returns the natural log of 2: function getnatlog2() { return math.ln2; } getnatlog2(); // 0.6931471805599453 specifications specification ecmascript (ecma-262)the definition of 'math.ln2' in that specification. ...
Math.LOG10E - JavaScript
ll request. property attributes of math.log10e writable no enumerable no configurable no description because log10e is a static property of math, you always use it as math.log10e, rather than as a property of a math object you created (math is not a constructor). examples using math.log10e the following function returns the base 10 logarithm of e: function getlog10e() { return math.log10e; } getlog10e(); // 0.4342944819032518 specifications specification ecmascript (ecma-262)the definition of 'math.log10e' in that specification. ...
Math.LOG2E - JavaScript
a pull request. property attributes of math.log2e writable no enumerable no configurable no description because log2e is a static property of math, you always use it as math.log2e, rather than as a property of a math object you created (math is not a constructor). examples using math.log2e the following function returns the base 2 logarithm of e: function getlog2e() { return math.log2e; } getlog2e(); // 1.4426950408889634 specifications specification ecmascript (ecma-262)the definition of 'math.log2e' in that specification. ...
Math.PI - JavaScript
and send us a pull request. property attributes of math.pi writable no enumerable no configurable no description because pi is a static property of math, you always use it as math.pi, rather than as a property of a math object you created (math is not a constructor). examples using math.pi the following function uses math.pi to calculate the circumference of a circle with a passed radius. function calculatecircumference(radius) { return math.pi * (radius + radius); } calculatecircumference(1); // 6.283185307179586 specifications specification ecmascript (ecma-262)the definition of 'math.pi' in that specification. ...
Math.SQRT1_2 - JavaScript
equest. property attributes of math.sqrt1_2 writable no enumerable no configurable no description because sqrt1_2 is a static property of math, you always use it as math.sqrt1_2, rather than as a property of a math object you created (math is not a constructor). examples using math.sqrt1_2 the following function returns 1 over the square root of 2: function getroot1_2() { return math.sqrt1_2; } getroot1_2(); // 0.7071067811865476 specifications specification ecmascript (ecma-262)the definition of 'math.sqrt1_2' in that specification. ...
Math.SQRT2 - JavaScript
a pull request. property attributes of math.sqrt2 writable no enumerable no configurable no description because sqrt2 is a static property of math, you always use it as math.sqrt2, rather than as a property of a math object you created (math is not a constructor). examples using math.sqrt2 the following function returns the square root of 2: function getroot2() { return math.sqrt2; } getroot2(); // 1.4142135623730951 specifications specification ecmascript (ecma-262)the definition of 'math.sqrt2' in that specification. ...
Math.acosh() - JavaScript
e of the given number. if the number is less than 1, nan. description because acosh() is a static method of math, you always use it as math.acosh(), rather than as a method of a math object you created (math is no constructor). polyfill for all x≥1x \geq 1, we have arcosh(x)=ln(x+x2-1)\operatorname {arcosh} (x) = \ln \left(x + \sqrt{x^{2} - 1} \right) and so this can be emulated with the following function: math.acosh = math.acosh || function(x) { return math.log(x + math.sqrt(x * x - 1)); }; examples using math.acosh() math.acosh(-1); // nan math.acosh(0); // nan math.acosh(0.5); // nan math.acosh(1); // 0 math.acosh(2); // 1.3169578969248166 for values less than 1 math.acosh() returns nan. specifications specification ecmascript (ecma-262)the ...
Math.asinh() - JavaScript
github.com/mdn/interactive-examples and send us a pull request. syntax math.asinh(x) parameters x a number. return value the hyperbolic arcsine of the given number. description because asinh() is a static method of math, you always use it as math.asinh(), rather than as a method of a math object you created (math is not a constructor). ...
Math.atanh() - JavaScript
perbolic arctangent of the given number. description because atanh() is a static method of math, you always use it as math.atanh(), rather than as a method of a math object you created (math is not a constructor). polyfill for |x|<1\left|x\right| < 1, we have artanh(x)=12ln(1+x1-x)\operatorname {artanh} (x) = \frac{1}{2}\ln \left( \frac{1 + x}{1 - x} \right) so this can be emulated by the following function: math.atanh = math.atanh || function(x) { return math.log((1+x)/(1-x)) / 2; }; examples using math.atanh() math.atanh(-2); // nan math.atanh(-1); // -infinity math.atanh(0); // 0 math.atanh(0.5); // 0.5493061443340548 math.atanh(1); // infinity math.atanh(2); // nan for values greater than 1 or less than -1, nan is returned. specifications specification ...
Math.cbrt() - JavaScript
send us a pull request. syntax math.cbrt(x) parameters x a number. return value the cube root of the given number. description because cbrt() is a static method of math, you always use it as math.cbrt(), rather than as a method of a math object you created (math is not a constructor). ...
Math.ceil() - JavaScript
ub.com/mdn/interactive-examples and send us a pull request. syntax math.ceil(x) parameters x a number. return value the smallest integer greater than or equal to the given number. description because ceil() is a static method of math, you always use it as math.ceil(), rather than as a method of a math object you created (math is not a constructor). examples using math.ceil() the following example shows example usage of math.ceil(). math.ceil(.95); // 1 math.ceil(4); // 4 math.ceil(7.004); // 8 math.ceil(-0.95); // -0 math.ceil(-4); // -4 math.ceil(-7.004); // -7 decimal adjustment // closure (function() { /** * decimal adjustment of a number. * * @param {string} type the type of adjustment. * @param {number} value the number. * @param {inte...
Math.log() - JavaScript
s a static method of math, you always use it as math.log(), rather than as a method of a math object you created (math is not a constructor). if you need the natural log of 2 or 10, use the constants math.ln2 or math.ln10 . if you need a logarithm to base 2 or 10, use math.log2() or math.log10() . if you need a logarithm to other bases, use math.log(x) / math.log(otherbase) as in the example below; you might want to precalculate 1 / math.log(otherbase) . examples using math.log() math.log(-1); // nan, out of range math.log(0); // -infinity math.log(1); // 0 math.log(10); // 2.302585092994046 using math.log() with a different base the following function returns the logarithm of y with base x (ie. logxy\log_x y): function getbaselog(x, y) { return math.log(y) / math.log(x); } if...
Math.log10() - JavaScript
u created (math is not a constructor). this function is the equivalent of math.log(x) / math.log(10). for log10(e) use the constant math.log10e which is 1 / math.ln10. examples using math.log10() math.log10(2); // 0.3010299956639812 math.log10(1); // 0 math.log10(0); // -infinity math.log10(-2); // nan math.log10(100000); // 5 polyfill this can be emulated with the following function: math.log10 = math.log10 || function(x) { return math.log(x) * math.log10e; }; specifications specification ecmascript (ecma-262)the definition of 'math.log10' in that specification. ...
Math.log1p() - JavaScript
u will get a much more accurate answer 1.1111111110999995e-15 with 15 correct digits of precision (actually 16 in this case). if the value of x is less than -1, the return value is always nan. because log1p() is a static method of math, you always use it as math.log1p(), rather than as a method of a math object you created (math is not a constructor). ...
Math.max() - JavaScript
not be converted to a number, the result is nan. examples using math.max() math.max(10, 20); // 20 math.max(-10, -20); // -10 math.max(-10, 20); // 20 getting the maximum element of an array array.reduce() can be used to find the maximum element in a numeric array, by comparing each value: var arr = [1,2,3]; var max = arr.reduce(function(a, b) { return math.max(a, b); }); the following function uses function.prototype.apply() to get the maximum of an array. getmaxofarray([1, 2, 3]) is equivalent to math.max(1, 2, 3), but you can use getmaxofarray() on programmatically constructed arrays. this should only be used for arrays with relatively few elements. function getmaxofarray(numarray) { return math.max.apply(null, numarray); } the new spread operator is a shorter way of ...
Math.round() - JavaScript
eractive-examples and send us a pull request. syntax math.round(x) parameters x a number. return value the value of the given number rounded to the nearest integer. description if the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. if it is less than 0.5, the argument is rounded to the integer with the lower absolute value. if the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. note that this differs from many languages' round() functions, which often round this case to the next integer away from zero, instead giving a different result in the case of negative numbers with a fractional part of exactly 0.5. because round() is a static method...
Math.tan() - JavaScript
) method returns a numeric value that represents the tangent of the angle. because tan() is a static method of math, you always use it as math.tan(), rather than as a method of a math object you created (math is not a constructor). examples using math.tan() math.tan(1); // 1.5574077246549023 because the math.tan() function accepts radians, but it is often easier to work with degrees, the following function accepts a value in degrees, converts it to radians and returns the tangent. function gettandeg(deg) { var rad = deg * math.pi/180; return math.tan(rad); } specifications specification ecmascript (ecma-262)the definition of 'math.tan' in that specification. ...
Math - JavaScript
degrees * (math.pi / 180); }; function radtodeg(rad) { return rad / (math.pi / 180); }; calculating the height of an equalateral triangle if we want to calculate the height of an equalateral triangle, and we know its side length is 100, we can use the formulae length of the adjacent multiplied 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); ...
Number.MAX_VALUE - JavaScript
enumerable no configurable no description the max_value property has a value of approximately 1.79e+308, or 21024. values larger than max_value are represented as infinity. because max_value is a static property of number, you always use it as number.max_value, rather than as a property of a number object you created. examples using max_value the following code multiplies two numeric values. if the result is less than or equal to max_value, the func1 function is called; otherwise, the func2 function is called. if (num1 * num2 <= number.max_value) { func1(); } else { func2(); } specifications specification ecmascript (ecma-262)the definition of 'number.max_value' in that specification. ...
Number.MIN_VALUE - JavaScript
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. 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 >= num...
Number.NEGATIVE_INFINITY - JavaScript
the number.negative_infinity property to indicate an error condition that returns a finite 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 specificati...
Number.POSITIVE_INFINITY - JavaScript
the number.positive_infinity property to indicate an error condition that returns a finite number in case of success. note, however, that isfinite would be more appropriate in such a case. because positive_infinity is a static property of number, you always use it as number.positive_infinity, rather than as a property of a number object you created. examples using positive_infinity in the following example, the variable bignumber is assigned a value that is larger than the maximum value. when the if statement executes, bignumber has the value infinity, so bignumber is set to a more manageable value before continuing. var bignumber = number.max_value * 2; if (bignumber == number.positive_infinity) { bignumber = returnfinite(); } specifications specification ecmasc...
Number.isNaN() - JavaScript
le value comparisons in javascript. in comparison to the global isnan() function, number.isnan() doesn't suffer the problem of forcefully converting the parameter to a number. this means it is now safe to pass values that would normally convert to nan, but aren't actually the same value as nan. this also means that only values of the type number, that are also nan, return true. polyfill the following works because nan is the only value in javascript which is not equal to itself. number.isnan = number.isnan || function isnan(input) { return typeof input === 'number' && input !== input; } examples using isnan number.isnan(nan); // true number.isnan(number.nan); // true number.isnan(0 / 0); // true // e.g. these would have been true with global isnan() number.isnan('nan'...
Number.prototype.toExponential() - JavaScript
s to as many digits as necessary to specify the number. return value a string representing the given number object in exponential notation with one digit before the decimal point, rounded to fractiondigits digits after the decimal point. exceptions rangeerror if fractiondigits is too small or too large. values between 0 and 20, inclusive, will not cause a rangeerror. implementations are allowed to support larger and smaller values as well. typeerror if this method is invoked on an object that is not a number. description if the fractiondigits argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. if you use the toexponential() method for a numeric literal and the numeric literal has no exponen...
Number.prototype.toFixed() - JavaScript
is may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. if this argument is omitted, it is treated as 0. return value a string representing the given number using fixed-point notation. exceptions rangeerror if digits is too small or too large. values between 0 and 100, inclusive, will not cause a rangeerror. implementations are allowed to support larger and smaller values as chosen. typeerror if this method is invoked on an object that is not a number. description tofixed() returns a string representation of numobj that does not use exponential notation and has exactly digits digits after the decimal place. the number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the sp...
Number.prototype.toPrecision() - JavaScript
f rounding in the description of the number.prototype.tofixed() method, which also applies to toprecision(). if the precision argument is omitted, behaves as number.prototype.tostring(). if the precision argument is a non-integer value, it is rounded to the nearest integer. exceptions rangeerror if precision is not between 1 and 100 (inclusive), a rangeerror is thrown. implementations are allowed to support larger and smaller values as well. ecma-262 only requires a precision of up to 21 significant digits. examples using toprecision let numobj = 5.123456 console.log(numobj.toprecision()) // logs '5.123456' console.log(numobj.toprecision(5)) // logs '5.1235' console.log(numobj.toprecision(2)) // logs '5.1' console.log(numobj.toprecision(1)) // logs '5' numobj = 0.000123 ...
Number.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. syntax numobj.tosource() number.tosource() return value a string representing the source code of the object. examples native function for the built-in number object, tosource() returns the following string indicating that the source code is not available: function number() { [native code] } for instances of number, tosource() returns a string representing the source code. this method is usually called internally by javascript and not explicitly in web code. specifications not part of any standard. ...
Object() constructor - JavaScript
o the given value. if the value is an object already, it will return the value. when called in a non-constructor context, object behaves identically to new object(). syntax new object() new object(value) parameters value any value. examples creating a new object let o = new object() o.foo = 42 console.log(o) // object { foo: 42 } using object given undefined and null types the following examples store an empty object object in o: let o = new object() let o = new object(undefined) let o = new object(null) specifications specification ecmascript (ecma-262)the definition of 'object constructor' in that specification. ...
Object.prototype.__defineGetter__() - JavaScript
ves exist. the __definegetter__ method binds an object's property to a function to be called when that property is looked up. syntax obj.__definegetter__(prop, func) parameters prop a string containing the name of the property to bind to the given function. func a function to be bound to a lookup of the specified property. return value undefined. description the __definegetter__ allows a getter to be defined on a pre-existing object. examples non-standard and deprecated way var o = {}; o.__definegetter__('gimmefive', function() { return 5; }); console.log(o.gimmefive); // 5 standard-compliant ways // using the get operator var o = { get gimmefive() { return 5; } }; console.log(o.gimmefive); // 5 // using object.defineproperty var o = {}; object.defineproperty(o, 'gimmef...
Object.prototype.__defineSetter__() - JavaScript
ers prop a string containing the name of the property to be bound to the given function. fun a function to be called when there is an attempt to set the specified property. this function takes the form function(val) { . . . } val an alias for the variable that holds the value attempted to be assigned to prop. return value undefined. description the __definesetter__ method allows a setter to be defined on a pre-existing object. examples non-standard and deprecated way var o = {}; o.__definesetter__('value', function(val) { this.anothervalue = val; }); o.value = 5; console.log(o.value); // undefined console.log(o.anothervalue); // 5 standard-compliant ways // using the set operator var o = { set value(val) { this.anothervalue = val; } }; o.value = 5; console.log(o.v...
Object.getOwnPropertyDescriptor() - JavaScript
ts 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 descriptors only). writable true if and only if the value associated with the property may be changed (data descriptors only). get a function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). set a function which serves as a setter for the property, or undefined if ...
Object.is() - JavaScript
bject.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 == operator. the...
Object.prototype.isPrototypeOf() - JavaScript
not against afunction itself. syntax prototypeobj.isprototypeof(object) parameters object the object whose prototype chain will be searched. return value a boolean indicating whether the calling object lies in the prototype chain of the specified object. errors thrown typeerror a typeerror is thrown if prototypeobj is undefined or null. description the isprototypeof() method allows you to check whether or not an object exists within another object's prototype chain. examples using isprototypeof this example demonstrates that baz.prototype, bar.prototype, foo.prototype and object.prototype exist in the prototype chain for object baz: function foo() {} function bar() {} function baz() {} bar.prototype = object.create(foo.prototype); baz.prototype = object.create(bar.pro...
Object.keys() - JavaScript
perties of the given object. description object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. the ordering of the properties is the same as that given by looping over the properties of the object manually. ...
Object.prototype.propertyIsEnumerable() - JavaScript
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 = 'is enumerable'; a[0] = 'is enumerable'; o.propertyisenumerable('prop'); // returns true a.propertyisenumerable(0); // returns true user-defined vs. built-in objects the following example demonstrates the enumerability of user-defined vs. built-in properties: var a = ['is enumer...
Object.setPrototypeOf() - JavaScript
the object.setprototypeof() method sets the prototype (i.e., the internal [[prototype]] property) of a specified object to another object or null. warning: changing the [[prototype]] of an object is, by the nature of how modern javascript engines optimize property accesses, currently a very slow operation in every browser and javascript engine. in addition, the effects of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in the object.setprototypeof(...) statement, but may extend to any code that has access to any object whose [[prototype]] has been altered. because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). until engine developers address this issue, if you...
Object.prototype.toLocaleString() - JavaScript
he interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax obj.tolocalestring() return value a string representing the object. description object's tolocalestring returns the result of calling tostring(). this function is provided to give objects a generic tolocalestring method, even though not all may use it. see the list below. objects overriding tolocalestring array: array.prototype.tolocalestring() number: number.prototype.tolocalestring() date: date.prototype.tolocalestring() typedarray: typedarray.prototype.tolocalestring() bigint: bigint.prototype.tolocalestring() examples array tolocalestring() override on array objects, tolocalestring() can be used to print array values as a string, optionally with l...
Promise.race() - JavaScript
as the first promise that settles amongst the promises of the iterable passed as an argument. if the iterable passed is empty, the promise returned will be forever pending. if the iterable contains one or more non-promise value and/or an already settled promise, then promise.race will resolve to the first of these values found in the iterable. ...
Promise.resolve() - JavaScript
this function flattens nested layers of promise-like objects (e.g. a promise that resolves to a promise that resolves to something) into a single layer. ...
Proxy.revocable() - JavaScript
ler); parameters target a target object to wrap with proxy. it can be any sort of object, including a native array, a function, or even another proxy. handler an object whose properties are functions define the behavior of proxy p when an operation is performed on it. return value a newly created revocable proxy object is returned. description a revocable proxy is an object with following two properties {proxy: proxy, revoke: revoke}. proxy a proxy object created with new proxy(target, handler) call. revoke a function with no argument to invalidate (switch off) the proxy. if the revoke() function gets called, the proxy becomes unusable: any trap to a handler will throw a typeerror. once a proxy is revoked, it will remain revoked and can be garbage collected. calling rev...
RangeError() constructor - JavaScript
syntax new rangeerror([message[, filename[, linenumber]]]) parameters message optional human-readable description of the error. ...
Comparing Reflect and Object methods - JavaScript
the reflect object, introduced in es2015, is a built-in object that provides methods to interface with javascript objects. some of the static functions that exist on reflect also correspond to methods available on object, which predates es2015. although some of the methods appear to be similar in their behavior, there are often subtle differences between them. the table below details the differences between the methods available on the object and reflect apis. please note that if a method does not exist in an api, it is marked as n/a. method name object reflect defineproperty() object.defineproperty() returns the object that was passed to the function. returns a typeerror if the property was not successfully defined on the object. reflect.defineproperty() ...
Reflect.defineProperty() - JavaScript
ters target the target object on which to define the property. propertykey the name of the property to be defined or modified. attributes the attributes for the property being defined or modified. return value a boolean indicating whether or not the property was successfully defined. exceptions a typeerror, if target is not an object. description the reflect.defineproperty method allows precise addition to or modification of a property on an object. for more details, see the object.defineproperty which is similar. one key difference: object.defineproperty returns the object or throws a typeerror if the property has not been successfully defined. reflect.defineproperty, however, simply returns a boolean indicating whether or not the property was successfully defined. example...
Reflect.deleteProperty() - JavaScript
the static reflect.deleteproperty() method allows to delete properties. it is like the delete operator as a function. 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.deleteproperty(target, propertykey) parameters target the target object on which to delete the property. propertykey the name of the property to be deleted. return value a boolean indicating whether or not the property was successfully deleted. exceptions a typeerror, if target is not an object. description the reflect.deleteproperty method allows you to delete a property on an object. it returns a boolean indicating whet...
Reflect.get() - JavaScript
the target object on which to get the property. propertykey the name of the property to get. receiver optional the value of this provided for the call to target if a getter is encountered. when used with proxy, it can be an object that inherits from target. return value the value of the property. exceptions a typeerror, if target is not an object. description the reflect.get method allows you to get a property on an object. it is like the property accessor syntax as a function. examples using reflect.get() // object let obj = { x: 1, y: 2 } reflect.get(obj, 'x') // 1 // array reflect.get(['zero', 'one'], 1) // "one" // proxy with a get handler let x = {p: 1}; let obj = new proxy(x, { get(t, k, r) { return k + 'bar' } }) reflect.get(obj, 'foo') // "foobar" //prox...
Reflect.has() - JavaScript
.com/mdn/interactive-examples and send us a pull request. syntax reflect.has(target, propertykey) parameters target the target object in which to look for the property. propertykey the name of the property to check. return value a boolean indicating whether or not the target has the property. exceptions a typeerror, if target is not an object. description the reflect.has method allows you to check if a property is in an object. it works like the in operator as a function. examples using reflect.has() reflect.has({x: 0}, 'x') // true reflect.has({x: 0}, 'y') // false // returns true for properties in the prototype chain reflect.has({x: 0}, 'tostring') // proxy with .has() handler method obj = new proxy({}, { has(t, k) { return k.startswith('door') } }); reflect.has(o...
Reflect.isExtensible() - JavaScript
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. 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) // =...
Reflect.preventExtensions() - JavaScript
://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.preventextensions(target) parameters target the target object on which to prevent extensions. return value a boolean indicating whether or not the target was successfully set to prevent extensions. exceptions a typeerror, if target is not an object. description the reflect.preventextensions() method allows you to prevent new properties from ever being added to an object (i.e., prevents future extensions to the object). it is similar to object.preventextensions(). examples using reflect.preventextensions() see also object.preventextensions(). // objects are extensible by default. let empty = {} reflect.isextensible(empty) // === true // ...but that can be changed. reflect.preventextensions(em...
Reflect.set() - JavaScript
he target object on which to set the property. propertykey the name of the property to set. value the value to set. receiver optional the value of this provided for the call to target if a setter is encountered. return value a boolean indicating whether or not setting the property was successful. exceptions a typeerror, if target is not an object. description the reflect.set method allows you to set a property on an object. it does property assignment and is like the property accessor syntax as a function. examples using reflect.set() // object let obj = {} reflect.set(obj, 'prop', 'value') // true obj.prop // "value" // array let arr = ['duck', 'duck', 'duck'] reflect.set(arr, 2, 'goose') // true arr[2] // "goose" // it can truncate an array. reflect.set(arr, 'length', ...
Reflect - JavaScript
cript operations. the methods are the same as those of proxy handlers. reflect is not a function object, so it's not constructible. description unlike most global objects, reflect is not a constructor. you cannot use it with a new operator or invoke the reflect object as a function. all properties and methods of reflect are static (just like the math object). the reflect object provides the following static functions which have the same names as the proxy handler methods. some of these methods are also the same as corresponding methods on object, although they do have some subtle differences between them. static methods reflect.apply(target, thisargument, argumentslist) calls a target function with arguments as specified by the argumentslist parameter. see also function.prototype.app...
RegExp.prototype[@@match]() - JavaScript
s://github.com/mdn/interactive-examples and send us a pull request. syntax regexp[symbol.match](str) parameters str a string that is a target of the match. return value an array containing the entire match result and any parentheses-captured matched results, or null if there were no matches. description this method is called internally in string.prototype.match(). for example, the following two examples return same result. 'abc'.match(/a/); /a/[symbol.match]('abc'); this method exists for customizing match behavior within regexp subclasses. examples direct call this method can be used in almost the same way as string.prototype.match(), except the different this and the different arguments order. let re = /[0-9]+/g; let str = '2016-01-02'; let result = re[symbol.match](str)...
RegExp.prototype[@@matchAll]() - JavaScript
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 regexp[symbol.matchall](str) parameters str a string that is a target of the match. return value an iterator. description this method is called internally in string.prototype.matchall(). for example, the following two examples return same result. 'abc'.matchall(/a/); /a/[symbol.matchall]('abc'); this method exists for customizing the behavior of matchall() in regexp subclasses. examples direct call this method can be used in almost the same way as string.prototype.matchall(), except for the different value of this and the different order of arguments. let re = /[0-9]+/g; let str = '2016-01-02'; l...
RegExp.prototype[@@replace]() - JavaScript
create the new substring. the arguments supplied to this function are described in the specifying a function as a parameter section in string.prototype.replace() page. return value a new string with some or all matches of a pattern replaced by a replacement. description this method is called internally in string.prototype.replace() if the pattern argument is a regexp object. for example, following two examples return same result. 'abc'.replace(/a/, 'a'); /a/[symbol.replace]('abc', 'a'); this method exists for customizing replace behavior in regexp subclass. if pattern argument is not a regexp object, string.prototype.replace() doesn't call this method, nor creates a regexp object. examples direct call this method can be used in almost the same way as string.prototype.replace(), e...
RegExp.prototype[@@search]() - JavaScript
tive-examples and send us a pull request. syntax regexp[symbol.search](str) parameters str a string that is a target of the search. return value integer if successful, [@@search]() returns the index of the first match of the regular expression inside the string. otherwise, it returns -1. description this method is called internally in string.prototype.search(). for example, the following two examples return the same result. 'abc'.search(/a/); /a/[symbol.search]('abc'); this method exists for customizing the search behavior in regexp subclasses. examples direct call this method can be used in almost the same way as string.prototype.search(), except the different this and the different arguments order. var re = /-/g; var str = '2016-01-02'; var result = re[symbol.search](...
RegExp.prototype[@@split]() - JavaScript
match of this regexp pattern (or, in the syntax above, regexp), until the number of split items match the limit or the string falls short of this pattern. return value an array containing substrings as its elements. description this method is called internally in string.prototype.split() if its separator argument is an object that has a @@split method, such as a regexp. for example, the following two examples return the same result. 'a-b-c'.split(/-/); /-/[symbol.split]('a-b-c'); this method exists for customizing the behavior of split() in regexp subclass. examples direct call this method can be used in almost the same way as string.prototype.split(), except the different this and the different order of arguments. let re = /-/g; let str = '2016-01-02'; let result = re[symbol.sp...
RegExp.rightContext ($') - JavaScript
regexp.$' is an alias for this property. description the rightcontext property is static, it is not a property of an individual regular expression object. instead, you always use it as regexp.rightcontext or regexp["$'"]. the value of the rightcontext property is read-only and modified whenever a successful match is made. you can not use the shorthand alias with the dot property accessor (regexp.$'), because the parser expects a starting string in that case and a syntaxerror is thrown. ...
RegExp.prototype.sticky - JavaScript
the bug was introduced some time after firefox 3.6 (which had the sticky flag but not the bug) and fixed in 2015. perhaps because of the bug, the es2015 specification specifically calls out the fact that: when the y flag is used with a pattern, ^ always matches only at the beginning of the input,...
RegExp.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. syntax regexobj.tosource() return value a string representing the source code of the given regexp object. examples native function for the built-in regexp object, tosource() returns the following string indicating that the source code is not available: function regexp() { [native code] } for instances of regexp, tosource() returns a string representing the source code. this method is usually called internally by javascript and not explicitly in web code. specifications not part of any standard. ...
RegExp.prototype.toString() - JavaScript
ctive-examples and send us a pull request. syntax regexobj.tostring(); return value a string representing the given object. description the regexp object overrides the tostring() method of the object object; it does not inherit object.prototype.tostring(). for regexp objects, the tostring() method returns a string representation of the regular expression. ...
Set.prototype.delete() - JavaScript
lue returns true if value was successfully removed from myset; otherwise false. examples using the delete() method const myset = new set(); myset.add('foo'); myset.delete('bar'); // returns false. no "bar" element found to be deleted. myset.delete('foo'); // returns true. successfully removed. myset.has('foo'); // returns false. the "foo" element is no longer present. let's checkout below how to delete an object from a set. const setobj = new set(); // create a new set. setobj.add({x: 10, y: 20}); // add object in the set. setobj.add({x: 20, y: 30}); // add object in the set. // delete any point with `x > 10`. setobj.foreach(function(point){ if (point.x > 10){ setobj.delete(point) } }) specifications specification ecmascript (ecma-262)the def...
Set.prototype.forEach() - JavaScript
lue 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; it does not return a value. ...
String.prototype.big() - JavaScript
<big> html element that causes a string to be displayed in a big font. usage note: the <big> element has been removed in html5 and shouldn't be used anymore. instead web developers should use css properties. syntax str.big() return value a string containing a <big> html element. description the big() method embeds a string in a <big> tag: "<big>str</big>". ...
String.prototype.blink() - JavaScript
reates a <blink> html element that causes a string to blink. warning: blinking text is frowned upon by several accessibility standards. the <blink> element itself is non-standard and deprecated! syntax str.blink() return value a string containing a <blink> html element. description the blink() method embeds a string in a <blink> tag: "<blink>str</blink>". ...
String.prototype.bold() - JavaScript
the bold() method creates a <b> html element that causes a string to be displayed as bold. syntax str.bold() return value a string containing a <b> html element. description the bold() method embeds a string in a <b> tag: "<b>str</b>". examples using bold() the following example uses string methods to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.bold' in that specification. ...
String.prototype.concat() - JavaScript
tring arguments to the calling string and returns a new string. changes to the original string or the returned string don't affect the other. if the arguments are not of the type string, they are converted to string values before concatenating. performance it is strongly recommended that the assignment operators (+, +=) are used instead of the concat() method. examples using concat() the following example combines strings into a new string. let hello = 'hello, ' console.log(hello.concat('kevin', '. have a nice day.')) // hello, kevin. have a nice day. let greetlist = ['hello', ' ', 'venkat', '!'] "".concat(...greetlist) // "hello venkat!" "".concat({}) // [object object] "".concat([]) // "" "".concat(null) // "null" "".concat(true) // "true" "".concat(4, 5) // "45" speci...
String.prototype.endsWith() - JavaScript
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-sensitive. polyfill this method has been added to the ecmascript 6 specification and may not be available in all javascript implementations yet. ...
String.prototype.fixed() - JavaScript
the fixed() method creates a <tt> html element that causes a string to be displayed in fixed-pitch font. syntax str.fixed() return value a string representing a <tt> html element. description the fixed() method embeds a string in a <tt> tag: "<tt>str</tt>". examples using fixed() the following example uses the fixed method to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.fixed()); // "<tt>hello, world</tt>" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.fixed' in that specification. ...
String.prototype.fontcolor() - JavaScript
teral. string literals for color names are listed in the css color reference. return value a string containing a <font> html element. description if you express color as a hexadecimal rgb triplet, you must use the format rrggbb. for example, the hexadecimal rgb values for salmon are red=fa, green=80, and blue=72, so the rgb triplet for salmon is "fa8072". examples using fontcolor() the following example uses the fontcolor() method to change the color of a string by producing a string with the html <font> tag. var worldstring = 'hello, world'; console.log(worldstring.fontcolor('red') + ' is red in this line'); // '<font color="red">hello, world</font> is red in this line' console.log(worldstring.fontcolor('ff00') + ' is red in hexadecimal in this line'); // '<font color="ff00">hell...
String.prototype.fontsize() - JavaScript
1 and 7, a string representing a signed integer between 1 and 7. return value a string containing a <font> html element. description when you specify size as an integer, you set the font size of str to one of the 7 defined sizes. when you specify size as a string such as "-2", you adjust the font size of str relative to the size set in the <basefont> tag. ...
String.fromCharCode() - JavaScript
thematical relationship between the supplementary code point value (e.g. 0x1f303) and both surrogate values that represent it (e.g., 0xd83c and 0xdf03), it does require an extra step to either calculate or look up the surrogate pair values every time a supplementary code point is to be used. for this reason, it's more convenient to use string.fromcodepoint() (part of the es2015 standard), which allows for returning supplementary characters based on their actual code point value. for example, string.fromcodepoint(0x1f303) returns code point u+1f303 "night with stars". examples using fromcharcode() bmp characters, in utf-16, use a single code unit: string.fromcharcode(65, 66, 67); // returns "abc" string.fromcharcode(0x2014); // returns "—" string.fromcharcode(0x12014); // a...
String.prototype.includes() - JavaScript
. 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-sensitivity the includes() method is case sensitive. for example, the following expression returns false: 'blue whale'.includes('blue') // returns false polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. however, you can easily polyfill this method: if (!string.prototype.includes) { string.prototype.includes = function(search, start) { 'use strict'; if (search instanceo...
String.prototype.italics() - JavaScript
the italics() method creates an <i> html element that causes a string to be italic. syntax str.italics() return value a string containing a <i> html element. description the italics() method embeds a string in an <i> tag: "<i>str</i>". examples using italics() the following example uses string methods to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.italics' in that specification. ...
String.prototype.lastIndexOf() - JavaScript
exof('x'); // returns -1 'canal'.lastindexof('c', -5); // returns 0 'canal'.lastindexof('c', 0); // returns 0 'canal'.lastindexof(''); // returns 5 'canal'.lastindexof('', 2); // returns 2 note: 'abab'.lastindexof('ab', 2) will return 2 and not 0, as fromindex limits only the beginning of the match. 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 world'; console.log('the index of the first w from the beginning is ' + anystring.indexof('w')); // logs 8 console.log('the index...
String length - JavaScript
counts code units instead of characters, if you want to get the number of characters you need something like this: function getcharacterlength (str) { // the string iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getcharacterlength('a\ud87e\udc04z')); // 3 // while not recommended, you could add this to each string as follows: object.defineproperty(string.prototype, 'charlength', { get () { return getcharacterlength(this); } }); console.log('a\ud87e\udc04z'.charlength); // 3 examples basic usage let x = 'mozilla'; let empty = ''; console.log(x + ' is ' + x.length + ' code units long'); /* "mozilla is 7 code units long" */ console.log('the empty string has a length of ' + empty.length); // expected out...
String.prototype.link() - JavaScript
d as &quot;. return value a string containing an <a> html element. description use the link() method to create an html snippet for a hypertext link. the returned string can then be added to the document via document.write() or element.innerhtml. links created with the link() method become elements in the links array of the document object. see document.links. examples using link() the following example displays the word "mdn" as a hypertext link that returns the user to the mozilla developer network. var hottext = 'mdn'; var url = 'https://developer.mozilla.org/'; console.log('click to return to ' + hottext.link(url)); // click to return to <a href="https://developer.mozilla.org/">mdn</a> specifications specification ecmascript (ecma-262)the definition of 'stri...
String.prototype.padEnd() - JavaScript
tring. 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.padend(targetlength [, padstring]) parameters targetlength the length of the resulting string once the current str has been padded. if the value is lower than str.length, the current string will be returned as-is. padstring optional the string to pad the current str with. if padstring is too long to stay within targetlength, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. the default value for this parameter is " " (u+0020). return value a string of the spe...
String.raw() - JavaScript
'java' + 'script'); // 'foo5barjavascriptbaz' // notice the first argument is an object with a 'raw' property, // whose value is an iterable representing the separated strings // in the template literal. // the rest of the arguments are the substitutions. // the first argument’s 'raw' value can be any iterable, even a string! // for example, 'test' is treated as ['t', 'e', 's', 't']. // the following is equivalent to // `t${0}e${1}s${2}t`: string.raw({ raw: 'test' }, 0, 1, 2); // 't0e1s2t' specifications specification ecmascript (ecma-262)the definition of 'string.raw' in that specification. ...
String.prototype.search() - JavaScript
p). return value the index of the first match between the regular expression and the given string, or -1 if no match was found. description when you want to know whether a pattern is found, and also know its index within a string, use search(). (if you only want to know if it exists, use the similar test() method on the regexp prototype, which returns a boolean.) for more information (but slower execution) use match() (similar to the regular expression exec() method). examples using search() the following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1) let str = "hey jude" let re = /[a-z]/g let redot = /[.]/g console.log(str.search(re)) // returns 4, which is the index of the first capital le...
String.prototype.small() - JavaScript
the small() method creates a <small> html element that causes a string to be displayed in a small font. syntax str.small() return value a string containing a <small> html element. description the small() method embeds a string in a <small> tag: "<small>str</small>". ...
String.prototype.startsWith() - JavaScript
ters 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. ...
String.prototype.strike() - JavaScript
the strike() method creates a <strike> html element that causes a string to be displayed as struck-out text. syntax str.strike() return value a string containing a <strike> html element. description the strike() method embeds a string in a <strike> tag: "<strike>str</strike>". ...
String.prototype.sub() - JavaScript
the sub() method creates a <sub> html element that causes a string to be displayed as subscript. syntax str.sub() return value a string containing a <sub> html element. description the sub() method embeds a string in a <sub> tag: "<sub>str</sub>". examples using sub() and sup() methods the following example uses the sub() and sup() methods to format a string: var supertext = 'superscript'; var subtext = 'subscript'; console.log('this is what a ' + supertext.sup() + ' looks like.'); // this is what a <sup>superscript</sup> looks like console.log('this is what a ' + subtext.sub() + ' looks like.'); // this is what a <sub>subscript</sub> looks like. specifications specification ecmascript (ecma-262)the definition of 'string.prototype.sub' in that specification...
String.prototype.substr() - JavaScript
g. if length is omitted, substr() extracts characters to the end of the string. if length is undefined, substr() extracts characters to the end of the string. if length is a negative number, it is treated as 0. for both start and length, nan is treated as 0. polyfill microsoft's jscript does not support negative values for the start index. ...
String.prototype.sup() - JavaScript
the sup() method creates a <sup> html element that causes a string to be displayed as superscript. syntax str.sup() return value a string containing a <sup> html element. description the sup() method embeds a string in a <sup> tag: "<sup>str</sup>". ...
String.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. syntax string.tosource() str.tosource() return value a string representing the source code of the calling object. examples native function for the built-in string object, tosource() returns the following string indicating that the source code is not available: function string() { [native code] } for instances of string or string literals, tosource() returns a string representing the source code. this method is usually called internally by javascript and not explicitly in web code. specifications not part of any standard. ...
String.prototype.toString() - JavaScript
syntax str.tostring() return value a string representing the calling object. description the string object overrides the tostring() method of the object object; it does not inherit object.prototype.tostring(). for string objects, the tostring() method returns a string representation of the object and is the same as the string.prototype.valueof() method. examples using tostring() the following example displays the string value of a string object: var x = new string('hello world'); console.log(x.tostring()); // logs 'hello world' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tostring' in that specification. ...
String.prototype.trimEnd() - JavaScript
tespace from its right end. trimend() or trimright() do not affect the value of the string itself. aliasing for consistency with functions like string.prototype.padend the standard method name is trimend. however, for web compatibility reasons, trimright remains as an alias to trimend. in some engines this means: string.prototype.trimright.name === "trimend"; examples using trimend() the following example displays the lowercase string ' foo': var str = ' foo '; console.log(str.length); // 8 str = str.trimend(); console.log(str.length); // 6 console.log(str); // ' foo' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.trimend' in that specification. ...
Symbol() constructor - JavaScript
ng symbols to create a new primitive symbol, you write symbol() with an optional string as its description: let sym1 = symbol() let sym2 = symbol('foo') let sym3 = symbol('foo') the above code creates three new symbols. note that symbol("foo") does not coerce the string "foo" into a symbol. it creates a new symbol each time: symbol('foo') === symbol('foo') // false new symbol(...) the following syntax with the new operator will throw a typeerror: let sym = new symbol() // typeerror this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new boolean, new string and new number). if you really want to create a symbo...
Symbol.for() - JavaScript
ilable in a global symbol registry list. symbol.for() does also not necessarily create a new symbol on every call, but checks first if a symbol with the given key is already present in the registry. in that case, that symbol is returned. if no symbol with the given key is found, symbol.for() will create a new global symbol. global symbol registry the global symbol registry is a list with the following record structure and it is initialized empty: a record in the global symbol registry field name value [[key]] a string key used to identify a symbol. [[symbol]] a symbol that is stored globally. examples using symbol.for symbol.for('foo'); // create a new global symbol symbol.for('foo'); // retrieve the already created symbol // same global symbo...
Symbol.match - JavaScript
ow a typeerror if they are. now, if the match symbol is set to false (or a falsy value), it indicates that the object is not intended to be used as a regular expression object. property attributes of symbol.match writable no enumerable no configurable no examples disabling the isregexp check the following code will throw a typeerror: '/bar/'.startswith(/bar/); // throws typeerror, as /bar/ is a regular expression // and symbol.match is not modified. however, if you set symbol.match to false, the isregexp check (that uses the match property) will indicate that the object is not a regular expression object. the methods startswith and endswith won't throw a typeerror as a consequence. var re =...
Symbol.matchAll - JavaScript
led by the string.prototype.matchall() method. 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. description this symbol is used for string.prototype.matchall() and specifically in regexp.prototype[@@matchall](). the following two examples return same result: 'abc'.matchall(/a/); /a/[symbol.matchall]('abc'); this method exists for customizing match behavior within regexp subclasses. property attributes of symbol.matchall writable no enumerable no configurable no examples using symbol.matchall let re = /[0-9]+/g; l...
Symbol.search - JavaScript
teractive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. property attributes of symbol.search writable no enumerable no configurable no examples custom string search class caseinsensitivesearch { constructor(value) { this.value = value.tolowercase(); } [symbol.search](string) { return string.tolowercase().indexof(this.value); } } console.log('foobar'.search(new caseinsensitivesearch('bar'))); // expected output: 3 specifications specification ecmascript (ecma-262)the definition of 'symbol.search' in that specification. ...
Symbol.species - JavaScript
known symbol symbol.species specifies a function-valued property that the constructor function uses to create derived objects. 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. description the species accessor property allows subclasses to override the default constructor for objects. property attributes of symbol.species writable no enumerable no configurable no examples using species you might want to return array objects in your derived array class myarray. for example, when using methods such as map() that return t...
Symbol.toPrimitive - JavaScript
ing argument hint, which specifies the preferred type of the result primitive value. the hint argument can be one of "number", "string", and "default". property attributes of symbol.toprimitive writable no enumerable no configurable no examples modifying primitive values converted from an object following example describes how symbol.toprimitive property can modify the primitive value converted from an object. // an object without symbol.toprimitive property. var obj1 = {}; console.log(+obj1); // nan console.log(`${obj1}`); // "[object object]" console.log(obj1 + ''); // "[object object]" // an object with symbol.toprimitive property. var obj2 = { [symbol.toprimitive](hint) { if (hi...
Symbol.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. this method is usually called internally by javascript. syntax symbol.tosource() var sym = symbol() sym.tosource() return value a string representing the source code of the object. examples native function for the built-in symbol object, tosource returns the following string indicating that the source code is not available: "function symbol() { [native code] }" for instances of symbol, tosource returns a string representing the source code. "symbol()" specifications not part of any standard. ...
Symbol.unscopables - JavaScript
t unscopable and therefore it won't appear in lexical scope variables. setting a property to false will make it scopable and thus it will appear in lexical scope variables. property attributes of symbol.unscopables writable no enumerable no configurable no examples scoping in with statements the following code works fine in es5 and below. however, in ecmascript 2015 and later, the array.prototype.keys() method was introduced. that means that inside with environment "keys" would now be the method and not the variable. that's when the unscopables symbol was introduced. a built-in unscopables setting is implemented as array.prototype[@@unscopables] to prevent that some of the array methods are bei...
Symbol - JavaScript
ry for symbol. description to create a new primitive symbol, you write symbol() with an optional string as its description: let sym1 = symbol() let sym2 = symbol('foo') let sym3 = symbol('foo') the above code creates three new symbols. note that symbol("foo") does not coerce the string "foo" into a symbol. it creates a new symbol each time: symbol('foo') === symbol('foo') // false the following syntax with the new operator will throw a typeerror: let sym = new symbol() // typeerror this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new boolean, new string and new number). if you really want to create a symbo...
TypedArray.prototype.every() - JavaScript
ill 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(isbigenough); // false new uint8array([12, 54, 18, 130, 44]).every(isbigenough); // true testing typed array elements using arrow functions arrow functions provide a shorter syntax for the same test. ne...
TypedArray.prototype.fill() - JavaScript
ts value, start and end. the start and end arguments are optional with default values of 0 and the length of the this object. if start is negative, it is treated as length+start where length is the length of the array. if end is negative, it is treated as length+end. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as needed" basis. use the following "polyfill" along with the array.prototype.fill() polyfill. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill if (!uint8array.prototype.fill) { uint8array.prototype.fill = array.prototype.fill; } examples using fill new uint8array([1, 2, 3]).fill(4); // uint8array [4, 4, 4] new uint8array([1, 2, 3]).fill(4, 1); // uint8array [1, 4, 4] new uint8array([1, 2, 3...
TypedArray.prototype.filter() - JavaScript
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, or deleted, their value as passed to callback will be the value at the time filter() visits them; elements that are deleted are not visited. examples filtering out all small values the following example uses filter() to create a filtered typed array that has all elements with values less than 10 removed. function isbigenough(element, index, array) { return element >= 10; } new uint8array([12, 5, 8, 130, 44]).filter(isbigenough); // uint8array [ 12, 130, 44 ] filtering typed array elements using arrow functions arrow functions provide a shorter syntax for the same test. new uint...
TypedArray.prototype.find() - JavaScript
ck. elements that are appended to the typed array after the call to find begins will not be visited by callback. if an existing, unvisited element of the typed array is changed by callback, its value passed to the visiting callback will be the value at the time that find visits that element's index; elements that are deleted are not visited. examples find a prime number in a typed array the following example finds an element in the typed array that is a prime number (or returns undefined if there is no prime number). function isprime(element, index, array) { var start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } var uint8 = new uint8array([4, 5, 8, 12]); console.log(uint8.find(isprime)); // 5 specif...
TypedArray.prototype.findIndex() - JavaScript
function isprime(element, index, array) { var start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } var uint8 = new uint8array([4, 6, 8, 12]); var uint16 = new uint16array([4, 6, 7, 1...
TypedArray.prototype.forEach() - JavaScript
of existing elements of the typed array are changed, the value passed to callback will be the value at the time foreach() visits them; elements that are deleted before being visited are not visited. foreach() executes the callback function once for each typed array element; unlike every() and some() it, always returns the value undefined. ...
TypedArray.prototype.reduce() - JavaScript
the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax typedarray.reduce(callback[, initialvalue]) parameters callback function to execute on each value in the typed array, taking four arguments: previousvalue the value previously returned in the last invocation of the callback, or initialvalue, if supplied (see below). currentvalue the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the typed array reduce was called upon. initialvalue optional. object to use as the first argument to the first call of the callback. return value the value that results from the reduction. description the reduce method exec...
TypedArray.prototype.reduceRight() - JavaScript
method has the same algorithm as array.prototype.reduceright(). typedarray is one of the typed array types here. syntax typedarray.reduceright(callback[, initialvalue]) parameters callback function to execute on each value in the typed array, taking four arguments: previousvalue the value previously returned in the last invocation of the callback, or initialvalue, if supplied (see below). currentvalue the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the typed array reduce was called upon. initialvalue optional. object to use as the first argument to the first call of the callback. return value the value that results from the reduction. description the reduceright method...
TypedArray.prototype.some() - JavaScript
otype.some if (!uint8array.prototype.some) { object.defineproperty(uint8array.prototype, 'some', { value: array.prototype.some }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. examples testing size of all typed array elements the following example tests whether any element in the typed array is bigger than 10. function isbiggerthan10(element, index, array) { return element > 10; } new uint8array([2, 5, 8, 1, 4]).some(isbiggerthan10); // false new uint8array([12, 5, 8, 1, 4]).some(isbiggerthan10); // true testing typed array elements using arrow functions arrow functions provide a shorter syntax for the same test. new uint...
TypedArray.prototype.toString() - JavaScript
/github.com/mdn/interactive-examples and send us a pull request. syntax typedarray.tostring() return value a string representing the elements of the typed array. examples the typedarray objects override the tostring method of object. for typedarray objects, the tostring method joins the array and returns one string containing each typed array element separated by commas. for example, the following code creates a typed array and uses tostring to convert the array to a string. var numbers = new uint8array([2, 5, 8, 1, 4]) numbers.tostring(); // "2,5,8,1,4" javascript calls the tostring method automatically when a typed array is to be represented as a text value or when an array is referred to in a string concatenation. compatibility if a browser doesn't support the typedarray.prototy...
WeakMap - JavaScript
a symbol can't be a weakmap key). ...
WeakRef - JavaScript
object from being reclaimed by the garbage collector. in contrast, a normal (or strong) reference keeps an object in memory. when an object no longer has any strong references to it, the javascript engine's garbage collector may destroy the object and reclaim its memory. if that happens, you can't get the object from a weak reference anymore. note: please see the avoid where possible section below. correct use of weakref takes careful thought, and it's best avoided if possible. constructor weakref() creates a new weakref object. instance methods weakref.prototype.deref() returns the weakref object's target object, or undefined if the target object has been reclaimed. avoid where possible correct use of weakref takes careful thought, and it's best avoided if possible. it's al...
WebAssembly.CompileError() constructor - JavaScript
ebassembly decoding or validation. syntax new webassembly.compileerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
WebAssembly.CompileError - JavaScript
bassembly.compileerror.prototype.stack stack trace. inherited from error. instance methods webassembly.compileerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.compileerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. ...
WebAssembly.Instance.prototype.exports - JavaScript
instance.exports examples using exports after fetching some webassembly bytecode using fetch, we compile and instantiate the module using the webassembly.instantiatestreaming() function, importing a javascript function into the webassembly module in the process. we then call an exported webassembly function that is exported by the instance. ...
WebAssembly.LinkError() constructor - JavaScript
(besides traps from the start function). syntax new webassembly.linkerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
WebAssembly.LinkError - JavaScript
m error. webassembly.linkerror.prototype.stack stack trace. inherited from error. instance methods webassembly.linkerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.linkerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. ...
WebAssembly.Memory.prototype.buffer - JavaScript
it then stores some values in that memory, then exports a function and uses it to sum some values. ...
WebAssembly.Memory.prototype.grow() - JavaScript
the grow() protoype method of the memory object increases the size of the memory instance by a specified number of webassembly pages. syntax memory.grow(number); parameters number the number of webassembly pages you want to grow the memory by (each one is 64kib in size). return value the previous size of the memory, in units of webassembly pages. examples using grow the following example creates a new webassembly memory instance with an initial size of 1 page (64kib), and a maximum size of 10 pages (640kib). var memory = new webassembly.memory({initial:1, maximum:10}); we can then grow the instance by one page like so: const bytesperpage = 64 * 1024; console.log(memory.buffer.bytelength / bytesperpage); // "1" console.log(memory.grow(1)); // "1" co...
WebAssembly.Module.exports() - JavaScript
rray containing descriptions of all the declared exports of the given module. syntax webassembly.module.exports(module); parameters module a webassembly.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 def...
WebAssembly.Module.imports() - JavaScript
rray containing descriptions of all the declared imports of the given module. syntax webassembly.module.imports(module); parameters module a webassembly.module object. 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" } spec...
WebAssembly.Module - JavaScript
and string, returns a copy of the contents of all custom sections in the module with the given string name. webassembly.module.exports() given a module, returns 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 ...
WebAssembly.RuntimeError() constructor - JavaScript
ever webassembly specifies a trap. syntax new webassembly.runtimeerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
WebAssembly.RuntimeError - JavaScript
bassembly.runtimeerror.prototype.stack stack trace. inherited from error. instance methods webassembly.runtimeerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.runtimeerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. ...
WebAssembly.Table.prototype.get() - JavaScript
ce stored at a given index. syntax table.get(index); parameters index the index of the function reference you want to retrieve. return value a function 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. 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...
WebAssembly.Table.prototype.length - JavaScript
the length prototype property of the webassembly.table object returns the length of the table, i.e. the number of elements in the table. syntax table.length; examples using length the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10. var table = new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification webassembly javascript interfacethe definition of 'length' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like ...
WebAssembly.Table.prototype.set() - JavaScript
te. value the value you want to mutate the reference to. this must be an exported webassembly function, a javascript wrapper for an underlying wasm function. return value void. exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown. if value is not an exported webassembly function or null, a typeerror is thrown. examples using table.set the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 references. we then print out the table length and contents of the two indexes (retrieved via table.prototype.get()) to show that the length is two, and the indexes currently contain no function references (they currently return null). var tbl = new webassembly.table({init...
WebAssembly.Table - JavaScript
th of the table, i.e. the number of elements. instance methods table.prototype.get() accessor function — gets the element stored at a given index. table.prototype.grow() increases the size of the table instance by a specified number of elements. table.prototype.set() sets an element stored at a given index to a given value. examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements. we then print out the table length and contents of the two indexes (retrieved via table.prototype.get() to show that the length is two and both elements are null. var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" co...
WebAssembly.compile() - JavaScript
ffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile. 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. if compilation fails, the promise rejects with a webassembly.compileerror. examples using compile the following example compiles the loaded simple.wasm byte code using the compile() function and then sends it to a worker using postmessage(). 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 ...
WebAssembly.compileStreaming() - JavaScript
l fulfill with one, representing the underlying source of a .wasm module you want to stream and compile. 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. if compilation fails, the promise rejects with a webassembly.compileerror. examples compile streaming the following example (see our compile-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles it to a webassembly.module object. because the compilestreaming() function accepts a promise for a response object, you can directly pass it a windoworworkerglobalscope.fetch() call, and it will pass the response into the function when it fulfi...
WebAssembly.instantiateStreaming() - JavaScript
ssembly.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. examples instantiating streaming the following example (see our instantiate-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a resultobject. because the instantiatestreaming() function accepts a promise for a response object, you can directly pass it a windoworworkerglobalscope.fetch() call, and it will pass the re...
WebAssembly.validate() - JavaScript
) or not (false). syntax webassembly.validate(buffersource); parameters buffersource a typed array or arraybuffer containing webassembly binary code to be validated. return value a boolean that specifies whether buffersource is valid wasm code (true) or not (false). exceptions if buffersource is not a typed array or arraybuffer, a typeerror is thrown. examples using validate the following example (see the validate.html source code, and see it live too) fetches a .wasm module and converts it into a typed array. the validate() method is then used to check whether the module is valid. fetch('simple.wasm').then(response => response.arraybuffer() ).then(function(bytes) { var valid = webassembly.validate(bytes); console.log("the given bytes are " + (valid ? "" : "not ") + ...
escape() - JavaScript
absence of legacy usage would be removed from this specification. … … programmers should not use or assume the existence of these features and behaviours when writing new ecmascript code. … the escape() function computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. note: this function was used mostly for url queries (the part of a url following ?)—not for escaping ordinary string literals, which use the format "\xhh". (hh are two hexadecimal digits, and the form \xhh\xhh is used for higher-plane unicode characters.) escaped characters in string literals can be expanded by replacing the \x with %, then using the decodeuricomponent() function. syntax escape(str) parameters str a string to be encoded. return value a new st...
isNaN() - JavaScript
lues 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 values for which no primitive numeric value is available. for example, 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...
undefined - JavaScript
/ 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, while strict equality doesn't. this is because n...
Addition assignment (+=) - JavaScript
dition 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. ...
Assignment (=) - JavaScript
nment 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. ...
Bitwise AND (&) - JavaScript
ed 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 a & b description the operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). numbers with more than 32 bits get their most significant bits discarded. for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. the operator is applied to each pair of bits, and the result is co...
Bitwise NOT (~) - JavaScript
tored 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 ~a description the operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). numbers with more than 32 bits get their most significant bits discarded. for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. the operator is applied to each pair of bits, and the result is co...
Bitwise OR (|) - JavaScript
ed 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 a | b description the operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). numbers with more than 32 bits get their most significant bits discarded. for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. the operator is applied to each pair of bits, and the result is co...
Bitwise XOR (^) - JavaScript
ed 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 a ^ b description the operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). numbers with more than 32 bits get their most significant bits discarded. for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. the operator is applied to each pair of bits, and the result is co...
Division assignment (/=) - JavaScript
e 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
ption the exponentiation operator is right-associative: a ** b ** c is equal to a ** (b ** c). in most languages, such as php, python, and others that have an exponentiation operator (**), the exponentiation operator is defined to have a higher precedence than unary operators, such as unary + and unary -, but there are a few exceptions. for example, in bash, the ** operator is defined to have a lower precedence than unary operators. in javascript, it is impossible to 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 javascr...
Exponentiation assignment (**=) - JavaScript
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. ...
Grouping operator ( ) - JavaScript
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 ( ) description the grouping operator consists of a pair of parentheses around an expression or sub-expression to override the normal operator precedence so that expressions with lower precedence can be evaluated before an expression with higher priority. as it sounds, it groups what's inside of the parentheses. examples using the grouping operator overriding multiplication and division first, then addition and subtraction to evaluate addition first. var a = 1; var b = 2; var c = 3; // default precedence a + b * c // 7 // evaluated by default like this a + (b * c) ...
Inequality (!=) - JavaScript
e of different 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 x != y description the inequality operator checks whether its operands are not equal. it is the negation of the equality operator so the following two lines will always give the same result: x != y !(x == y) for details of the comparison algorithm, see the page for the equality operator. like the equality operator, the inequality operator will attempt to convert and compare operands of different types: 3 != "3"; // false to prevent this, and require that different types are considered to be different, use the strict inequality oper...
Less than (<) - JavaScript
ight operand, and false otherwise. 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 x < y description the operands are compared using the abstract relational comparison algorithm, which is roughly summarised below: first, objects are converted to primitives using symbol.toprimitive. if both values are strings, they are compared as strings, based on the values of the unicode code points they contain. otherwise javascript attempts to convert non-numeric types to numeric values: boolean values true and false are converted to 1 and 0 respectively. null is converted to 0. undefined is converted...
Logical OR assignment (||=) - JavaScript
ns 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. examples setting default content if the "lyrics" element is empty, set the innerhtml to a default value: document.getelementbyid('lyrics').innerhtml ||= '<i>no lyrics.</i>' here the short-circuit is especially beneficial, since the element will no...
Multiplication assignment (*=) - JavaScript
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. ...
Nullish coalescing operator (??) - JavaScript
ide operand is null or undefined, and otherwise returns its left-hand side operand. contrary to the logical or (||) operator, the left operand is returned if it is a falsy value which is not null or undefined. in other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors if you consider some falsy values as usable (eg. '' or 0). see below for more examples. 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. see pr #1482 regarding the addition of this example. syntax leftexpr ?? rightexpr examples using the nullish coalescing operator in this example, ...
Optional chaining (?.) - JavaScript
te of obj.first before trying to access obj.first.second: let nestedprop = obj.first?.second; by using the ?. operator instead of just ., javascript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second. if obj.first is null or undefined, the expression automatically short-circuits, returning undefined. this is equivalent to the following, except that the temporary variable is in fact not created: let temp = obj.first; let nestedprop = ((temp === null || temp === undefined) ? undefined : temp.second); optional chaining with function calls you can use optional chaining when attempting to call a method which may not exist. this can be helpful, for example, when using an api in which a method might be unavailable, either due t...
Pipeline operator (|>) - JavaScript
the result is syntactic sugar in which a function call with a single argument can be written like this: let url = "%21" |> decodeuri; the equivalent call in traditional syntax looks like this: let url = decodeuri("%21"); syntax expression |> function the value of the specified expression is passed into the function as its sole parameter. parameters expression any valid expression. function any function. ...
Remainder assignment (%=) - JavaScript
e 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. ...
Strict inequality (!==) - JavaScript
erent. 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 x !== y description the strict inequality operator checks whether its operands are not equal. it is the negation of the strict equality operator so the following two lines will always give the same result: x !== y !(x === y) for details of the comparison algorithm, see the page for the strict equality operator. like the strict equality operator, the strict inequality operator will always consider operands of different types to be different: 3 !== "3"; // true examples comparing operands of the same type console.log("hello" !== "hello"); // fa...
Subtraction assignment (-=) - JavaScript
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
description the await expression causes async function execution to pause until a promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. when resumed, the value of the await expression is that of the fulfilled promise. if the promise is rejected, the await expression throws the rejected value. if the value of the expression following the await operator is not a promise, it's converted to a resolved promise. an await 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 th...
function* expression - JavaScript
tion. description a function* expression is very similar to and has almost the same syntax as a function* statement. the main difference between a function* expression and a function* statement is the function name, which can be omitted in function* expressions to create anonymous generator functions. see also the chapter about functions for more information. examples using function* the following example defines an unnamed generator function and assigns it to x. the function yields the square of its argument: let x = function*(y) { yield y * y; }; specifications specification ecmascript (ecma-262)the definition of 'function*' in that specification. ...
in operator - JavaScript
ctive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax prop in object parameters prop a string or symbol representing a property name or array index (non-symbols will be coerced to strings). object object to check if it (or its prototype chain) contains the property with specified name (prop). examples basic usage the following examples show some uses of the in operator. // arrays let trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'] 0 in trees // returns true 3 in trees // returns true 6 in trees // returns false 'bay' in trees // returns false (you must specify the index number, not the value at that index) 'length' in trees // returns true (length is an array property) symbol.iterator in...
yield* - JavaScript
mples and send us a pull request. syntax yield* expression; expression the expression which returns an iterable object. description the yield* expression iterates over the operand and yields each value returned by it. the value of yield* expression itself is the value returned by that iterator when it's closed (i.e., when done is true). examples delegating to another generator in following code, values yielded by g1() are returned from next() calls just like those which are yielded by g2(). function* g1() { yield 2; yield 3; yield 4; } function* g2() { yield 1; yield* g1(); yield 5; } const iterator = g2(); console.log(iterator.next()); // {value: 1, done: false} console.log(iterator.next()); // {value: 2, done: false} console.log(iterator.next()); // {value: 3, ...
block - JavaScript
ve-examples and send us a pull request. syntax block statement { statementlist } labelled block statement labelidentifier: { statementlist } statementlist statements grouped within the block statement. labelidentifier an optional label for visual identification or as a target for break. description the block statement is often called compound statement in other languages. it allows you to use multiple statements where javascript expects only one statement. combining statements into blocks is a common practice in javascript. the opposite behavior is possible using an empty statement, where you provide no statement, although one is required. blocks are commonly used in association with if...else and for statements. examples block scoping rules with var or function declara...
debugger - JavaScript
function potentiallybuggycode() { debugger; // do potentially buggy stuff to examine, step through, etc. ...
do...while - JavaScript
is executed at least once and is re-executed each time the condition evaluates to true. to execute multiple statements within the loop, use a block statement ({ ... }) to group those statements. condition an expression evaluated after each pass through the loop. if condition evaluates to true, the statement is re-executed. when condition evaluates to false, control passes to the statement following the do...while. examples using do...while in the following example, the do...while loop iterates at least once and reiterates until i is no longer less than 5. var result = ''; var i = 0; do { i += 1; result += i + ' '; } while (i > 0 && i < 5); // despite i == 0 this will still loop as it starts off without the test console.log(result); specifications specification ...
function* - 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. you can also define generator functions using the generatorfunction constructor, or the function expression syntax. syntax function* name([param[, param[, ... param]]]) { statements } name the function name. param optional the name of a formal parameter for the function. statements the statements comprising the body of the function. ...
function declaration - JavaScript
n javascript are hoisted to the top of the enclosing function or global scope. you can use the function before you declared it: hoisted(); // logs "foo" function hoisted() { console.log('foo'); } note that function expressions are not hoisted: nothoisted(); // typeerror: nothoisted is not a function var nothoisted = function() { console.log('bar'); }; examples using function the following code declares a function that returns the total amount of sales, when given the number of units sold of products a, b, and c. function calc_sales(units_a, units_b, units_c) { return units_a * 79 + units_b * 129 + units_c * 699; } specifications specification ecmascript (ecma-262)the definition of 'function definitions' in that specification. ...
if...else - JavaScript
ver, you can write it with a space between else and if: if (x > 50) { /* do something */ } else if (x > 5) { /* do something */ } else { /* do something */ } assignment within the conditional expression it is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. for example, do not use the following code: if (x = y) { /* do something */ } if you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. for example: if ((x = y)) { /* do something */ } specifications specification ecmascript (ecma-262)the definition of 'if statement' in that specification. ...
var - JavaScript
var varname1 [= value1] [, varname2 [= value2] ... [, varnamen [= valuen]]]; varnamen variable name. it can be any legal identifier. valuen optional initial value of the variable. it can be any legal expression. default value is undefined. description var declarations, wherever they occur, are processed before any code is executed. this is called hoisting, and is discussed further below. the scope of a variable declared with var is its current execution context and closures thereof, which is either the enclosing function and functions declared within it, or, for variables declared outside any function, global. duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value, unless another assignment is performed...
Transitioning to strict mode - JavaScript
requires a bit more work. this article aims at providing guidance for developers. gradual transition strict mode has been designed so that the transition to it can be made gradually. it is possible to change each file individually and even to transition code to strict mode down to the function granularity. ...
JavaScript reference - JavaScript
format intl.displaynames intl.listformat intl.locale intl.numberformat intl.pluralrules intl.relativetimeformat webassembly webassembly webassembly.module webassembly.instance webassembly.memory webassembly.table webassembly.compileerror webassembly.linkerror webassembly.runtimeerror statements javascript statements and declarations control flowblock break continue empty if...else switch throw try...catch declarations var let const functions and classes function function* async function return class iterations do...while for for each...in for...in for...of for await...of while other debugger import label with expressions and operators javascript express...
categories - Web app manifests
an array of strings defining the names of categories that the application supposedly belongs to. there is no standard list of possible values, but the w3c maintains a list of known categories. note: categories are used only as hints for catalogs or stores listing web applications. like search engines and meta keywords, catalogs and stores are free to ignore them. note: categories values are lower-cased by the stores and catalogs before processing, so "news" and "news" are treated as the same value. developers are encouraged to use lower case in the first place. example "categories": ["books", "education", "medical"] specification specification status comment feedback web app manifestthe definition of 'categories' in that specification. ...
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...
orientation - Web app manifests
ember defines the default orientation for all the website's top-level browsing contexts. note: orientation and/or its specific values might not be supported by a user agent on various display modes because supporting them does not make sense for the particular context. note: the orientation can be changed at runtime via the screen orientation api. values orientation can take one of the following values: any natural landscape landscape-primary landscape-secondary portrait portrait-primary portrait-secondary examples "orientation": "portrait-primary" specification specification status comment feedback web app manifestthe definition of 'orientation' in that specification. working draft initial definition. ...
related_applications - Web app manifests
ation by setting prefer_related_applications to true. examples "related_applications": [ { "platform": "play", "url": "https://play.google.com/store/apps/details?id=com.example.app1", "id": "com.example.app1" }, { "platform": "itunes", "url": "https://itunes.apple.com/app/example-app1/id123456789" } ] related application values application objects may contain the following values: member description platform the platform on which the application can be found. list of available values url the url at which the application can be found. id the id used to represent the application on the specified platform. specification specification status comment feedback web app manifestt...
scope - Web app manifests
web application's application context. it restricts what web pages can be viewed while the manifest is applied. if the user navigates outside the scope, it reverts to a normal web page inside a browser tab or window. if the scope is a relative url, the base url will be the url of the manifest. examples if the scope is relative, the manifest url is used as a base url: "scope": "/app/" the following scope limits navigation to the current site: "scope": "https://example.com/" finally, the following example limits navigation to a subdirectory of the current site: "scope": "https://example.com/subdirectory/" specification specification status comment feedback web app manifestthe definition of 'scope' in that specification. working draft ...
serviceworker - Web app manifests
type object mandatory no the serviceworker member describes a service worker that the developer intends to install to control the pwa. examples "serviceworker": { "src": "./serviceworker.js", "scope": "/app", "type": "", "update_via_cache": "none" } values service worker contain the following values (only src is required): member description src the url to download the service worker script from. this is the only required member of the serviceworker member. scope a string representing a url that defines a service worker's registration scope; that is, what range of urls a service worker can control. this is usually a relative url, relative to the base url of the application. by default, the scope value for ...
shortcuts - Web app manifests
mandatory no the shortcuts member defines an array of shortcuts or links to key tasks or pages within a web app. a user agent can use these values to assemble a context menu to be displayed by the operating system when a user engages with the web app's icon. when user invokes a shortcut, the user agent will navigate to the address given by shortcut's url member. ...
start_url - Web app manifests
tring mandatory no the start_url member is a string that represents the start url of the web application — the prefered url that should be loaded when the user launches the web application (e.g., when the user taps on the web application's icon from a device's application menu or homescreen). note: the start_url member is purely advisory, and a user agent may ignore it or allow the user to alter it at install time or afterwards. examples absolute url "start_url": "https://example.com" relative url if the url is relative, the manifest url is used as the base url to resolve it. "start_url": "../startpoint.html" specification specification status comment feedback web app manifestthe definition of 'start_url' in that specificatio...
Web app manifests
aded and be presented to the user similarly to a native app (e.g., be installed on the homescreen of a device, providing users with quicker access and a richer experience). pwa manifests include its name, author, icon(s), version, description, and list of all the necessary resources (among other things). can pwa manifest contain comments? it is a json-formatted file, with one exception: it is allowed to contain "//"-style comments. members web manifests can contain the following keys. click each one for more information about it: background_colorcategoriesdescriptiondirdisplayiarc_rating_idiconslangnameorientationprefer_related_applicationsrelated_applicationsscopescreenshotsserviceworkershort_nameshortcutsstart_urltheme_color example manifest { "name": "hackerweb", "short_name": ...
Values - MathML
elative unit. (the "x"-height of the element, 1ex ≈ 0.5em in many fonts) px pixels in inches (1 inch = 2.54 centimeters) cm centimeters mm millimeters pt points (1 point = 1/72 inch) pc picas (1 pica = 12 points) % percentage of the default value. ...
<maction> - MathML
tylesheets. 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 and also the fraction line color. you can use #rgb, #rrggbb and html color names. selection the child element which is addressed by the action. the default value is 1, which is the first child element. ...
<menclose> - MathML
a2 + b2 box roundedbox a2 + b2 rounded box circle a2 + b2 circle left a2 + b2 line to the left of the contents right a2 + b2 line to the right of the contents top a2 + b2 line above of the contents bottom a2 + b2 line below of the contents updiagonalstrike a2 + b2 strikeout line through contents from lower left to upper right downdiagonalstrike a2 + b2 strikeout line through contents from upper left to lower right verticalstrike a2 + b2 vertical strikeout line through contents horizontalstrike a2 + b2 ...
<mover> - MathML
Web › MathML › Element › mover
if false (default value) the over-script is a limit over the base expression. align the alignment of the over-script. possible values are: left, center, and right. this attribute is deprecated and will be removed in the future. use css text-align instead. 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. ...
<mpadded> - MathML
s: any length or an increment/decrement (a length prefixed with "+" or "-") . pseudo-units it is possible to use the keywords "depth", "height", and "width" as a pseudo-unit for the attributes depth, height, lspace, voffset, and width. they represent each length of the same-named dimension. prior to gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) the mathml2 pseudo-unit lspace was allowed, which is no longer present in the mathml3 recommendation and has been removed now. examples <math> <mpadded height="+150px" width="100px" lspace="2height"> <mi> x </mi> <mo> + </mo> <mi> y </mi> </mpadded> </math> specifications specification status comment mathml 3.0the definition of 'mpadded' in that specification. recommendation curre...
<mrow> - MathML
Web › MathML › Element › mrow
s (such as <mi> and <mn>). this element renders as a horizontal row containing its arguments. when writing a mathml expression, you should group elements within an <mrow> in the same way as they are grouped in the mathematical interpretation of the expression. proper grouping helps the rendering of the expression in several ways: it can improve the display by possibly affecting spacing. it allows for more intelligent line-breaking and indentation. it simplifies the interpretation of the expression by automated systems such as computer algebra systems and audio renderers. attributes class, id, style provided for use with stylesheets. dir overall directionality of formulas. possible values are either ltr (left to right) or rtl (right to left). href used to set a hyperlink to a s...
<mspace> - MathML
Web › MathML › Element › mspace
height the desired height (above the baseline) of the space (see length for values and units). linebreak indicates a line-break at the space. possible values: auto (default value), newline, nobreak, goodbreak, badbreak. starting with mathml 3, it is preferred to use <mo> to control linebreaking. mathbackground the background color. ...
<msqrt> - MathML
Web › MathML › Element › msqrt
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 and also the color of the root symbol itself. you can use #rgb, #rrggbb and html color names. ...
<msup> - MathML
Web › MathML › Element › 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. ...
<munder> - MathML
Web › MathML › Element › munder
if false (default value), the element is a limit under the base expression. align the alignment of the underscript. possible values are: left, center, and right. this attribute is deprecated and will be removed in the future. use css text-align instead. class, id, style provided for use with stylesheets. href used to set a hyperlink to a specified uri. mathbackground the background color. ...
<munderover> - MathML
if false (default value), the overscript is a limit over the base expression. accentunder if true, the underscript is an accent, which is drawn closer to the base expression. if false (default value), the underscript is a limit under the base expression. align the alignment of both underscript and overscript. possible values are: left, center, and right. ...
Examples - MathML
pythagorean theorem small example showing a proof of the pythagorean theorem. deriving the quadratic formula outlines the derivation of the quadratic formula. mathml torture test large set of test markup. ...
Media type and format guide: image, audio, and video content - Web media technologies
Web › Media › Formats
media containers (file types) a guide to the file types that contain media data. some are audio-specific, while others may be used for either audio or combined audiovisual content such as movies. includes overviews of each of the file types supported by the major web browsers, along with browser support information and supported features. web audio codec guide a guide to the audio codecs allowed for by the common media containers, as well as by the major browsers. includes benefits, limitations, key specifications and capabilities, and use cases. it also covers each browser's support for using the codec in given containers. web video codec guide this article provides basic information about the video codecs supported by the major browsers, as well as some that are not commonly suppor...
Guide to streaming audio and video - Web media technologies
other environments, although in some cases this support is conditional. for example, because many web sites' mobile-specific content assume that mobile browsers support hls, firefox for android does as well, in order to avoid strange compatibility errors from occurring due to this assumption being incorrect. the desktop version of android, however, does not support hls. hls uses playlists to allow the user to not only select the media to stream, but also to choose among versions or forms of the same media. for example, hls lets the server stream a video with multiple audio streams which the user can choose from, in order to hear their own language. additionally, forms of the stream can be provided which are optimized for different network conditions. in this way, live streams can be made f...
Using images in HTML - Web media technologies
Web › Media › images
ve images. in this guide you'll find links to resources that deal with adding images to websites. references these articles cover some of the html elements and css properties that are used to control how images are displayed on the web. html <img> the html <img> element is used to embed an image in a webpage. it supports a wide range of attributes that control how the image behaves and allows you to add important information like alt text for people who don't see the image. <picture> the html <picture> element contains zero or more <source> elements and one <img> element which provides versions of an image for different display/device scenarios. the browser considers each child <source> element and chooses the best match among them. css object-fit the object-fit css property ...
Lazy loading - Web Performance
kely) 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 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 livin...
Performance Monitoring: RUM vs synthetic monitoring - Web Performance
n may differ greatly in life experiences from those creating it. by leveraging rum, a business can better understand its users and identify the areas on its site that require the most attention. moreover, rum can help to understand the geographic or channel distribution trends of your users. knowing your user trends helps you better define your business plan and, from a monitoring perspective, allows you to identify key areas to target for optimization and performance improvements. rum v synthetic synthetic is well suited for catching regressions during development life cycles, especially with network throttling. it is fairly easy, inexpensive, and great for spot-checking performance during development as an effective way to measure the effect of code changes, but it doesn’t reflect what...
Using dns-prefetch - Web Performance
why use dns-prefetch? when a browser requests a resource from a (third party) server, that cross-origin’s domain name must be resolved to an ip address before the browser can issue the request. this process is known as dns resolution. while dns caching can help to reduce this latency, dns resolution can add significant latency to requests. for websites that open connections to many third parties, this latency can significantly reduce loading performance. ...
PWA developer guide - Progressive web apps (PWAs)
in the articles listed here, you'll find guides about every aspect of development specific to the greation of progressive web applications (pwas). for all other documentation about web development, which generally pertains to pwas as well, see our primary web development documentation. --->>> titles below are just for the list; give articles good seo names and feel free to tweak those and this as needed... <<<--- web app basics introduction and getting started with pwa development some description installing and uninstalling web apps an introductory guide to how a web app can be installed on the user's device... using service workers to run offline description alerting the user using notifications description creating a web app from an existing site description advanced t...
Progressive loading - Progressive web apps (PWAs)
need all of the images in the best possible quality at the very beginning of viewing the site. this can be optimized. first of all, you should use tools or services similar to tinypng, which will reduce the file size of your images without altering the quality too much. if you're past that point, then you can start thinking about optimizing the image loading using javascript. we'll expain this below. placeholder image instead of having all the screenshots of games referenced in <img> element src attributes, which will force the browser to download them automatically, we can do it selectively via javascript. the js13kpwa app uses a placeholder image instead, which is small and lightweight, while the final paths to target images are stored in data-src attributes: <img src='data/img/placehol...
Responsive Navigation Patterns - Progressive web apps (PWAs)
top and left navigation menus are common on larger screens, but are often not the optimal way to present information on small screens because of the reduced screen real estate. therefore, it is necessary to consider the presentation of content and ease of navigation for all screen sizes. note: html/css for the corresponding patterns will be available soon. ...
Web API reference - Web technology reference
Web › Reference › API
be accessed using javascript code, and let you do anything from making minor adjustments to any window or element, to generating intricate graphical and audio effects using apis such as webgl and web audio. 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. html, xml and svg have extended it to manipulate their specific elements. device apis this set of apis allows access to various hardware features available to web pages and applications. e.g. ambient light sensor api, geolocation api, pointer lock api, proximity api, device orientation api,...
Web technology reference
if you're new to web development, consider starting with our learning area, which is filled with step-by-step tutorials that will guide you from total webdev newbie to at least semi-pro! html — structuring the web hypertext markup language is used to define and describe semantically the content (markup) of a web page in a well-structured format. ...
SVG Conditional Processing Attributes - SVG: Scalable Vector Graphics
stemlanguage attributes externalresourcesrequired deprecated since svg 2 if set to true, it indicates that the browser must wait for all the external resources necessary to render that element to be loaded before processing the associated element. value: false|true; animatable: no requiredextensions list all the browser specific capabilities that must be supported by the borwser to be allowed to render the associated element. value: a list of space-separated uri; animatable: no requiredfeatures deprecated since svg 2 list all the features, as defined is the svg 1.1 specification, that must be supported by the borwser to be allowed to render the associated element.. value: a list of space-separated uri; animatable: no systemlanguage indicates which language the user must have c...
additive - SVG: Scalable Vector Graphics
ion as an offset or delta to an attribute's value, rather than as absolute values. four elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, and <animatetransform> usage notes value replace | sum default value replace animatable no sum specifies that the animation will add to the underlying value of the attribute and other lower priority animations. replace specifies that the animation will override the underlying value of the attribute and other lower priority animations. this is the default, however the behavior is also affected by the animation value attributes by and to, as described in smil animation: how from, to and by attributes affect additive behavior. specifications specification status c...
alphabetic - SVG: Scalable Vector Graphics
it has the same syntax and semantics as the baseline descriptor within an @font-face. for horizontally oriented glyph layouts, it indicates the alignment coordinate for glyphs to achieve alphabetic baseline alignment. the value is an offset in the font coordinate system. only one element is using this attribute: <font-face> usage notes value <number> default value 0 animatable no specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'alphabetic' in that specification. ...
bbox - SVG: Scalable Vector Graphics
Web › SVG › Attribute › bbox
the bbox attribute defines the maximal bounding box of a font. only one element is using this attribute: <font-face> usage notes value <string> default value none animatable no <string> a comma-separated list of exactly four numbers specifying, in order, the lower left x, lower left y, upper right x, and upper right y of the bounding box for the complete font. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'bbox' in that specification. recommendation initial definition ...
bias - SVG: Scalable Vector Graphics
Web › SVG › Attribute › bias
usage notes value <number> default value 0 animatable yes one application of bias is when it is desirable to have 0.5 gray value be the zero response of the filter. ...
by - SVG: Scalable Vector Graphics
Web › SVG › Attribute › by
om attribute. four elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, and <animatetransform> html, body, svg { height: 100%; } <svg viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <rect x="10" y="10" width="100" height="100"> <animate attributename="width" fill="freeze" by="50" dur="3s"/> </rect> </svg> usage notes value see below default value none animatable no the exact value type for this attribute depends on the value of the attribute that will be animated. when a list of values is defined via the values attribute, the by attribute is ignored. specifications specification status comment svg animations level 2the definition of 'by' in that specification. ...
clip-path - SVG: Scalable Vector Graphics
the clip-path presentation attribute defines or associates a clipping path with the element it is related to. note: as a presentation attribute clip-path can be used as a css property. ...
color-interpolation-filters - SVG: Scalable Vector Graphics
ffects operations occur in the linearrgb color space, whereas all other color interpolations occur by default in the srgb color space. it has no affect on filter functions, which operate in the srgb color space. note: as a presentation attribute, color-interpolation can be used as a css property. ...
color-interpolation - SVG: Scalable Vector Graphics
lement which is directly referenced by the fill or stroke property. when animating colors, color interpolation is performed according to the value of the color-interpolation property on the element being animated. note: as a presentation attribute, color-interpolation can be used as a css property. ...
color-profile - SVG: Scalable Vector Graphics
the color-profile attribute is used to define which color profile a raster image included through the <image> element should use. note: as a presentation attribute, color-profile can be used as a css property. as a presentation attribute, it can be applied to any element but it only has an effect on the following element: <image> usage notes value auto | srgb | <name> | <iri> default value auto animatable yes auto all colors are presumed to be defined in the srgb color space unless a more precise embedded profile is specified within content data. for images that do have a profile built into their data, that profile is used. for images that do not have a profile, the srgb profile is used. srgb the source profile is assumed to be srgb. this ...
color-rendering - SVG: Scalable Vector Graphics
er agent should perform color operations in a way that optimizes performance, which might mean sacrificing the color interpolation precision as specified by through the linearrgb value for color-interpolation-filters. note: as a presentation attribute, color-rendering can be used as a css property. ...
cursor - SVG: Scalable Vector Graphics
Web › SVG › Attribute › cursor
[[<funciri>,]* [ auto | crosshair | default | pointer | move | e-resize | ne-resize | nw-resize | n-resize | se-resize | sw-resize | s-resize | w-resize| text | wait | help ]] | inherit animatable yes normative document svg 1.1 (2nd edition) <funciri> functional notation for a reference. the syntax for this reference is the same as the css uri. elements the following elements can use the cursor attribute container elements » graphics elements » browser compatibility the compatibility table on this page is generated from structured data. 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 ...
data-* - SVG: Scalable Vector Graphics
Web › SVG › Attribute › data-*
the data-* svg attributes are called custom data attributes. they let svg markup and its resulting dom share information that standard attributes can't, usually for scripting purposes. their custom data are available via the svgelement interface of the element the attributes belong to, with the svgelement.dataset property. the * can be replaced by any characters allowed in xml's rules for names, with the following restrictions: can't start with xml. no semicolons (;, u+003a). no capital a to z letters. the svgelement.dataset property is a domstringmap that provides the attribute data-test-value via svgelement.dataset.testvalue. hyphen characters (-, u+002d) are removed and the next letter is capitalized, resulting in the camelcase format. specifications specification ...
direction - SVG: Scalable Vector Graphics
characters rotated 90 degrees clockwise relative to a top-to-bottom inline-base direction. in many cases, the bidirectional unicode algorithm produces the desired result automatically, so this attribute doesn't need to be specified in those cases. for other cases, such as when using right-to-left languages, it may be sufficient to add the direction attribute to the outermost <svg> element, and allow that direction to inherit to all text elements: note: as a presentation attribute, direction can be used as a css property. see css direction for further information. as a presentation attribute, it can be applied to any element but it only has effect on shapes and text context elements, including: <altglyph>, <textpath>, <text>, <tref>, and <tspan>. html, body, svg { height: 100%; } <sv...
fill-rule - SVG: Scalable Vector Graphics
the fill-rule attribute is a presentation attribute defining the algorithm to use to determine the inside part of a shape. note: as a presentation attribute, fill-rule 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 eight elements: <altglyph>, <path>, <polygon>, <polyline>, <text>, <textpath>, <tref>, and <tspan> html,body,svg { height:100% } <svg viewbox="-10 -10 220 120" xmlns="http://www.w3.org/2000/svg"> <!-- default value for fill-rule --> <polygon fill-rule="nonzero" stroke="red" points="50,0 21,90 98,35 2,35 79,90"/> <!-- the center of the shape has two path segments (shown by the red stroke) between it and infinity. it is therefore considered outside the shape, and not filled...
fill - SVG: Scalable Vector Graphics
Web › SVG › Attribute › fill
the fill attribute has two different meanings. for shapes and text it's a presentation attribute that defines the color (or any svg paint servers like gradients or patterns) used to paint the element; for animation it defines the final state of the animation. as a presentation attribute, it can be applied to any element but it only has an effect on the following eleven elements: <altglyph>, <circle>, <ellipse>, <path>, <polygon>, <polyline>, <rect>, <text>, <textpath>, <tref>, and <tspan>. for animation five elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set>. html,body,svg { height:100% } <svg viewbox="0 0 300 100" xmlns="http://www.w3.org/2000/svg"> <!-- simple color fill --> <circle cx="50" cy="50" r="40" fill="pink" /> ...
filterRes - SVG: Scalable Vector Graphics
note that negative values or zero values disable the rendering of the element which referenced the filter. ...
flood-color - SVG: Scalable Vector Graphics
the flood-color attribute indicates what color to use to flood the current filter primitive subregion. note: as a presentation attribute, flood-color can be used as a css property. ...
flood-opacity - SVG: Scalable Vector Graphics
the flood-opacity attribute indicates the opacity value to use across the current filter primitive subregion. note: as a presentation attribute, flood-opacity can be used as a css property. ...
font-family - SVG: Scalable Vector Graphics
the font-family attribute indicates which font family will be used to render the text, specified as a prioritized list of font family names and/or generic family names. note: as a presentation attribute, font-family can be used as a css property. see the css font-family property for more information. ...
font-size - SVG: Scalable Vector Graphics
the font-size attribute refers to the size of the font from baseline to baseline when multiple lines of text are set solid in a multiline layout environment. note: as a presentation attribute, font-size can be used as a css property. see the css font-size property for more information. ...
font-stretch - SVG: Scalable Vector Graphics
the font-stretch attribute indicates the desired amount of condensing or expansion in the glyphs used to render the text. note: as a presentation attribute, font-stretch can be used as a css property. see the css font-stretch property for more information. ...
font-style - SVG: Scalable Vector Graphics
the font-style attribute specifies whether the text is to be rendered using a normal, italic, or oblique face. note: as a presentation attribute, font-style can be used as a css property. see the css font-style property for more information. ...
font-variant - SVG: Scalable Vector Graphics
the font-variant attribute indicates whether the text is to be rendered using variations of the fontʼs glyphs. note: as a presentation attribute, font-variant can be used as a css property. see the css font-variant property for more information. ...
font-weight - SVG: Scalable Vector Graphics
the font-weight attribute refers to the boldness or lightness of the glyphs used to render the text, relative to other fonts in the same font family. note: as a presentation attribute, font-weight can be used as a css property. see the css font-weight property for more information. ...
from - SVG: Scalable Vector Graphics
Web › SVG › Attribute › from
cified in by. four elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, and <animatetransform> html, body, svg { height: 100%; } <svg viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <rect x="10" y="10" height="100"> <animate attributename="width" fill="freeze" from="100" to="150" dur="3s"/> </rect> </svg> usage notes value see below default value none animatable no the exact value type for this attribute depends on the value of the attribute that will be animated. when a list of values is defined via the values attribute, the from attribute is ignored. specifications specification status comment svg animations level 2the definition of 'from' in that specification.
glyph-orientation-horizontal - SVG: Scalable Vector Graphics
e is not a multiple of 180 degrees, then the current text position is incremented according to the vertical metrics of the glyph. this attribute is applied only to text written in a horizontal writing-mode. note: as a presentation attribute, glyph-orientation-horizontal 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>, <textpath>, <text>, <tref>, and <tspan> context notes value <angle> default value 0deg animatable no <angle> the value of the angle is restricted to 0, 90, 180, and 270 degrees. if another angle is specified, it is rounded to the closest of the permitted values. a value of 0deg indicates that all glyphs are set with...
glyph-orientation-vertical - SVG: Scalable Vector Graphics
gle is not a multiple of 180 degrees, then the current text position is incremented according to the horizontal metrics of the glyph. this attribute is applied only to text written in a vertical writing-mode. note: as a presentation attribute, glyph-orientation-vertical 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>, <textpath>, <text>, <tref>, and <tspan> context notes value auto | <angle> default value auto animatable no auto fullwidth ideographic and fullwidth latin text will be set with a glyph orientation of 0 degrees. ideographic punctuation and other ideographic characters having alternate horizontal and vertical forms will...
gradientTransform - SVG: Scalable Vector Graphics
this additional transformation matrix is post-multiplied to (i.e., inserted to the right of) any previously defined transformations, including the implicit transformation necessary to convert from object bounding box units to user space. ...
id - SVG: Scalable Vector Graphics
Web › SVG › Attribute › id
scalable vector graphics (svg) 1.1 (second edition)the definition of 'id' in that specification. recommendation initial definition ...
image-rendering - SVG: Scalable Vector Graphics
s image processing. the resampling is always done in a truecolor (e.g., 24-bit) color space even if the original data and/or the target device is indexed color. note: as a presentation attribute, image-rendering can be used as a css property. see the css image-rendering property for more information. as a presentation attribute, it can be applied to any element but it has effect only on the following element: <image> usage notes value auto | optimizespeed | optimizequality default value auto animatable yes auto indicates that the user agent shall make appropriate tradeoffs to balance speed and quality, but quality shall be given more importance than speed. optimizespeed indicates that the user agent shall emphasize rendering speed over qual...
in - SVG: Scalable Vector Graphics
Web › SVG › Attribute › in
if no value is provided and this is the first filter primitive, then this filter primitive will use sourcegraphic as its input. if no value is provided and this is a subsequent filter primitive, then this filter primitive will use the result from the previous filter primitive as its input. ...
k1 - SVG: Scalable Vector Graphics
Web › SVG › Attribute › k1
the k1 attribute defines one of the values to be used within the the arithmetic operation of the <fecomposite> filter primitive. ...
k2 - SVG: Scalable Vector Graphics
Web › SVG › Attribute › k2
the k2 attribute defines one of the values to be used within the the arithmetic operation of the <fecomposite> filter primitive. ...
k3 - SVG: Scalable Vector Graphics
Web › SVG › Attribute › k3
the k3 attribute defines one of the values to be used within the the arithmetic operation of the <fecomposite> filter primitive. ...
k4 - SVG: Scalable Vector Graphics
Web › SVG › Attribute › k4
the k4 attribute defines one of the values to be used within the the arithmetic operation of the <fecomposite> filter primitive. ...
kerning - SVG: Scalable Vector Graphics
Web › SVG › Attribute › kerning
ables that are included in the relevant font (i.e., enable auto-kerning) or instead disable auto-kerning and set the spacing between them to a specific length (typically, zero). note: as a presentation attribute kerning can be used as a css property. in css the property is called font-kerning, though. ...
keyPoints - SVG: Scalable Vector Graphics
in time specified by corresponding keytimes value. the distance is calculated along the path specified by the path attribute. each progress value in the list corresponds to a value in the keytimes attribute list. if a list of key points is specified, there must be exactly as many values in the keypoints list as in the keytimes list. if there's a semicolon at the end of the value, optionally followed by white space, both the semicolon and the trailing white space are ignored. if there are any errors in the value specification (i.e. bad values, too many or too few values), then thatʼs an error. specifications specification status comment svg animations level 2the definition of 'keypoints' in that specification. editor's draft no change scala...
letter-spacing - SVG: Scalable Vector Graphics
ribute value has a unit identifier, such as .25em or 1%, then the browser converts the <length> into its corresponding value in the current user coordinate system. note: as a presentation attribute, letter-spacing can be used as a css property. see the css letter-spacing property for more information. ...
marker-end - SVG: Scalable Vector Graphics
ot none, then two markers will be rendered on that final vertex. for <path> elements, for each closed subpath, the last vertex is the same as the first vertex. marker-end is only rendered on the final vertex of the path data. note: as a presentation attribute, marker-end can be used as a css property. ...
marker-mid - SVG: Scalable Vector Graphics
the marker-mid attribute defines the arrowhead or polymarker that will be drawn at all interior vertices of the given shape. the marker is rendered on every vertex other than the first and last vertices of the path data. note: as a presentation attribute, marker-mid can be used as a css property. ...
marker-start - SVG: Scalable Vector Graphics
one, then two markers will be rendered on that final vertex. for <path> elements, for each closed subpath, the last vertex is the same as the first vertex. marker-start is only rendered on the first vertex of the path data. note: as a presentation attribute, marker-start can be used as a css property. ...
markerHeight - SVG: Scalable Vector Graphics
attributes. <number> this value defines the height of the marker in the units defined by the markerunits attribute. a value of zero disables rendering of the element and negative values are an error. specifications specification status comment scalable vector graphics (svg) 2the definition of 'markerheight' in that specification. candidate recommendation allowed percentage and number values. scalable vector graphics (svg) 1.1 (second edition)the definition of 'markerheight' in that specification. recommendation initial definition ...
markerWidth - SVG: Scalable Vector Graphics
io attributes. <number> this value defines the width of the marker in the units defined by the markerunits attribute. a value of zero disables rendering of the element and negative values are an error. specifications specification status comment scalable vector graphics (svg) 2the definition of 'markerwidth' in that specification. candidate recommendation allowed percentage and number values. scalable vector graphics (svg) 1.1 (second edition)the definition of 'markerwidth' in that specification. recommendation initial definition ...
name - SVG: Scalable Vector Graphics
Web › SVG › Attribute › name
profile description. the name "srgb" is predefined; any color profile descriptions with <name> set to "srgb" (case-insensitively) will be ignored. font-face-name for <font-face-name>, name defines the name of the font face. value <name> default value none animatable yes <name> this value specifies the name of a local font. unlike the syntax allowed between the parentheses of the local(…) clause in an @font-face rule src descriptor, the font name specified in this attribute is not surrounded in single or double quotes. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'name for <font-face-name>' in that specification. recommendation initia...
opacity - SVG: Scalable Vector Graphics
Web › SVG › Attribute › opacity
the opacity attribute specifies the transparency of an object or of a group of objects, that is, the degree to which the background behind the element is overlaid. note: as a presentation attribute, opacity can be used as a css property. see the css opacity property for more information. ...
operator - SVG: Scalable Vector Graphics
destination graphic defined in the in2 attribute are combined. lighter this value indicates that the sum of the source graphic defined in the in attribute and the destination graphic defined in the in2 attribute is displayed. arithmetic this value indicates that the source graphic defined in the in attribute and the destination graphic defined in the in2 attribute are combined using the following formula: result = k1*i1*i2 + k2*i1 + k3*i2 + k4 where: i1 and i2 indicate the corresponding pixel channel values of the input image, which map to in and in2 respectively, and k1,k2,k3,and k4 indicate the values of the attributes with the same name. femorphology for <femorphology>, operator defines whether to erode (i.e., thin) or dilate (fatten) the source graphic. value ...
orient - SVG: Scalable Vector Graphics
Web › SVG › Attribute › orient
this value indicates that the marker is oriented such that its positive x-axis is pointing in a direction relative to the path at the position the marker is placed. auto-start-reverse if placed by marker-start, the marker is oriented 180° different from the orientation that would be used if auto where specified. for all other markers, auto-start-reverse means the same as auto. note: this allows a single arrowhead marker to be defined that can be used for both the start and end of a path, i.e. which points outwards from both ends. <angle> this value indicates that the marker is oriented such that the specified angle is that measured between the shape's positive x-axis and the marker's positive x-axis. note: for example, if a value of 45 is given, then the marker's positive x-axi...
overline-position - SVG: Scalable Vector Graphics
the overline-position attribute represents the ideal vertical position of the overline. ...
overline-thickness - SVG: Scalable Vector Graphics
the overline-thickness attribute represents the ideal thickness of the overline. ...
patternTransform - SVG: Scalable Vector Graphics
skewx(30) scale(1 0.5)"> <circle cx="10" cy="10" r="10" /> </pattern> <!-- apply the transformed pattern tile --> <rect x="10" y="10" width="80" height="80" fill="url(#p1)" /> </svg> pattern for <pattern>, patterntransform defines a list of transform definitions that are applied to a pattern tile. note: as of svg2, it is also allowed to use the css transform property. however, the current state of implementation isn't very good. for backward compatibility reason, it is highly suggested to keep using the patterntransform attribute. value <transform-list> default value identity transform animatable yes transform functions to know more about the definition of transform functions, se...
rendering-intent - SVG: Scalable Vector Graphics
olor spaces. the different options 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 prese...
rotate - SVG: Scalable Vector Graphics
Web › SVG › Attribute › rotate
if the value of rotate is auto, the element turns to align its right-hand side in the current direction of motion. ...
rx - SVG: Scalable Vector Graphics
Web › SVG › Attribute › rx
" rx="0" ry="25" /> <ellipse cx="150" cy="50" rx="25" ry="25" /> <ellipse cx="250" cy="50" rx="50" ry="25" /> <rect x="20" y="120" width="60" height="60" rx="0" ry="15"/> <rect x="120" y="120" width="60" height="60" rx="15" ry="15"/> <rect x="220" y="120" width="60" height="60" rx="150" ry="15"/> </svg> ellipse for <ellipse>, rx defines the x-radius of the shape. with a value lower or equal to zero the ellipse won't be drawn at all. value <length> | <percentage> | auto default value auto animatable yes note: starting with svg2, rx is a geometry property meaning this attribute can also be used as a css property for ellipses. rect for <rect>, rx defines the x-axis radius of the ellipse used to round off the corners of the rectan...
ry - SVG: Scalable Vector Graphics
Web › SVG › Attribute › ry
" ry="0" rx="25" /> <ellipse cx="150" cy="50" ry="25" rx="25" /> <ellipse cx="250" cy="50" ry="50" rx="25" /> <rect x="20" y="120" width="60" height="60" ry="0" rx="15"/> <rect x="120" y="120" width="60" height="60" ry="15" rx="15"/> <rect x="220" y="120" width="60" height="60" ry="150" rx="15"/> </svg> ellipse for <ellipse>, ry defines the y-radius of the shape. with a value lower or equal to zero the ellipse won't be drawn at all. value <length> | <percentage> | auto default value auto animatable yes note: starting with svg2, ry is a geometry property meaning this attribute can also be used as a css property for ellipses. rect for <rect>, ry defines the y-axis radius of the ellipse used to round off the corners of the rectan...
shape-rendering - SVG: Scalable Vector Graphics
the shape-rendering attribute provides hints to the renderer about what tradeoffs to make when rendering shapes like paths, circles, or rectangles. note: as a presentation attribute, shape-rendering can be used as a css property. ...
startOffset - SVG: Scalable Vector Graphics
e is given, then the start offset represents a percentage distance along the entire path. thus, 0% indicates the start point of the path and 100% indicates the end point of the path. <number> this value indicates a distance along the path measured in the current user coordinate system for the <textpath> element. note: negative values and values larger than the path length (e.g. 150%) are allowed. specifications specification status comment scalable vector graphics (svg) 2the definition of 'startoffset' in that specification. candidate recommendation no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'startoffset' in that specification. recommendation initial definition ...
stemh - SVG: Scalable Vector Graphics
Web › SVG › Attribute › stemh
also, either by design or by error, all stems may have slightly different widths. ...
stop-color - SVG: Scalable Vector Graphics
n pre-multiplied space, so transparent really means transparent black. so, specifying a stop-color with the value transparent is equivalent to specifying a stop-color with the value black and a stop-opacity with the value 0. note: as a presentation attribute, stop-color 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 element: <stop> usage notes value currentcolor | <color> <icccolor> default value black animatable yes currentcolor this keyword denotes the current fill color and can be specified in the same manner as within a <paint> specification for the fill and stroke attributes. <color> this value indicates a color value. <icccolor> this value refers t...
strikethrough-position - SVG: Scalable Vector Graphics
« svg attribute reference home the strikethrough-position attribute represents the ideal vertical position of the strikethrough. the strikethrough position is expressed in the font's coordinate system. usage context categories none value <number> animatable no normative document svg 1.1 (2nd edition) elements the following elements can use the strikethrough-position attribute: <font-face> ...
strikethrough-thickness - SVG: Scalable Vector Graphics
« svg attribute reference home the strikethrough-thickness attribute represents the ideal thickness of the strikethrough. the strikethrough thickness is expressed in the font's coordinate system. usage context categories none value <number> animatable no normative document svg 1.1 (2nd edition) elements the following elements can use the strikethrough-thickness attribute: <font-face> ...
stroke-dasharray - SVG: Scalable Vector Graphics
the stroke-dasharray attribute is a presentation attribute defining the pattern of dashes and gaps used to paint the outline of the shape; note: as a presentation attribute, stroke-dasharray can be used as a css property. ...
stroke - SVG: Scalable Vector Graphics
Web › SVG › Attribute › stroke
the stroke attribute is a presentation attribute defining the color (or any svg paint servers like gradients or patterns) used to paint the outline of the shape; note: as a presentation attribute stroke can be used as a css property. ...
style - SVG: Scalable Vector Graphics
Web › SVG › Attribute › style
it functions identically to the style attribute in html. all elements are using this attribute. html,body,svg { height:100% } <svg viewbox="0 0 100 60" xmlns="http://www.w3.org/2000/svg"> <rect width="80" height="40" x="10" y="10" style="fill: skyblue; stroke: cadetblue; stroke-width: 2;"/> </svg> usage notes value <style> default value none animatable no <style> the syntax of style data depends on the style sheet language. by default, the style sheet language is css. note: in theory, the contentstyletype attribute could be used to specify styling languages other than css, like xsl(t). ...
tabindex - SVG: Scalable Vector Graphics
all elements are using this attribute. html, body, svg { height: 100%; } <?xml version="1.0"?> <svg viewbox="0 0 260 260" xmlns="http://www.w3.org/2000/svg"> <circle cx="60" cy="60" r="15" tabindex="1" /> <circle cx="60" cy="160" r="30" tabindex="3" /> <circle cx="160" cy="60" r="30" tabindex="2" /> <circle cx="160" cy="160" r="60" tabindex="4" /> </svg> usage notes value valid integer default value none animatable no valid integer relative order of the element for the purposes of sequential focus navigation. ...
target - SVG: Scalable Vector Graphics
Web › SVG › Attribute › target
context (tab, inline frame, object, etc.) for display of the linked content. if a context with this name already exists, and can be securely accessed from this document, it is re-used, replacing the existing content. if it does not exist, it is created (the same as '_blank', except that it now has a name). the name must be a valid xml name [xml11], and should not start with an underscore (u+005f low line character), to meet the requirements of a valid browsing context name from html. specifications specification status comment scalable vector graphics (svg) 2the definition of 'target' in that specification. candidate recommendation removed the _replace value. scalable vector graphics (svg) 1.1 (second edition)the definition of 'target' in that sp...
text-anchor - SVG: Scalable Vector Graphics
ent, 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. ...
text-decoration - SVG: Scalable Vector Graphics
der 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. ...
text-rendering - SVG: Scalable Vector Graphics
the text-rendering attribute provides hints to the renderer about what tradeoffs to make when rendering text. note: as a presentation attribute, text-rendering can be used as a css property. see the css text-rendering property for more information. ...
textLength - SVG: Scalable Vector Graphics
the contents of the widthdisplay box are updated with the new value as well, and we're finished. result here's what the example looks like. try dragging the slider around to get a feel for what it does. specifications specification status comment scalable vector graphics (svg) 2the definition of 'textlength' in that specification. candidate recommendation allowed percentages and numbers as values. scalable vector graphics (svg) 1.1 (second edition)the definition of 'textlength' in that specification. recommendation initial definition ...
underline-position - SVG: Scalable Vector Graphics
« svg attribute reference home the underline-position attribute represents the ideal vertical position of the underline. the underline position is expressed in the font's coordinate system. usage context categories none value <number> animatable no normative document svg 1.1 (2nd edition) elements the following elements can use the underline-position attribute: <font-face> ...
underline-thickness - SVG: Scalable Vector Graphics
« svg attribute reference home the underline-thickness attribute represents the ideal thickness of the underline. the underline thickness is expressed in the font's coordinate system. usage context categories none value <number> animatable no normative document svg 1.1 (2nd edition) elements the following elements can use the underline-thickness attribute: <font-face> ...
unicode-bidi - SVG: Scalable Vector Graphics
the unicode-bidi attribute specifies how the accumulation of the background image is managed. note: as a presentation attribute, unicode-bidi can be used as a css property. see the css unicode-bidi property for more information. as a presentation attribute, it can be applied to any element but it has effect only on the following eleven elements: <altglyph>, <textpath>, <text>, <tref>, and <tspan> context notes value normal | embed | isolate | bidi-override | isolate-override | plaintext default value normal animatable no for a description of the values, please refer to the css unicode-bidi property. specifications specification status comment css writing modes module level 3the definition of 'unicode-bidi' in that s...
vector-effect - SVG: Scalable Vector Graphics
the vector-effect property specifies the vector effect to use when drawing an object. vector effects are applied before any of the other compositing operations, i.e. filters, masks and clips. note: as a presentation attribute, vector-effect 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 ten elements: <circle>, <ellipse>, <foreignobject>, <image>, <line>, <path>, <polygon>, <polyline>, <rect>, <text>, <textpath> <tspan>, and <use> usage notes value none | non-scaling-stroke | non-scaling-size | non-rotation | fixed-position default value none animatable yes none this value specifies that no vector effect shall be applied, i.e. the default rendering behaviour ...
version - SVG: Scalable Vector Graphics
Web › SVG › Attribute › version
it is purely advisory and has no influence on rendering or processing. while it is specified to accept any number, the only two valid choices are currently 1.0 and 1.1. ...
viewBox - SVG: Scalable Vector Graphics
Web › SVG › Attribute › viewBox
100%" height="100%"/> <!-- with the point of coordinate 0,0 in the center of the viewport the value 50% is resolve to 5 which means the center of the circle is in the bottom/right corner of the viewport. --> <circle cx="50%" cy="50%" r="4" fill="white"/> </svg> the exact effect of this attribute is influenced by the preserveaspectratio attribute. note: values for width or height lower or equal to 0 disable rendering of the element. five elements are using this attribute: <marker>, <pattern>, <svg>, <symbol>, and <view>. marker for <marker>, viewbox defines the position and dimension for the content of the <marker> element. value <number>?, <number>?, <number>?, <number> default value none animatable yes pattern for <pattern>, v...
word-spacing - SVG: Scalable Vector Graphics
provided with one of the unit identifiers (e.g. .25em or 1%), then the browser converts the <length> into a corresponding value in the current user coordinate system. note: as a presentation attribute, word-spacing can be used as a css property. see the css word-spacing property for more information. ...
Compatibility sources - SVG: Scalable Vector Graphics
the following sources are used for the compatibility tables on svg elements and attributes: https://developer.mozilla.org/en/svg_in_firefox together with its revision history for firefox http://www.webkit.org/projects/svg/status.xml together with its recorded archive for webkit, safari and chrome http://www.opera.com/docs/specs/opera9/svg/ and accompanying pages for opera >= 9, http://www.opera.com/docs/specs/opera8/ for opera 8 http://blogs.msdn.com/b/ie/archive/2010/03/18/svg-in-ie9-roadmap.aspx for hints on ie9 support status the svg support charts at codedread.com for basic checks against the w3c test suite wikipedia for basic hints, not normative ...
<altGlyph> - SVG: Scalable Vector Graphics
Web › SVG › Element › altGlyph
usage context categoriestext content element, text content child elementpermitted contentany elements or character data attributes x this attribute defines the corresponding absolute x-coordinates for rendering the element. value type: <list-of-coordinates> ; default value: absolute x-coordinate of ancestor <text> or <tspan>; animatable: yes y this attribute defines the corresponding absolute y-coordinates for rendering the element. value type: <list-of-coordinates> ; default value: absolute y-coordinate of ancestor <text> or <tspan>; animatable: yes dx this attribute indicates a shift along the x-axis on the position of the element. ...
<animateColor> - SVG: Scalable Vector Graphics
d in svg 1.1 second edition and may be removed in a future version of svg. it provides no features not already available by using the <animate> element. so, authors should use the <animate> element instead. the <animatecolor> svg element specifies a color transformation over time. ...
<animateMotion> - SVG: Scalable Vector Graphics
value type: <number>*; default value: none; animatable: no path this attribute defines the path of the motion, using the same syntax as the d attribute. value type: <string>; default value: none; ...
<clipPath> - SVG: Scalable Vector Graphics
Web › SVG › Element › clipPath
candidate recommendation scalable vector graphics (svg) 1.1 (second edition)the definition of '<clippath>' in that specification. reco...
<color-profile> - SVG: Scalable Vector Graphics
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of '<color-profile>' in that specification. ...
<cursor> - SVG: Scalable Vector Graphics
Web › SVG › Element › cursor
nes 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 number of the following elements, in any order:descriptive elements attributes global attributes conditional processing attributes core attributes xlink attributes externalresourcesrequired specific attributes x y xlink:href dom interface this element implements the svgcursorelement interface. specifications specification status comment scalable vector graphics (svg) 2t...
<defs> - SVG: Scalable Vector Graphics
Web › SVG › Element › defs
interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility usage notes categoriescontainer element, structural elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> specifications specification status comment scalable vector graphi...
<feBlend> - SVG: Scalable Vector Graphics
Web › SVG › Element › feBlend
the <feblend> svg filter primitive composes two objects together ruled by a certain blending mode. this is similar to what is known from image editing software when blending two layers. the mode is defined by the mode attribute. usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in in2 mode dom interface this element implements the svgfeblendelement interface. example svg <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <filter id="spotlight"> <feflood result="floodfill" x="0" y=...
<feDiffuseLighting> - SVG: Scalable Vector Graphics
permitted contentany number of descriptive elements and exactly one light source element, in any order. attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in surfacescale diffuseconstant kernelunitlength dom interface this element implements the svgfediffuselightingelement interface. example the following example show the effect of the <fediffuselighting> element on a circle with each light source available. each time, the light comes from the upper left corner. <svg width="440" height="140" xmlns="http://www.w3.org/2000/svg"> <!-- no light is applied --> <text text-anchor="middle" x="60" y="22">no light</text> <circle cx="60" cy="80" r="50" fill="green" /> <!-- the light source is a...
<feDisplacementMap> - SVG: Scalable Vector Graphics
. the formula for the transformation looks like this: p'(x,y) ← p( x + scale * (xc(x,y) - 0.5), y + scale * (yc(x,y) - 0.5)) where p(x,y) is the input image, in, and p'(x,y) is the destination. xc(x,y) and yc(x,y) are the component values of the channel designated by xchannelselector and ychannelselector. usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in in2 scale xchannelselector ychannelselector dom interface this element implements the svgfedisplacementmapelement interface. example <svg width="200" height="200" viewbox="0 0 220 220" xmlns="http...
<feDistantLight> - SVG: Scalable Vector Graphics
the <fedistantlight> filter primitive defines a distant light source that can be used within a lighting filter primitive: <fediffuselighting> or <fespecularlighting>. usage context categorieslight source elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes specific attributes azimuth elevation dom interface this element implements the svgfedistantlightelement interface. specifications specification status comment filter effects module level 1the definition of '<fedistantlight>' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of '<fedistantlight>' in that specification. recommendatio...
<feDropShadow> - SVG: Scalable Vector Graphics
blur operation in the drop shadow. value type: <number>; default value: 2; animatable: yes global attributes core attributes most notably: id styling attributes class, style filter primitive attributes height, in, result, x, y, width presentation attributes most notably: flood-color, flood-opacity usage notes categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <script>, <set> specifications specification status comment filter effects module level 1the definition of '<fedropshadow>' in that specification. working draft initial definition ...
<feFlood> - SVG: Scalable Vector Graphics
Web › SVG › Element › feFlood
the <feflood> svg filter primitive fills the filter subregion with the color and opacity defined by flood-color and flood-opacity. usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <animatecolor>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes flood-color flood-opacity dom interface this element implements the svgfefloodelement interface. example html content <svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"> <defs> <filter id="floodfilter" filterunits="userspaceonuse"> <feflood x="50" y="50" width="100" height="100" flood-color="green" flood-opacity="0.5"/> </filter...
<feFuncA> - SVG: Scalable Vector Graphics
Web › SVG › Element › feFuncA
the <fefunca> svg filter primitive defines the transfer function for the alpha component of the input graphic of its parent <fecomponenttransfer> element. usage context categoriesnonepermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes transfer function attributes specific attributes none dom interface this element implements the svgfefuncaelement interface. specifications specification status comment filter effects module level 1the definition of '<fefunca>' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of '<fefunca>' in that specification. recommendation initial definition ...
<feFuncB> - SVG: Scalable Vector Graphics
Web › SVG › Element › feFuncB
the <fefuncb> svg filter primitive defines the transfer function for the blue component of the input graphic of its parent <fecomponenttransfer> element. usage context categoriesnonepermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes transfer function attributes specific attributes none dom interface this element implements the svgfefuncbelement interface. specifications specification status comment filter effects module level 1the definition of '<fefuncb>' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of '<fefuncb>' in that specification. recommendation initial definition ...
<feFuncG> - SVG: Scalable Vector Graphics
Web › SVG › Element › feFuncG
the <fefuncg> svg filter primitive defines the transfer function for the green component of the input graphic of its parent <fecomponenttransfer> element. usage context categoriesnonepermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes transfer function attributes specific attributes none dom interface this element implements the svgfefuncgelement interface. specifications specification status comment filter effects module level 1the definition of '<fefuncg>' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of '<fefuncg>' in that specification. recommendation initial definition ...
<feFuncR> - SVG: Scalable Vector Graphics
Web › SVG › Element › feFuncR
the <fefuncr> svg filter primitive defines the transfer function for the red component of the input graphic of its parent <fecomponenttransfer> element. usage context categoriesnonepermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes transfer function attributes specific attributes none dom interface this element implements the svgfefuncrelement interface. specifications specification status comment filter effects module level 1the definition of '<fefuncr>' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of '<fefuncr>' in that specification. recommendation initial definition ...
<feGaussianBlur> - SVG: Scalable Vector Graphics
the <fegaussianblur> svg filter primitive blurs the input image by the amount specified in stddeviation, which defines the bell-curve. usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in stddeviation edgemode dom interface this element implements the svgfegaussianblurelement interface. example simple example svg <svg width="230" height="120" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <filter id="blurme"> <fegaussianblur in="sourcegraphic" stddeviation="5" /> </filter> <circle cx="60" cy="60" r="50" fill="gre...
<feImage> - SVG: Scalable Vector Graphics
Web › SVG › Element › feImage
example svg <svg viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <filter id="image"> <feim...
<feMergeNode> - SVG: Scalable Vector Graphics
the femergenode takes the result of another filter to be processed by its parent <femerge>. ...
<feMorphology> - SVG: Scalable Vector Graphics
the <femorphology> svg filter primitive is used to erode or dilate the input image. its usefulness lies especially in fattening or thinning effects. usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in operator radius dom interface this element implements the svgfemorphologyelement interface. examples filtering svg content svg <svg xmlns="http://www.w3.org/2000/svg" width="300" height="180"> <filter id="erode"> <femorphology operator="erode" radius="1"/> </filter> <filter id="dilate"> <femorphology operator="dilate" radius="2"/> </filter> <t...
<feOffset> - SVG: Scalable Vector Graphics
Web › SVG › Element › feOffset
the <feoffset> svg filter primitive allows to offset the input image. the input image as a whole is offset by the values specified in the dx and dy attributes. usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in dx dy dom interface this element implements the svgfeoffsetelement interface. example svg <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <defs> <filter id="offset" width="180" height="180"> <feoffset in="sourcegraphic" dx="60" dy="60" /> </filter> </defs> <rect x="0" y="0" width="100" height="100" stroke="black"...
<fePointLight> - SVG: Scalable Vector Graphics
the <fepointlight> filter primitive defines a light source which allows to create a point light effect. it that can be used within a lighting filter primitive: <fediffuselighting> or <fespecularlighting>. usage context categorieslight source elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes specific attributes x y z dom interface this element implements the svgfepointlightelement interface. example svg <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <filter id="spotlight"> <fespecularlighting result="spotlight" specularconstant="1.5" specularexponent="80" lighting-color="#fff"> <fepoint...
<feSpecularLighting> - SVG: Scalable Vector Graphics
the resulting image depends on the light color, light position and surface geometry of the input bump map. the result of the lighting calculation is added. the filter primitive assumes that the viewer is at infinity in the z direction. ...
<feSpotLight> - SVG: Scalable Vector Graphics
the <fespotlight> svg filter primitive defines a light source which allows to create a spotlight effect. it that can be used within a lighting filter primitive: <fediffuselighting> or <fespecularlighting>. usage context categorieslight source elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes specific attributes x y z pointsatx pointsaty pointsatz specularexponent limitingconeangle dom interface this element implements the svgfespotlightelement interface. example html content <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <filter id="spotlight"> <fespecularlighting result="spotlight" specularconst...
<feTile> - SVG: Scalable Vector Graphics
Web › SVG › Element › feTile
the <fetile> svg filter primitive allows to fill a target rectangle with a repeated, tiled pattern of an input image. the effect is similar to the one of a <pattern>. usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in dom interface this element implements the svgfetileelement interface. example svg <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <filter id="tile" x="0" y="0" width="100%" height="100%"> <fetile in="sourcegraphic" x="50" y="50" width="100" height="100" ...
<feTurbulence> - SVG: Scalable Vector Graphics
the <feturbulence> svg filter primitive creates an image using the perlin turbulence function. it allows the synthesis of artificial textures like clouds or marble. the resulting image will fill the entire filter primitive subregion. usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes basefrequency numoctaves seed stitchtiles type dom interface this element implements the svgfeturbulenceelement interface. example <svg width="200" height="200" viewbox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feturbulence type...
<filter> - SVG: Scalable Vector Graphics
Web › SVG › Element › filter
the <filter> svg element defines a custom filter effect by grouping atomic filter primitives. it is never rendered itself, but must be used by the filter attribute on svg elements, or the filter css property for svg/html elements. usage context categoriesnonepermitted contentany number of the following elements, in any order:descriptive elementsfilter primitive elements<animate>, <set> attributes global attributes core attributes presentation attributes xlink attributes class style externalresourcesrequired specific attributes x y width height filterres filterunits primitiveunits xlink:href dom interface this element implements the svgfilterelement interface. example svg <svg width="230" height="120" xmlns="http://www.w3.org/2000/svg"> <filter id="blurme"> <...
<font-face-src> - SVG: Scalable Vector Graphics
the <font-face-src> svg element corresponds to the src descriptor in css @font-face rules. it serves as container for <font-face-name>, pointing to locally installed copies of this font, and <font-face-uri>, utilizing remotely defined fonts. usage context categoriesfont elementpermitted contentone or more of the following elements, in any order:<font-face-name>, <font-face-uri> attributes global attributes core attributes specific attributes none dom interface this element implements the svgfontfacesrcelement interface. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of '<font-face-src>' in that specification. recommendation initial definition ...
<font-face-uri> - SVG: Scalable Vector Graphics
the <font-face-uri> svg element points to a remote definition of the current font. usage context categoriesfont elementpermitted contentany number of the following elements, in any order:<font-face-format> attributes global attributes core attributes xlink attributes specific attributes xlink:href dom interface this element implements the svgfontfaceurielement interface. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of '<font-face-uri>' in that specification. recommendation initial definition ...
<font> - SVG: Scalable Vector Graphics
Web › SVG › Element › font
the <font> svg element defines a font to be used for text layout. usage context categoriesfont elementpermitted contentany number of the following elements, in any order:descriptive elements<font-face>, <glyph>, <hkern>, <missing-glyph>, <vkern> attributes global attributes core attributes presentation attributes class style externalresourcesrequired specific attributes horiz-origin-x horiz-origin-y horiz-adv-x vert-origin-x vert-origin-y vert-adv-y dom interface this element implements the svgfontelement interface. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of '<font>' in that specification. recommendation initial definition ...
<glyph> - SVG: Scalable Vector Graphics
Web › SVG › Element › glyph
a <glyph> defines a single glyph in an svg font. usage context categoriestext content elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> attributes global attributes core attributes presentation attributes class style specific attributes d horiz-adv-x vert-origin-x vert-origin-y vert-adv-y unicode glyph-name orientation arabic-form lang dom interface this element implements the svgglyphelement interface. example svg <svg width="400px" height="300px" version="1.1" ...
<hatch> - SVG: Scalable Vector Graphics
Web › SVG › Element › hatch
direction to cover the areas to be painted. hatches defined by the <hatch> element can then referenced by the fill and stroke css properties on a given graphics element to indicate that the given element shall be filled or stroked with the hatch. paths are defined by <hatchpath> elements. usage context categoriesnever-rendered element, paint server elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elements<hatchpath>, <script>, <style> attributes global attributes core attributes global event attributes presentation attributes style attributes specific attributes x y pitch rotate hatchunits hatchcontentunits transform href dom interface this element implements the svghatchelement interface. example svg <svg w...
<hatchpath> - SVG: Scalable Vector Graphics
Web › SVG › Element › hatchpath
the <hatchpath> svg element defines a hatch path used by the <hatch> element. usage context categoriesnonepermitted contentany number of the following elements, in any order:animation elementsdescriptive elements<script>, <style> attributes global attributes core attributes global event attributes presentation attributes style attributes specific attributes d offset dom interface this element implements the svghatchpathelement interface. example svg <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <defs> <hatch id="hatch" hatchunits="userspaceonuse" pitch="5" rotate="135"> <hatchpath stroke="#a080ff" stroke-width="2"/> </hatch> </defs> <rect fill="url(#hatch)" stroke="black" stroke-width="2" x="10%" y="10%" wi...
<hkern> - SVG: Scalable Vector Graphics
Web › SVG › Element › hkern
this process is known as kerning. usage context categoriesfont elementpermitted contentempty attributes global attributes core attributes specific attributes u1 g1 u2 g2 k dom interface this element implements the svghkernelement interface. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of '<hkern>' in that specification. ...
<linearGradient> - SVG: Scalable Vector Graphics
candidate recommendation scalable vector graphics (svg) 1.1 (second edition)the definition of '<lineargradient>' in that spec...
<mask> - SVG: Scalable Vector Graphics
Web › SVG › Element › mask
nguage presentation attributes most notably: clip-path, clip-rule, color, display, fill, fill-opacity, fill-rule, filter, mask, opacity, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility usage notes categoriescontainer elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> specifications specification status comment css masking module lev...
<metadata> - SVG: Scalable Vector Graphics
Web › SVG › Element › metadata
<!-- draw cable n. --> <g id="cablen" transform="translate(242 88)"> <title>cable n</title> <desc>10baset twisted pair cable</desc> <path d="m0,0c0,-70 20,-50 60,-50"/> </g> </svg> specifications specification status comment scalable vector graphics (svg) 2the definition of '<metadata>' in that specification. candidate recommendation allowed global event attributes on the element. scalable vector graphics (svg) 1.1 (second edition)the definition of '<metadata>' in that specification. recommendation initial definition ...
<missing-glyph> - SVG: Scalable Vector Graphics
the <missing-glyph> svg element's content is rendered, if for a given character the font doesn't define an appropriate <glyph>. usage context categoriesnonepermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> attributes global attributes core attributes presentation attributes class style specific attributes d horiz-adv-x vert-origin-x vert-origin-y vert-adv-y dom interface this element implements the svgmissingglyphelement interface. specifications specification stat...
<pattern> - SVG: Scalable Vector Graphics
Web › SVG › Element › pattern
ering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility xlink attributes most notably: xlink:title usage notes categoriescontainer elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> specifications specification status comment scalable vector graphi...
<radialGradient> - SVG: Scalable Vector Graphics
candidate recommendation added fr attribute scalable vector graphics (svg) 1.1 (second edition)the definition of '<radialgradie...
<stop> - SVG: Scalable Vector Graphics
Web › SVG › Element › stop
candidate recommendation scalable vector graphics (svg) 1.1 (second edition)the definition of '<stop>' in that specification. recommendation initial definition ...
<style> - SVG: Scalable Vector Graphics
Web › SVG › Element › style
svg's style element has the same attributes as the corresponding element in html (see html's <style> element). html,body,svg { height:100%; margin: 0; padding: 0; } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <style> circle { fill: gold; stroke: maroon; stroke-width: 2px; } </style> <circle cx="5" cy="5" r="4" /> </svg> attributes type this attribute defines type of the style sheet language to use as a media type string. value type: <string>; default value: text/css; animatable: no media this attribute defines to which media the style applies. ...
<switch> - SVG: Scalable Vector Graphics
Web › SVG › Element › switch
child element is a container element, like <g>, then its subtree is also processed/rendered or bypassed/not rendered. the display and visibility properties have no effect on <switch> element processing. in particular, setting display:none on a child has no effect on the true/false testing for <switch> processing. ...
<tref> - SVG: Scalable Vector Graphics
Web › SVG › Element › tref
the textual content for a <text> svg element can be either character data directly embedded within the <text> element or the character data content of a referenced element, where the referencing is specified with a <tref> element. usage context categoriestext content element, text content child elementpermitted contentany number of the following elements, in any order:descriptive elements<animate>, <animatecolor>, <set> attributes global attributes conditional processing attributes core attributes graphical event attributes presentation attributes xlink attributes class style externalresourcesrequired specific attributes xlink:href dom interface this element implements the svgtrefelement interface. example <svg width="100%" height="100%" viewbox="0 0 1000 300" ...
<view> - SVG: Scalable Vector Graphics
Web › SVG › Element › view
a view is a defined way to view the image, like a zoom level or a detail view. ...
<vkern> - SVG: Scalable Vector Graphics
Web › SVG › Element › vkern
this process is known as kerning. usage context categoriesfont elementpermitted contentempty attributes global attributes core attributes specific attributes u1 g1 u2 g2 k dom interface this element implements the svgvkernelement interface. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of '<vkern>' in that specification. ...
Example - SVG: Scalable Vector Graphics
() -- apply an upper limit // on mote velocity. mote.prototype.capvelocity = function() { var max = parseint( document.getelementbyid('max_velocity').value ); if( max < this.vx ) this.vx = max; else if( -max > this.vx ) this.vx = -max; if( max < this.vy ) this.vy = max; else if( -max > this.vy ) this.vy = -max; } // mote::capposition() -- apply an upper/lower limit // on mote position. mote.prototype.capposition = function() { var dims = dimensions(); if( this.x < 0 ) this.x = 0; else if( this.x >= dims[0] ) this.x = dims[0]-1; if( this.y < 0 ) this.y = 0; else if( this.y >= dims[1] ) this.y = dims[1]-1; } // mote::move() -- move a mote, update the screen. mote.prototype.move = function() { // apply ...
SVG 1.1 Support in Firefox - SVG: Scalable Vector Graphics
red in the dom, no user interface. title implemented. the title is displayed as a tooltip when the mouse hovers over the svg object. metadata implemented. only stored in the dom, no user interface. symbol implemented. use implemented. doesn't completely follow <svg:use> cascading rules (bug 265894). doesn't deliver events to a svgelementinstance tree (bug 265895). conditional processing module switch implemented. image module image implemented. style module style implemented. shape module path ...
Scripting - SVG: Scalable Vector Graphics
Web › SVG › Scripting
represented using that interface. however, svg documents are now represented using the xmldocument interface instead. inter-document scripting: calling javascript functions when calling a javascript function that resides in the html file from an svg file that is embedded in an html document, you should use parent.functionname() to reference the function. although the adobe svg viewer plugin allows the use of functionname(), it's not the preferred way to do things. according to the svg wiki the "parent" js variable is broken in adobe's svg version 6 preview plugin. the suggested workaround is to use "top" instead of "parent". since it is a beta version of their plugin, we can probably safely ignore this. more information and some examples can be found on the svg wiki inter-document scr...
SVG image element - SVG: Scalable Vector Graphics
in this basic example, a .jpg image referenced by an href attribute will be rendered inside an svg object: <?xml version="1.0" standalone="no"?> <!doctype svg public "-//w3c//dtd svg 1.1//en" "http://www.w3.org/graphics/svg/1.1/dtd/svg11.dtd"> <svg width="5cm" height="4cm" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <image href="firefox.jpg" x="0" y="0" height="50px" width="50px"/> </svg> there are some important things to take note of (referenced from the w3 specs): if you do not set the x or y attributes, they will be set to 0. ...
SVG Tutorial - SVG: Scalable Vector Graphics
Web › SVG › Tutorial
're able, please help out by chipping in and writing a paragraph or two. extra points for writing a whole page! introducing svg from scratch introduction getting started positions basic shapes paths fills and strokes gradients patterns texts basic transformations clipping and masking other content in svg filter effects svg fonts svg image tag tools for svg svg and css the following topics are more advanced and hence should get their own tutorials. scripting svg with javascript tbd svg filters tutorial tbd animations with smil in svg tbd creating fonts in svg tbd ...
mimeTypes.rdf corruption - SVG: Scalable Vector Graphics
m or your mozilla profile (mimetypes.rdf) that are corrupt. the latter is more common, so we'll start with that. however, it seems that the former may also cause the latter. one way to check is to create a new profile and restart mozilla using that profile. if svg works with the new profile, then simply delete the new profile and go about cleaning your old profile using the steps in the section below. if the new profile doesn't work, clean your os file associations, then your mimetypes.rdf. create and remove a bogus file association this solution should work for mimetypes.rdf corruption, and requires little technical knowledge. it's adapted from jp fiset's comment in bug 303581 which in turn was adapted from jeff schiller's comment in bug 303581. 1. try and open a local .svg file using moz...
SVG: Scalable Vector Graphics
Web › SVG
as examples google maps (route overlay) & docs (spreadsheet charting) svg bubble menus svg authoring guidelines an overview of the mozilla svg project frequently asked questions regarding svg and mozilla svg as an image svg animation with smil svg art gallery animation and interactions like html, svg has a document model (dom) and events, and is accessible from javascript. this allows developers to create rich animations and interactive images. some real eye-candy svg at svg-wow.org firefox extension (grafox) to add a subset of smil animation support interactive photos manipulation html transformations using svg's foreignobject mapping, charting, games & 3d experiments while a little svg can go a long way to enhanced web content, here are some examples of heavy svg u...
How to fix a website with blocked mixed content - Web security
this page explains what you should be aware of as a web developer. your website may break if your website delivers https pages, all active mixed content delivered via http on this pages will be blocked by default. consequently, your website may appear broken to users (if iframes or plugins don't load, etc.). passive mixed content is displayed by default, but users can set a preference to block this type of content, as well. ...
XML introduction - XML: Extensible Markup Language
gs. xml declaration xml - declaration is not a tag. it is used for the transmission of the meta-data of a document. <?xml version="1.0" encoding="utf-8"?> attributes: version : used version xml in this document. encoding : used encoding in this document. comments <!-- comment --> "correct" xml (valid and well-formed) Сorrect design rules for an xml document to be correct, the following conditions must be fulfilled: document must be well-formed. document must conform to all xml syntax rules. document must conform to semantic rules, which are usually set in an xml schema or a dtd (document type definition). example <?xml version="1.0" encoding="utf-8"?> <message> <warning> hello world <!--missing </warning> --> </message> now let's look at a corrected...
Comparison of CSS Selectors and XPath - XPath
ent the difference between css selectors and xpath for web developers to be able to better choose the right tool for the right job. ...
current - XPath
nstruction. syntax current() returns a node-set containing only the current node. notes this function is an xslt-specific addition to xpath. it is not a part of the core xpath function library. for an outermost expression (an expression not occurring within another expression), the current node is always the same as the context node (which will be returned by the . or self syntax). the following two are symantically equivalent. <xsl:value-of select="current()"/> <xsl:value-of select="."/> in an inner expression (e.g. in square brackets), the current node is still the same as it would have been in an outermost expression. thus within all of the following three expressions the current function (not the entire expressions) returns the same node. moreover, the latter two are semantic...
string - XPath
lements, exslt functions, xpath functions, xpath axes the string function converts the given argument to a string. syntax string( [object] ) arguments object(optional) the object to convert to a string. if omitted, the context node is used. returns a string notes if the object is a node-set, the string value of the first node in the set is returned. a number is converted as follows: nan is converted to the string nan. positive zero is converted to the string 0. negative zero is converted to the string 0. positive infinity is converted to the string infinity. negative infinity is converted to the string -infinity. decimal numbers between -1 and 1 are converted to a string with a single leading 0 before the decimal point. boolean true is converted to ...
translate - XPath
occurrence of the first character in abc that appears in string. returns the translated string. notes xpath notes that the translate function is not a sufficient solution for case conversion in all languages. a future version of xpath may provide additional functions for case conversion. however, this is the closest we have at present to a function that can convert a string to uppercase or lowercase. example <xsl:value-of select="translate('the quick brown fox.', 'abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz')" /> output the quick brown fox. if abc is longer than xyz, then every occurrence of characters in abc that do not have a corresponding character in xyz will be removed. example <xsl:value-of select="translate('the quick brown fox.', 'brown', 'red')" /> o...
Functions - XPath
for further information on using xpath/xslt functions, please see the for further reading page. ...
Index - XPath
Web › XPath › Index
ute node is an element node, but attribute nodes are not the children of their parents. 8 descendant-or-self axe, xpath the descendant-or-self axis indicates the context node and all of its descendants. attribute and namespace nodes are not included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents. 9 following axe, xpath the following axis indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes. 10 following-sibling axe, xpath the following-sibling axis indicates all the nodes that have the same parent as the context node and appear after the context node in the source document. 11 namespace axe, ...
<xsl:apply-imports> - XSLT: Extensible Stylesheet Language Transformations
xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:apply-imports> element is fairly arcane, used mostly in complex stylesheets. import precedence requires that template rules in main stylesheets have higher precedence than template rules in imported stylesheets. sometimes, however, it is useful to be able to force the processor to use a template rule from the (lower precedence) imported stylesheet rather than an equivalent rule in the main stylesheet. syntax <xsl:apply-imports/> required attributes none. optional attributes none. type instruction, appears within a template. defined xslt, section 5.6. gecko support supported. ...
<xsl:copy> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › copy
it does not copy any children or attributes of the current node. syntax <xsl:copy use-attribute-sets=list-of-names> template </xsl:copy> required attributes none. optional attributes use-attribute-sets lists attribute sets that should be applied to the output node, if it is an element. names of the sets should be separated with whitespace characters. ...
<xsl:import> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › import
this is in contrast to <xsl:include> where the contents of the included stylesheet have exactly the same precedence as the contents of the including stylesheet. ...
<xsl:text> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › text
, exslt functions, xpath functions, xpath axes the <xsl:text> element writes literal text to the output tree. it may contain #pcdata, literal text, and entity references. syntax <xsl:text disable-output-escaping="yes" | "no"> text </xsl:text> required attributes none. optional attributes disable-output-escaping (netscape does not serialize the result of transformation - the "output" below - so this attribute is essentially irrelevant in context. to output html-entities, use numerical values instead, eg &#160; for &nbsp;) specifies whether special characters are escaped when written to the output. the available values are "yes" or "no". if "yes" is set, for example, the character > is output as >, not as &gt;. type instruction, appears within a template. defined xslt, section...
<xsl:value-of> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › value-of
th expression, converts it to a string, and writes that string to the result tree. syntax <xsl:value-of select=expression disable-output-escaping="yes" | "no" /> required attributes select specifies the xpath expression to be evaluated and written to the output tree. optional attributes disable-output-escaping (netscape does not serialize the result of transformation - the "output" below - so this attribute is essentially irrelevant in context. to output html-entities, use numerical values instead, eg &#160 for &nbsp) specifies whether special characters are escaped when written to the output. the available values are "yes" or "no". if "yes" is set, for example, the character > is output as >, not as "&gt". type instruction, appears with a template. defined xslt, section 7.
Resources - XSLT: Extensible Stylesheet Language Transformations
...
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
the javascript loads the .xsl file only on the first sort and sets the xslloaded variable to true once it has finished loading the file. using the xsltprocessor.getparameter() method, the code can figure whether to sort in ascending or descending order. it defaults to ascending if the parameter is empty (the first time the sorting happens, as there is no value for it in the xslt file). the sorting value is set using xsltprocessor.setparameter(). ...
Basic Example - XSLT: Extensible Stylesheet Language Transformations
opy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet> the example loads using synchronous xmlhttprequest both the .xsl (xslstylesheet) and the .xml (xmldoc) files into memory. the .xsl file is then imported (xsltprocessor.importstylesheet(xslstylesheet)) and the transformation run (xsltprocessor.transformtofragment(xmldoc, document)). this allows fetching of data after the page has been loaded, without initiating a fresh page load. figure 6 : example var xslstylesheet; var xsltprocessor = new xsltprocessor(); var mydom; var xmldoc; function init(){ // load the xslt file, example1.xsl var myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "example1.xsl", false); myxmlhttprequest.send(null); xslstylesheet...
Introduction - XSLT: Extensible Stylesheet Language Transformations
uction with modern browsers supporting xslt, developers can now use javascript to access the power that xslt provides. javascript can enable a web application to load xml data, process it via xslt into a presentable form and then add it into an existing document. since the xml data loaded only contains the raw information without any presentation data, it can load quickly even on dialup. xslt allows the author to directly manipulate the structure of a document. for example, it permits the rearranging and sorting of elements; it also provides more fine-grained control of the resulting document's structure. as of mozilla 1.2, gecko enables javascript to create xslt processors. this article covers xslt/javascript bindings in gecko. they are not available in netscape 7.0x however are available...
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
ml 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 clone all descendants as well (a deep clone). the cloned dom can then be easily inserted into the xml document using node.appendchild(), as shown in figure 2. figure 2 : creating an xml document...
Exported WebAssembly functions - WebAssembly
same results. they are real functions in the previous example, the return value of each table.prototype.get() call is an exported webassembly function — exactly what we have been talking about. it is worth noting that these are real javascript functions, in addition to being wrappers for webassembly functions. if you load the above example in a webassembly-supporting browser, and run the following lines in your console: var testfunc = othertable.get(0); typeof testfunc; you'll get the result function returned. you can then go on to do pretty much anything to this function that you can do to other functions in javascript — call(), bind(), etc. testfunc.tostring() returns an interesting result: function 0() { [native code] } this gives you more of an idea of its wrapper-type nat...
Loading and running WebAssembly code - WebAssembly
(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, 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 ...